Files
pipelines/internal/claude/quota_test.go
T
alan 10049b8062 Chat info: account quota per harness (Claude rate_limit_event, Codex account/rateLimits, OpenCode unsupported)
Usage frames carry optional usage.account {harness, source, plan, as_of,
windows[{id,label,used_percent,resets_at}], unsupported}. Claude Code quota
comes from its rate_limit_event stream lines and the initialize account
(plan), shared across chats on the same account. Codex reads
account/rateLimits/read once per connection (re-read when a chat opens after
5 min) and merges account/rateLimits/updated. OpenCode exposes no quota API
and says so. The app's chat info sheet shows an Account usage section with a
progress bar and reset countdown per window, Material and Cupertino.
2026-11-02 18:57:13 +00:00

106 lines
4.5 KiB
Go

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 TestDecodeAccountIdentity(t *testing.T) {
got := decodeAccountIdentity(json.RawMessage(`{"email":"a@example.invalid","organization":"Org","subscriptionType":"max","apiProvider":"firstParty"}`))
if got.key == "" || got.plan != "max" {
t.Fatalf("identity = %+v", got)
}
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)
}
quota := waitFrame(t, frames, "account usage", func(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.Account != nil
}).Usage.Account
if quota.Plan != "max" || 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)
}
}