package claude import ( "bytes" "context" "log" "os" "path/filepath" "strings" "testing" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) func writeLogin(t *testing.T, profile, email, uuid, token string) { t.Helper() writeFile(t, filepath.Join(profile, ".credentials.json"), `{"claudeAiOauth":{"accessToken":"access-`+token+`","refreshToken":"refresh-`+token+`","expiresAt":1,"subscriptionType":"pro","accountUuid":"`+uuid+`"}}`) writeFile(t, filepath.Join(profile, ".claude.json"), "{\n \"numStartups\": 3,\n \"oauthAccount\": {\"accountUuid\":\""+uuid+"\",\"emailAddress\":\""+email+"\",\"organizationName\":\"Org\"}\n}") } func TestUseAccountMovesTheHomesChatsToTheNewAccountQuota(t *testing.T) { chat := directoryChat(t) var logs bytes.Buffer log.SetOutput(&logs) defer log.SetOutput(os.Stderr) profile := t.TempDir() directory := t.TempDir() writeFile(t, filepath.Join(directory, ".envrc"), "export CLAUDE_CONFIG_DIR=...\n") writeFile(t, filepath.Join(directory, ".envrc.allowed"), "") writeFile(t, filepath.Join(directory, ".envrc.json"), `{"CLAUDE_CONFIG_DIR":"`+profile+`"}`) ctx := context.Background() writeLogin(t, profile, "a@example.invalid", "uuid-a", "a1") if _, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccountSave, ""); err != nil { t.Fatal(err) } writeLogin(t, profile, "b@example.invalid", "uuid-b", "b1") if _, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccountSave, "B"); err != nil { t.Fatal(err) } // Two chats on the home are on b, which is out of quota; a third chat // elsewhere is on another account. oldKey := accountKeyFor("b@example.invalid", "Org") limited := &protocol.ChatAccountUsage{Harness: quotaHarness, Windows: []protocol.ChatQuotaWindow{{ID: "five_hour", Label: "5-hour", UsedPercent: 100, ResetsAt: 1}}} chat.quotas = map[string]*protocol.ChatAccountUsage{oldKey: limited} here := chat.sessionFor("11111111-1111-4111-8111-111111111111", directory) alsoHere := chat.sessionFor("22222222-2222-4222-8222-222222222222", directory) elsewhere := chat.sessionFor("33333333-3333-4333-8333-333333333333", t.TempDir()) for _, s := range []*session{here, alsoHere} { s.account = accountIdentity{key: oldKey, plan: "pro"} } elsewhere.account = accountIdentity{key: "other"} frames := subscribe(t, chat, here.id) list, err := chat.ClaudeAccounts(ctx, here.id, "", protocol.ClaudeAccountUse, "a@example.invalid") if err != nil { t.Fatal(err) } if list.Active == nil || list.Active.Email != "a@example.invalid" || list.Usage == nil || list.Usage.SwitchedAt == 0 || len(list.Usage.Windows) != 0 { t.Fatalf("use reply = %+v usage=%+v", list, list.Usage) } newKey := accountKeyFor("a@example.invalid", "Org") if here.account.key != newKey || alsoHere.account.key != newKey || elsewhere.account.key != "other" { t.Fatalf("keys = %q %q %q", here.account.key, alsoHere.account.key, elsewhere.account.key) } pushed := waitFrame(t, frames, "switched usage", func(frame protocol.ChatEventFrame) bool { return frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.Account != nil && frame.Usage.Account.SwitchedAt != 0 }).Usage.Account if len(pushed.Windows) != 0 { t.Fatalf("the new account inherited the old quota: %+v", pushed) } // usage.account names the account the home is signed in to now. if list.Usage.Email != "a@example.invalid" || pushed.Email != "a@example.invalid" || pushed.Organization != "Org" { t.Fatalf("switched usage names %q / %q (%q)", list.Usage.Email, pushed.Email, pushed.Organization) } data, _ := os.ReadFile(filepath.Join(profile, ".credentials.json")) if !strings.Contains(string(data), "refresh-a1") { t.Fatal("credentials not switched") } for _, secret := range []string{"access-", "refresh-"} { if strings.Contains(logs.String(), secret) { t.Fatalf("log carries a token: %s", logs.String()) } } // A later quota report on the new account keeps the switch. known := mergeRateLimit(chat.quotas[newKey], []byte(`{"rateLimitType":"five_hour","utilization":0.2,"resetsAt":1900000000}`), "pro", time.Now()) if known == nil || known.SwitchedAt != pushed.SwitchedAt { t.Fatalf("merge dropped the switch: %+v", known) } } func TestAccountsRefusedWithoutAClaudeHome(t *testing.T) { chat := directoryChat(t) t.Setenv("CLAUDE_CONFIG_DIR", "") os.Unsetenv("CLAUDE_CONFIG_DIR") if _, err := chat.ClaudeAccounts(context.Background(), "s", t.TempDir(), protocol.ClaudeAccounts, ""); err != ErrNoConfigDir { t.Fatalf("err = %v", err) } }