package claude import ( "context" "errors" "path/filepath" "sync" "testing" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) func TestUsageLimitRefusalIsReportedOnceWithItsAccount(t *testing.T) { chat := testChat(t) refusals := make(chan UsageRefusal, 4) chat.OnUsageRefused(func(refusal UsageRefusal) { refusals <- refusal }) created := newCreatedChat(t, chat) frames := subscribe(t, chat, created.ID) ended := func(what string) { waitFrame(t, frames, what, func(frame protocol.ChatEventFrame) bool { return frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded }) } if err := chat.Prompt(context.Background(), created.ID, "hello"); err != nil { t.Fatal(err) } ended("an ordinary turn's end") if err := chat.Prompt(context.Background(), created.ID, "usage-limit"); err != nil { t.Fatal(err) } ended("the refused turn's end") select { case refusal := <-refusals: if refusal.SessionID != created.ID || refusal.MessageID != "refusal-2" || refusal.Email != "fixture@example.invalid" || refusal.TurnID == "" || refusal.Directory != created.Directory { t.Fatalf("refusal = %+v", refusal) } case <-time.After(5 * time.Second): t.Fatal("the refusal was not reported") } select { case extra := <-refusals: t.Fatalf("a second refusal was reported: %+v", extra) case <-time.After(200 * time.Millisecond): } // The rejected rate_limit_event says when the limit ends. chat.quotaMu.Lock() until := chat.rejectedUntil["fixture@example.invalid"] chat.quotaMu.Unlock() if !until.Equal(time.Unix(1900000000, 0)) { t.Fatalf("rejected until %v", until) } } func TestUsageRefusalNeedsTheLimitText(t *testing.T) { s := &session{id: "s", turnID: "t1", account: accountIdentity{email: "a@example.invalid"}} s.beginTurnLocked() s.noteUsageRefusalLocked(lineEnvelope{}, messageBody{}, []contentBlock{{Type: "text", Text: "Done; nothing hit any limit."}}, "m1") if _, refused := s.takeUsageRefusalLocked(lineEnvelope{IsError: true, Result: "Done"}); refused { t.Fatal("an ordinary error result was taken for a usage refusal") } // The older CLI's text on the result alone is enough. s.turnID = "t2" refusal, refused := s.takeUsageRefusalLocked(lineEnvelope{IsError: true, Result: "Claude AI usage limit reached|1900000000"}) if !refused || refusal.Email != "a@example.invalid" || refusal.TurnID != "t2" { t.Fatalf("refusal = %+v %v", refusal, refused) } } // accountsHome is a chat directory whose Claude home has saved accounts a-e, // signed in as a. func accountsHome(t *testing.T, chat *Chat) string { t.Helper() 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+`"}`) for _, name := range []string{"e", "d", "c", "b", "a"} { writeLogin(t, profile, name+"@example.invalid", "uuid-"+name, name+"1") if _, err := chat.ClaudeAccounts(context.Background(), "s", directory, protocol.ClaudeAccountSave, ""); err != nil { t.Fatal(err) } } return directory } func setQuota(chat *Chat, email string, percent float64, resetsAt int64) { chat.quotaMu.Lock() defer chat.quotaMu.Unlock() if chat.quotas == nil { chat.quotas = map[string]*protocol.ChatAccountUsage{} } chat.quotas[accountKeyFor(email, "Org")] = &protocol.ChatAccountUsage{Harness: quotaHarness, Windows: []protocol.ChatQuotaWindow{{ID: "five_hour", Label: "5-hour", UsedPercent: percent, ResetsAt: resetsAt}}} } func TestAutoSwitchMovesToTheSavedAccountWithTheMostUsageLeft(t *testing.T) { chat := directoryChat(t) directory := accountsHome(t, chat) ctx := context.Background() future := time.Now().Add(3 * time.Hour).UnixMilli() setQuota(chat, "a@example.invalid", 100, future) setQuota(chat, "b@example.invalid", 80, future) setQuota(chat, "c@example.invalid", 20, future) setQuota(chat, "d@example.invalid", 100, future) // exhausted // e has no known quota. // Two chats refused on a at once: the home switches once, to c. var wg sync.WaitGroup results := make([]AutoSwitch, 2) errs := make([]error, 2) for i := range results { wg.Add(1) go func(i int) { defer wg.Done() results[i], errs[i] = chat.AutoSwitchAccount(ctx, UsageRefusal{SessionID: "s", Directory: directory, TurnID: "t", Email: "a@example.invalid"}) }(i) } wg.Wait() if errs[0] != nil || errs[1] != nil { t.Fatalf("errs = %v", errs) } if results[0].Switched == results[1].Switched || results[0].To != "c@example.invalid" || results[1].To != "c@example.invalid" { t.Fatalf("results = %+v", results) } for _, result := range results { if result.From != "a@example.invalid" { t.Fatalf("from = %+v", result) } if result.Switched && (result.Usage == nil || result.Usage.SwitchedAt == 0) { t.Fatalf("the switch was not marked: %+v", result.Usage) } } // c is refused too: the next best known account is b; then e, whose // usage nobody knows; then nothing is left (a was refused, d is out). for _, step := range []struct{ from, to string }{{"c@example.invalid", "b@example.invalid"}, {"b@example.invalid", "e@example.invalid"}} { result, err := chat.AutoSwitchAccount(ctx, UsageRefusal{SessionID: "s", Directory: directory, TurnID: "t", Email: step.from}) if err != nil || !result.Switched || result.To != step.to { t.Fatalf("after %s: %+v %v", step.from, result, err) } } if _, err := chat.AutoSwitchAccount(ctx, UsageRefusal{SessionID: "s", Directory: directory, TurnID: "t", Email: "e@example.invalid"}); !errors.Is(err, ErrNoAccountLeft) { t.Fatalf("all exhausted: %v", err) } list, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccounts, "") if err != nil || list.Active == nil || list.Active.Email != "e@example.invalid" { t.Fatalf("active = %+v %v", list.Active, err) } } func TestAutoSwitchOffLeavesTheAccount(t *testing.T) { chat := directoryChat(t) directory := accountsHome(t, chat) ctx := context.Background() list, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccountAutoSwitch, "off") if err != nil || list.AutoSwitch { t.Fatalf("auto off = %+v %v", list, err) } if _, err := chat.AutoSwitchAccount(ctx, UsageRefusal{SessionID: "s", Directory: directory, TurnID: "t", Email: "a@example.invalid"}); !errors.Is(err, ErrAutoSwitchOff) { t.Fatalf("err = %v", err) } list, _ = chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccounts, "") if list.Active == nil || list.Active.Email != "a@example.invalid" { t.Fatalf("switched while off: %+v", list.Active) } if _, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccountAutoSwitch, "maybe"); err == nil { t.Fatal("a bad choice was accepted") } }