package claude import ( "context" "encoding/json" "reflect" "testing" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) // Shaped like Claude Code 2.1.316's SDKRateLimitEvent.rate_limit_info; // the numbers are synthetic. const unifiedRateLimit = `{"status":"allowed_warning","resetsAt":1900000000,"rateLimitType":"seven_day", "utilization":0.8,"isUsingOverage":false,"surpassedThreshold":0.75, "unifiedWindows":{"five_hour":{"utilization":0.125,"resetsAt":1899990000,"status":"allowed"}, "seven_day":{"utilization":0.8,"resetsAt":1900000000,"status":"allowed_warning","surpassedThreshold":0.75}}}` func TestMergeRateLimitReadsUnifiedWindows(t *testing.T) { now := time.UnixMilli(1_800_000_000_000) got := mergeRateLimit(nil, json.RawMessage(unifiedRateLimit), "max", now) want := &protocol.ChatAccountUsage{ Harness: "Claude Code", Source: "rate_limit_event", Plan: "max", AsOf: now.UnixMilli(), Windows: []protocol.ChatQuotaWindow{ {ID: "five_hour", Label: "5-hour", UsedPercent: 12.5, ResetsAt: 1_899_990_000_000}, {ID: "seven_day", Label: "Weekly", UsedPercent: 80, ResetsAt: 1_900_000_000_000}, }, } if !reflect.DeepEqual(got, want) { t.Fatalf("merged = %+v\nwant %+v", got, want) } } func TestMergeRateLimitKeepsUnmentionedWindowsAndIgnoresStatusOnly(t *testing.T) { now := time.UnixMilli(1_800_000_000_000) first := mergeRateLimit(nil, json.RawMessage(unifiedRateLimit), "pro", now) // A top-level-only event (older CLIs, or no unifiedWindows) updates its window. later := now.Add(time.Minute) next := mergeRateLimit(first, json.RawMessage(`{"status":"allowed","rateLimitType":"five_hour","utilization":0.5,"resetsAt":1899990000}`), "", later) if next == nil || len(next.Windows) != 2 || next.Windows[0].UsedPercent != 50 || next.Windows[1].UsedPercent != 80 { t.Fatalf("merge = %+v", next) } if next.Plan != "pro" || next.AsOf != later.UnixMilli() { t.Fatalf("plan/as_of = %q %d", next.Plan, next.AsOf) } for _, raw := range []string{ `{"status":"rejected","rateLimitType":"five_hour"}`, // no utilization: nothing to show `{"status":"allowed","rateLimitType":"overage","utilization":0.2}`, `not json`, } { if got := mergeRateLimit(first, json.RawMessage(raw), "", later); got != nil { t.Fatalf("%s merged into %+v", raw, got) } } } func TestMergeRateLimitCarriesExtraUsage(t *testing.T) { now := time.UnixMilli(1_800_000_000_000) first := mergeRateLimit(nil, json.RawMessage(unifiedRateLimit), "max", now) if first.ExtraUsage != nil { t.Fatalf("no overage fields, extra = %+v", first.ExtraUsage) } // Overage news alone updates a known report. next := mergeRateLimit(first, json.RawMessage(`{"status":"rejected","overageStatus":"allowed","isUsingOverage":true,"overageResetsAt":1901000000}`), "", now) want := &protocol.ChatExtraUsage{Status: "allowed", InUse: true, ResetsAt: 1_901_000_000_000} if next == nil || !reflect.DeepEqual(next.ExtraUsage, want) || len(next.Windows) != 2 { t.Fatalf("merge = %+v", next) } // A later window-only event keeps the last overage state. kept := mergeRateLimit(next, json.RawMessage(`{"status":"allowed","rateLimitType":"five_hour","utilization":0.5,"resetsAt":1899990000}`), "", now) if kept == nil || !reflect.DeepEqual(kept.ExtraUsage, want) { t.Fatalf("kept = %+v", kept) } if clone := kept.Clone(); clone.ExtraUsage == kept.ExtraUsage { t.Fatal("clone shares the extra usage") } off := mergeRateLimit(kept, json.RawMessage(`{"status":"rejected","overageStatus":"rejected","overageDisabledReason":"out_of_credits","isUsingOverage":false}`), "", now) if off == nil || !reflect.DeepEqual(off.ExtraUsage, &protocol.ChatExtraUsage{Status: "rejected", DisabledReason: "out_of_credits"}) { t.Fatalf("off = %+v", off) } // Without a report to attach to, overage alone shows nothing. if got := mergeRateLimit(nil, json.RawMessage(`{"overageStatus":"allowed"}`), "", now); got != nil { t.Fatalf("lone overage = %+v", got) } } func TestDecodeAccountIdentity(t *testing.T) { got := decodeAccountIdentity(json.RawMessage(`{"email":"a@example.invalid","organization":"Org","subscriptionType":"max","apiProvider":"firstParty"}`)) if got.key == "" || got.plan != "max" || got.email != "a@example.invalid" || got.organization != "Org" { t.Fatalf("identity = %+v", got) } // An API key login names no account, so nothing is shown for it. chat := &Chat{} if usage := chat.accountUsage(decodeAccountIdentity(json.RawMessage(`{"apiProvider":"firstParty","apiKeySource":"ANTHROPIC_API_KEY"}`))); usage != nil { t.Fatalf("API key usage = %+v", usage) } if empty := decodeAccountIdentity(json.RawMessage(`{}`)); empty.key != "" || empty.plan != "" { t.Fatalf("empty account = %+v", empty) } } func TestRateLimitEventReachesEverySessionOfTheAccount(t *testing.T) { t.Setenv("FAKE_CLAUDE_RATE_LIMIT", "1") chat := testChat(t) first := newCreatedChat(t, chat) frames := subscribe(t, chat, first.ID) if err := chat.Prompt(context.Background(), first.ID, "hello"); err != nil { t.Fatal(err) } // The process's start names the account before any quota is known. named := waitFrame(t, frames, "account identity", func(frame protocol.ChatEventFrame) bool { return frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.Account != nil }).Usage.Account if named.Email != "fixture@example.invalid" || named.Organization != "Fixture Org" || len(named.Windows) != 0 { t.Fatalf("account identity = %+v", named) } quota := waitFrame(t, frames, "account usage", func(frame protocol.ChatEventFrame) bool { return frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.Account != nil && len(frame.Usage.Account.Windows) > 0 }).Usage.Account if quota.Plan != "max" || quota.Email != "fixture@example.invalid" || len(quota.Windows) != 2 || quota.Windows[0].Label != "5-hour" || quota.Windows[0].UsedPercent != 42 || quota.Windows[1].Label != "Weekly" || quota.Windows[1].UsedPercent != 73.1 || quota.Windows[1].ResetsAt != 1_900_400_000_000 { t.Fatalf("account usage = %+v", quota) } // The token snapshot that follows still carries the quota. tokens := waitFrame(t, frames, "token usage", func(frame protocol.ChatEventFrame) bool { return frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.TotalTokens != nil }).Usage if tokens.Account == nil || len(tokens.Account.Windows) != 2 { t.Fatalf("token usage lost the account quota: %+v", tokens) } // A second chat on the same account learns the quota once its process // identifies the account, without a turn of its own. second := newCreatedChat(t, chat) s := chat.sessionFor(second.ID, "") if _, err := s.ensureProcess(context.Background()); err != nil { t.Fatal(err) } other := subscribe(t, chat, second.ID) replayed := waitFrame(t, other, "replayed account usage", func(frame protocol.ChatEventFrame) bool { return frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.Account != nil }).Usage if replayed.Scope != "" || replayed.TotalTokens != nil || len(replayed.Account.Windows) != 2 { t.Fatalf("replay invented token usage or lost quota: %+v", replayed) } }