Claude account switcher: save and switch a chat's Claude login in place

Saved accounts live under <CLAUDE_CONFIG_DIR>/pipelines-accounts/<slug>/
(0700 dir, 0600 files). Switching changes what /login changes: the
claudeAiOauth entry of .credentials.json and oauthAccount of .claude.json
(atomic temp+rename, mode and other keys kept) and the org caches /login
drops, under Claude Code's own refresh, storage and config locks, so
running CLIs continue on the new account without a restart. The active
login's rotated tokens are written back to its slot first.

Server: claude_accounts / claude_account_save / _use / _remove, chat-scoped
and Claude-only; a switch moves the home's open chats to the new account's
quota (usage.account.switched_at), clearing a reached limit.
CLI: pipelines claude-account list|save|use|remove [--dir].
App: Claude account in the chat menu, and Switch to <account> on the
usage-limit and usage-warning banners, with a confirmation snack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 15:10:08 +00:00
parent 1772100af2
commit c490f71042
33 changed files with 2958 additions and 4 deletions
+3
View File
@@ -294,6 +294,9 @@ func (a App) Run(ctx context.Context, args []string) error {
if len(args) > 0 && args[0] == "harness" {
return a.harness(ctx, args[1:])
}
if len(args) > 0 && args[0] == "claude-account" {
return a.claudeAccount(ctx, args[1:])
}
if len(args) > 0 && args[0] == "--version" {
args = append([]string{"version"}, args[1:]...)
}
+113
View File
@@ -0,0 +1,113 @@
package cli
import (
"context"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"git.a-wan.net/alan/pipelines/internal/claude"
"git.a-wan.net/alan/pipelines/internal/claudeaccounts"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
const claudeAccountUsage = "usage: pipelines claude-account list | save [name] | use <name> | remove <name> [--dir DIR] [--json]"
// claudeAccount saves and switches the Claude login of the Claude home a
// directory selects (its CLAUDE_CONFIG_DIR after direnv/mise), locally and
// without a server. It changes the same files /login does, so running Claude
// Code processes there continue on the new account.
func (a App) claudeAccount(ctx context.Context, args []string) error {
f := flag.NewFlagSet("claude-account", flag.ContinueOnError)
f.SetOutput(a.Err)
dir := f.String("dir", "", "Directory whose environment selects the Claude home (default: current directory)")
jsonMode := f.Bool("json", false, "Machine-readable JSON")
if err := parse(f, args); err != nil {
if errors.Is(err, flag.ErrHelp) {
return nil
}
return err
}
pos := f.Args()
if len(pos) == 0 {
return errors.New(claudeAccountUsage)
}
directory := *dir
if directory == "" {
wd, err := os.Getwd()
if err != nil {
return err
}
directory = wd
}
directory, err := filepath.Abs(directory)
if err != nil {
return err
}
configDir, err := claude.AccountConfigDir(ctx, workenv.Default, directory, os.Environ())
if err != nil {
return err
}
store := claudeaccounts.Store{ConfigDir: configDir}
var list protocol.ClaudeAccountList
switch {
case pos[0] == "list" && len(pos) == 1:
list, err = store.List()
case pos[0] == "save" && len(pos) <= 2:
list, err = store.Save(strings.Join(pos[1:], ""))
case pos[0] == "use" && len(pos) == 2:
list, err = store.Use(pos[1])
case pos[0] == "remove" && len(pos) == 2:
list, err = store.Remove(pos[1])
default:
return errors.New(claudeAccountUsage)
}
if err != nil {
return err
}
if *jsonMode {
return a.output(list)
}
fmt.Fprintf(a.Out, "Claude home: %s\n", list.ConfigDir)
if len(list.Accounts) == 0 {
fmt.Fprintln(a.Out, "No saved accounts.")
}
for _, account := range list.Accounts {
mark := " "
if account.Active {
mark = "*"
}
fmt.Fprintf(a.Out, "%s %s%s\n", mark, account.Name, accountDetail(account))
}
if list.Active != nil && !list.Active.Saved {
fmt.Fprintf(a.Out, "* %s (signed in, not saved; pipelines claude-account save)\n", list.Active.Email)
}
if list.Active == nil {
fmt.Fprintln(a.Out, "Signed out.")
}
if pos[0] == "use" && list.Active != nil {
fmt.Fprintf(a.Out, "Switched to %s. Running Claude Code sessions continue on it.\n", list.Active.Email)
}
return nil
}
func accountDetail(account protocol.ClaudeAccount) string {
var parts []string
if account.Email != "" && account.Email != account.Name {
parts = append(parts, account.Email)
}
if account.Organization != "" {
parts = append(parts, account.Organization)
}
if account.Plan != "" {
parts = append(parts, account.Plan)
}
if len(parts) == 0 {
return ""
}
return " (" + strings.Join(parts, ", ") + ")"
}
+78
View File
@@ -0,0 +1,78 @@
package cli
import (
"bytes"
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
func cliLogin(t *testing.T, profile, email, uuid, token string) {
t.Helper()
files := map[string]string{
".credentials.json": `{"claudeAiOauth":{"accessToken":"access-` + token + `","refreshToken":"refresh-` + token + `","subscriptionType":"max","accountUuid":"` + uuid + `"}}`,
".claude.json": `{"userID":"device","oauthAccount":{"accountUuid":"` + uuid + `","emailAddress":"` + email + `","organizationName":"Org"}}`,
}
for name, content := range files {
if err := os.WriteFile(filepath.Join(profile, name), []byte(content), 0o600); err != nil {
t.Fatal(err)
}
}
}
func TestClaudeAccountCommandSavesAndSwitches(t *testing.T) {
profile := t.TempDir()
t.Setenv("CLAUDE_CONFIG_DIR", profile)
t.Setenv(workenv.DisableEnvKey, "off")
dir := t.TempDir()
run := func(args ...string) (string, error) {
var out, errs bytes.Buffer
err := App{Out: &out, Err: &errs}.Run(context.Background(), append([]string{"claude-account"}, args...))
return out.String() + errs.String(), err
}
cliLogin(t, profile, "a@example.invalid", "uuid-a", "a1")
if out, err := run("save", "--dir", dir); err != nil || !strings.Contains(out, "* a@example.invalid (Org, max)") {
t.Fatalf("save a: %v\n%s", err, out)
}
cliLogin(t, profile, "b@example.invalid", "uuid-b", "b1")
if out, err := run("list", "--dir", dir); err != nil || !strings.Contains(out, " a@example.invalid") || !strings.Contains(out, "* b@example.invalid (signed in, not saved") {
t.Fatalf("list: %v\n%s", err, out)
}
if _, err := run("save", "work", "--dir", dir); err != nil {
t.Fatal(err)
}
out, err := run("use", "a@example.invalid", "--dir", dir, "--json")
if err != nil {
t.Fatalf("use: %v\n%s", err, out)
}
if strings.Contains(out, "access-") || strings.Contains(out, "refresh-") {
t.Fatalf("output carries a token: %s", out)
}
var list protocol.ClaudeAccountList
if err := json.Unmarshal([]byte(out), &list); err != nil {
t.Fatalf("json: %v\n%s", err, out)
}
if list.ConfigDir != profile || list.Active == nil || list.Active.Email != "a@example.invalid" || len(list.Accounts) != 2 {
t.Fatalf("use reply = %+v", list)
}
data, _ := os.ReadFile(filepath.Join(profile, ".credentials.json"))
if !strings.Contains(string(data), "refresh-a1") {
t.Fatal("credentials not switched")
}
if out, err := run("remove", "work", "--dir", dir); err != nil || strings.Contains(out, "work") {
t.Fatalf("remove: %v\n%s", err, out)
}
if _, err := run("use", "--dir", dir); err == nil || !strings.Contains(err.Error(), "usage:") {
t.Fatalf("use without a name: %v", err)
}
t.Setenv("CLAUDE_CONFIG_DIR", "")
if _, err := run("list", "--dir", dir); err == nil || !strings.Contains(err.Error(), "CLAUDE_CONFIG_DIR") {
t.Fatalf("no Claude home: %v", err)
}
}
+1
View File
@@ -38,6 +38,7 @@ var usage = map[string]string{
"stats": "stats [--json]",
"rpc": "rpc <request.json|->",
"retention": "retention report|apply [--older-than DURATION] [--keep N] [--db FILE] [--artifacts DIR] [--json] [--yes]",
"claude-account": "claude-account list | save [name] | use <name> | remove <name> [--dir DIR] [--json]",
"tui": "tui",
}
+3
View File
@@ -56,6 +56,9 @@ SERVER / INTERFACE
harness setup <claude|codex|opencode|pi>
Install check, sign-in, models and verify for one harness
harness list Installed / signed-in / configured / default for all four
claude-account list|save|use|remove
Save and switch the Claude login of this directory's
CLAUDE_CONFIG_DIR (--dir DIR); running sessions follow
tui Open the dashboard (default with no command)
serve Start native server in the foreground (Ctrl+C stops it)
service enable Configure user autostart