| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "net/http" |
| 9 | "sync/atomic" |
| 10 | "testing" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | func usageServer(t *testing.T, n int) (*Server, claudeAccountList) { |
| 15 | t.Helper() |
| 16 | s := testServer(t) |
| 17 | s.ready = true |
| 18 | t.Cleanup(func() { s.beginClose(); s.activities.Wait() }) |
| 19 | list := claudeAccountList{Accounts: []claudeAccount{}} |
| 20 | for i := 1; i <= n; i++ { |
| 21 | id := fmt.Sprintf("%024x", i) |
| 22 | list.Accounts = append(list.Accounts, claudeAccount{ID: id, Source: "managed", Status: "ready", Email: id + "@example.org", Enabled: true}) |
| 23 | } |
| 24 | if err := s.saveClaudeAccounts(list); err != nil { |
| 25 | t.Fatal(err) |
| 26 | } |
| 27 | s.claudeAccounts.probe = func(_ context.Context, id string) (claudeGuestSnapshot, error) { |
| 28 | if id == "default" { |
| 29 | return claudeGuestSnapshot{}, nil |
| 30 | } |
| 31 | return claudeGuestSnapshot{LoggedIn: true, Email: id + "@example.org"}, nil |
| 32 | } |
| 33 | return s, list |
| 34 | } |
| 35 | |
| 36 | func TestClaudeUsagePanelAndManualRefreshUseOfficialProbe(t *testing.T) { |
| 37 | s, list := usageServer(t, 2) |
| 38 | list.Accounts[1].Enabled = false |
| 39 | if err := s.saveClaudeAccounts(list); err != nil { |
| 40 | t.Fatal(err) |
| 41 | } |
| 42 | var calls atomic.Int32 |
| 43 | var mode atomic.Int32 |
| 44 | now := time.Now().Unix() |
| 45 | s.claudeAccounts.usageProbe = func(_ context.Context, id, subject string) (claudeGuestSnapshot, error) { |
| 46 | calls.Add(1) |
| 47 | email := id + "@example.org" |
| 48 | if claudeIdentityHash(email, "") != subject { |
| 49 | t.Errorf("missing or misbound expected identity") |
| 50 | } |
| 51 | r := claudeGuestSnapshot{LoggedIn: true, Email: email} |
| 52 | switch mode.Load() { |
| 53 | case 0: |
| 54 | r.UsageStatus = "reported" |
| 55 | r.Quota = &claudeQuota{ObservedAt: now - 120, FiveHour: &claudeWindow{UsedPercentage: 40, ResetsAt: now + 3600}, SevenDay: &claudeWindow{UsedPercentage: 61, ResetsAt: now + 86400}} |
| 56 | case 1: |
| 57 | r.UsageStatus = "partial" |
| 58 | r.Quota = &claudeQuota{ObservedAt: now - 30, FiveHour: &claudeWindow{UsedPercentage: 45}} |
| 59 | case 2: |
| 60 | return claudeGuestSnapshot{}, errors.New("simulated guest failure") |
| 61 | case 3: |
| 62 | r.UsageStatus = "unavailable" |
| 63 | case 4: |
| 64 | r.UsageStatus = "cached" |
| 65 | r.Quota = &claudeQuota{ObservedAt: now - 200, FiveHour: &claudeWindow{UsedPercentage: 7, ResetsAt: now + 3600}} |
| 66 | case 6: |
| 67 | r.UsageStatus = "not_applicable" |
| 68 | case 5: |
| 69 | r.UsageStatus = "reported" |
| 70 | r.Email = "[email protected]" |
| 71 | r.Quota = &claudeQuota{ObservedAt: now, FiveHour: &claudeWindow{UsedPercentage: 99, ResetsAt: now + 999}} |
| 72 | } |
| 73 | return r, nil |
| 74 | } |
| 75 | panel := func(method, path, body string) claudePanel { |
| 76 | t.Helper() |
| 77 | w := request(s, method, path, s.origin, body, true) |
| 78 | var v claudePanel |
| 79 | if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &v) != nil { |
| 80 | t.Fatalf("status %d: %s", w.Code, w.Body) |
| 81 | } |
| 82 | s.activities.Wait() |
| 83 | return v |
| 84 | } |
| 85 | panel("GET", "/api/claude-accounts", "") |
| 86 | panel("GET", "/api/claude-accounts?panel=visible", "") |
| 87 | if calls.Load() != 0 { |
| 88 | t.Fatal("passive GET ran /usage") |
| 89 | } |
| 90 | panel("POST", "/api/claude-accounts", `{"action":"usage_panel"}`) |
| 91 | if calls.Load() != 2 { |
| 92 | t.Fatalf("opening a panel checked %d accounts", calls.Load()) |
| 93 | } |
| 94 | panel("POST", "/api/claude-accounts", `{"action":"usage_panel"}`) |
| 95 | panel("GET", "/api/claude-accounts?panel=visible", "") |
| 96 | if calls.Load() != 2 { |
| 97 | t.Fatal("reopen/read amplified upstream traffic") |
| 98 | } |
| 99 | body := `{"action":"refresh","id":"` + list.Accounts[0].ID + `"}` |
| 100 | for i, status := range []string{"partial", "error", "unavailable", "cached", "identity_changed", "not_applicable"} { |
| 101 | mode.Store(int32(i + 1)) |
| 102 | v := panel("POST", "/api/claude-accounts", body) |
| 103 | a := v.Accounts[0] |
| 104 | if a.UsageStatus != status || a.UsageCheckedAt < now || a.Quota.FiveHour.UsedPercentage != 45 || a.Quota.FiveHour.ObservedAt != now-30 || a.Quota.SevenDay.ObservedAt != now-120 || a.Quota.SevenDay.UsedPercentage != 61 { |
| 105 | t.Fatalf("%s replaced the last valid observation: %+v %+v", status, a, a.Quota) |
| 106 | } |
| 107 | if v.Accounts[1].UsageStatus != "reported" || v.Accounts[1].Quota.FiveHour.UsedPercentage != 40 { |
| 108 | t.Fatal("manual refresh affected unrelated account") |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | func TestClaudeUsageUnregisteredDefaultRequiresTheDisplayedIdentity(t *testing.T) { |
| 114 | s, _ := usageServer(t, 0) |
| 115 | a := claudeGuestSnapshot{LoggedIn: true, Email: "[email protected]", Organization: "team"} |
| 116 | current := a |
| 117 | s.claudeAccounts.probe = func(context.Context, string) (claudeGuestSnapshot, error) { return current, nil } |
| 118 | calls := 0 |
| 119 | s.claudeAccounts.usageProbe = func(_ context.Context, id, subject string) (claudeGuestSnapshot, error) { |
| 120 | calls++ |
| 121 | if id != "default" || subject != a.subject() { |
| 122 | t.Error("unexpected default identity") |
| 123 | } |
| 124 | r := a |
| 125 | r.UsageStatus = "partial" |
| 126 | r.Quota = &claudeQuota{ObservedAt: time.Now().Unix() - 20, FiveHour: &claudeWindow{UsedPercentage: 58}} |
| 127 | return r, nil |
| 128 | } |
| 129 | wOpen := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"usage_panel"}`, true) |
| 130 | if wOpen.Code != 200 { |
| 131 | t.Fatal(wOpen.Code, wOpen.Body) |
| 132 | } |
| 133 | s.activities.Wait() |
| 134 | if calls != 1 { |
| 135 | t.Fatal("panel did not proactively check detected, unregistered default") |
| 136 | } |
| 137 | body := `{"action":"refresh_default","identity":"` + a.subject() + `"}` |
| 138 | w := request(s, "POST", "/api/claude-accounts", s.origin, body, true) |
| 139 | var v claudePanel |
| 140 | if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &v) != nil || len(v.Accounts) != 0 || v.Detected == nil || v.Detected.Quota == nil || v.Detected.Quota.FiveHour.UsedPercentage != 58 || v.Detected.UsageStatus != "partial" { |
| 141 | t.Fatal(w.Code, w.Body.String()) |
| 142 | } |
| 143 | current = claudeGuestSnapshot{LoggedIn: true, Email: "[email protected]"} |
| 144 | if w = request(s, "POST", "/api/claude-accounts", s.origin, body, true); w.Code != 409 || calls != 2 { |
| 145 | t.Fatal("stale A triggered usage for B", w.Code, calls) |
| 146 | } |
| 147 | v, _, err := s.claudePanelView(context.Background()) |
| 148 | if err != nil || v.Detected == nil || v.Detected.Quota != nil || v.Detected.UsageStatus != "" { |
| 149 | t.Fatal("B inherited A's readings", v, err) |
| 150 | } |
| 151 | current = a |
| 152 | if err := s.joinClaudeDefault(context.Background(), a.subject()); err != nil { |
| 153 | t.Fatal(err) |
| 154 | } |
| 155 | saved, _ := s.loadClaudeAccounts() |
| 156 | if saved.Accounts[0].Quota == nil || saved.Accounts[0].Quota.FiveHour.UsedPercentage != 58 || saved.Accounts[0].UsageStatus != "partial" { |
| 157 | t.Fatal("joining lost this identity's last reading") |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | func TestClaudeUsageBatchBoundedAndCancellable(t *testing.T) { |
| 162 | for _, how := range []string{"lock", "stop"} { |
| 163 | t.Run(how, func(t *testing.T) { |
| 164 | s, list := usageServer(t, 40) |
| 165 | entered := make(chan string, 40) |
| 166 | release := make(chan struct{}) |
| 167 | var calls atomic.Int32 |
| 168 | s.claudeAccounts.usageProbe = func(ctx context.Context, id, subj string) (claudeGuestSnapshot, error) { |
| 169 | calls.Add(1) |
| 170 | entered <- id |
| 171 | select { |
| 172 | case <-ctx.Done(): |
| 173 | return claudeGuestSnapshot{}, ctx.Err() |
| 174 | case <-release: |
| 175 | } |
| 176 | return claudeGuestSnapshot{LoggedIn: true, Email: id + "@example.org", UsageStatus: "unavailable"}, nil |
| 177 | } |
| 178 | open := func() { |
| 179 | w := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"usage_panel"}`, true) |
| 180 | if w.Code != 200 { |
| 181 | t.Fatal(w.Code, w.Body) |
| 182 | } |
| 183 | } |
| 184 | open() |
| 185 | if id := <-entered; id != list.Accounts[0].ID { |
| 186 | t.Fatal("wrong account at queue start") |
| 187 | } |
| 188 | open() |
| 189 | ctx, cancel := context.WithTimeout(context.Background(), 25*time.Millisecond) |
| 190 | defer cancel() |
| 191 | if err := s.refreshClaudeUsage(ctx, claudeAccountInput{Action: "refresh", ID: list.Accounts[0].ID}); !errors.Is(err, context.DeadlineExceeded) { |
| 192 | t.Fatal("same-account check did not join existing call", err) |
| 193 | } |
| 194 | second := make(chan error, 1) |
| 195 | go func() { |
| 196 | second <- s.refreshClaudeUsage(context.Background(), claudeAccountInput{Action: "refresh", ID: list.Accounts[1].ID}) |
| 197 | }() |
| 198 | <-entered |
| 199 | body := `{"action":"refresh","id":"` + list.Accounts[2].ID + `"}` |
| 200 | if w := request(s, "POST", "/api/claude-accounts", s.origin, body, true); w.Code != http.StatusConflict { |
| 201 | t.Fatal("per-account probes exceeded global limit", w.Code) |
| 202 | } |
| 203 | if how == "lock" { |
| 204 | s.account.lock() |
| 205 | } else { |
| 206 | s.mu.Lock() |
| 207 | s.ready = false |
| 208 | s.mu.Unlock() |
| 209 | } |
| 210 | close(release) |
| 211 | <-second |
| 212 | s.activities.Wait() |
| 213 | got, _ := s.loadClaudeAccounts() |
| 214 | if calls.Load() != 2 { |
| 215 | t.Fatalf("after %s, started %d commands", how, calls.Load()) |
| 216 | } |
| 217 | for _, a := range got.Accounts { |
| 218 | if a.UsageCheckedAt != 0 { |
| 219 | t.Fatal("wrote late results after", how) |
| 220 | } |
| 221 | } |
| 222 | }) |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | func TestClaudeUnknownResetOnlyBlocksWhileFresh(t *testing.T) { |
| 227 | now := time.Now() |
| 228 | a := claudeAccount{Quota: &claudeQuota{FiveHour: &claudeWindow{UsedPercentage: 100, ObservedAt: now.Unix()}}} |
| 229 | if _, ok := a.headroom(now); ok { |
| 230 | t.Fatal("ignored exhausted window without a known reset") |
| 231 | } |
| 232 | if room, ok := a.headroom(now.Add(claudeQuotaFresh + time.Second)); !ok || room != -1 { |
| 233 | t.Fatal("treated missing reset as permanent exhaustion", room, ok) |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | func TestClaudeUsageHiddenPanelStopsDispatching(t *testing.T) { |
| 238 | s, _ := usageServer(t, 4) |
| 239 | entered, release := make(chan struct{}), make(chan struct{}) |
| 240 | var calls atomic.Int32 |
| 241 | s.claudeAccounts.usageProbe = func(_ context.Context, id, subject string) (claudeGuestSnapshot, error) { |
| 242 | if calls.Add(1) == 1 { |
| 243 | close(entered) |
| 244 | <-release |
| 245 | } |
| 246 | return claudeGuestSnapshot{LoggedIn: true, Email: id + "@example.org", UsageStatus: "unavailable"}, nil |
| 247 | } |
| 248 | w := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"usage_panel"}`, true) |
| 249 | if w.Code != 200 { |
| 250 | t.Fatal(w.Code, w.Body) |
| 251 | } |
| 252 | <-entered |
| 253 | s.claudeAccounts.mu.Lock() |
| 254 | s.claudeAccounts.panelUntil = time.Now().Add(-time.Second) |
| 255 | s.claudeAccounts.mu.Unlock() |
| 256 | |
| 257 | w = request(s, "GET", "/api/claude-accounts", "", "", true) |
| 258 | if w.Code != 200 { |
| 259 | t.Fatal(w.Code, w.Body) |
| 260 | } |
| 261 | close(release) |
| 262 | s.activities.Wait() |
| 263 | if calls.Load() != 1 { |
| 264 | t.Fatal("hidden panel kept issuing upstream queries", calls.Load()) |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | func TestClaudeUsageKeepsExpiredHistoricalWindowsForBothSources(t *testing.T) { |
| 269 | s, list := usageServer(t, 1) |
| 270 | now := time.Now() |
| 271 | history := &claudeQuota{ObservedAt: now.Add(-time.Hour).Unix(), FiveHour: &claudeWindow{UsedPercentage: 100, ResetsAt: now.Add(-time.Minute).Unix()}, SevenDay: &claudeWindow{UsedPercentage: 63, ResetsAt: now.Add(time.Hour).Unix()}} |
| 272 | list.Accounts[0].mergeQuota(history, now) |
| 273 | if err := s.saveClaudeAccounts(list); err != nil { |
| 274 | t.Fatal(err) |
| 275 | } |
| 276 | candidate := claudeGuestSnapshot{LoggedIn: true, Email: "[email protected]", Quota: history} |
| 277 | |
| 278 | s.claudeAccounts.probe = func(_ context.Context, id string) (claudeGuestSnapshot, error) { |
| 279 | if id == "default" { |
| 280 | return candidate, nil |
| 281 | } |
| 282 | return claudeGuestSnapshot{LoggedIn: true, Email: list.find(id).Email}, nil |
| 283 | } |
| 284 | if _, _, err := s.claudePanelView(context.Background()); err != nil { |
| 285 | t.Fatal(err) |
| 286 | } |
| 287 | candidate.Quota = nil |
| 288 | s.claudeAccounts.usageProbe = func(_ context.Context, id, expected string) (claudeGuestSnapshot, error) { |
| 289 | if id == "default" { |
| 290 | return claudeGuestSnapshot{LoggedIn: true, Email: candidate.Email, UsageStatus: "unavailable"}, nil |
| 291 | } |
| 292 | return claudeGuestSnapshot{LoggedIn: true, Email: list.find(id).Email, UsageStatus: "unavailable"}, nil |
| 293 | } |
| 294 | for _, body := range []string{`{"action":"refresh","id":"` + list.Accounts[0].ID + `"}`, `{"action":"refresh_default","identity":"` + candidate.subject() + `"}`} { |
| 295 | w := request(s, "POST", "/api/claude-accounts", s.origin, body, true) |
| 296 | if w.Code != 200 { |
| 297 | t.Fatal(w.Code, w.Body) |
| 298 | } |
| 299 | s.activities.Wait() |
| 300 | } |
| 301 | view, _, err := s.claudePanelView(context.Background()) |
| 302 | if err != nil || view.Detected == nil { |
| 303 | t.Fatal(view, err) |
| 304 | } |
| 305 | for _, q := range []*claudeQuota{view.Accounts[0].Quota, view.Detected.Quota} { |
| 306 | if q == nil || q.FiveHour == nil || q.SevenDay == nil || q.FiveHour.UsedPercentage != 100 || q.FiveHour.ObservedAt != history.ObservedAt || q.SevenDay.ObservedAt != history.ObservedAt { |
| 307 | t.Fatal("missing read discarded or retimestamped historical quota", q) |
| 308 | } |
| 309 | if _, eligible := (claudeAccount{Quota: q}).headroom(now); !eligible { |
| 310 | t.Fatal("closed 5h window still blocked allocation") |
| 311 | } |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | func TestClaudeUsageFailedBatchOnlyRetriesOnOpeningAfterDebounce(t *testing.T) { |
| 316 | s, list := usageServer(t, 1) |
| 317 | var calls atomic.Int32 |
| 318 | s.claudeAccounts.usageProbe = func(context.Context, string, string) (claudeGuestSnapshot, error) { |
| 319 | calls.Add(1) |
| 320 | return claudeGuestSnapshot{}, errors.New("unavailable") |
| 321 | } |
| 322 | get := func() claudePanel { |
| 323 | w := request(s, "GET", "/api/claude-accounts?panel=visible", "", "", true) |
| 324 | s.activities.Wait() |
| 325 | var v claudePanel |
| 326 | if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &v) != nil { |
| 327 | t.Fatal(w.Code, w.Body) |
| 328 | } |
| 329 | return v |
| 330 | } |
| 331 | open := func() claudePanel { |
| 332 | w := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"usage_panel"}`, true) |
| 333 | s.activities.Wait() |
| 334 | var v claudePanel |
| 335 | if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &v) != nil { |
| 336 | t.Fatal(w.Code, w.Body) |
| 337 | } |
| 338 | return v |
| 339 | } |
| 340 | open() |
| 341 | if v := get(); v.UsagePanelRunning || v.Accounts[0].UsageStatus != "error" || v.Accounts[0].UsageChecking { |
| 342 | t.Fatal("failed batch never ended", v) |
| 343 | } |
| 344 | if v := open(); v.UsagePanelRunning || calls.Load() != 1 { |
| 345 | t.Fatal("recent failure started an empty batch") |
| 346 | } |
| 347 | list, _ = s.loadClaudeAccounts() |
| 348 | list.Accounts[0].UsageCheckedAt = time.Now().Add(-61 * time.Second).Unix() |
| 349 | if err := s.saveClaudeAccounts(list); err != nil { |
| 350 | t.Fatal(err) |
| 351 | } |
| 352 | if v := get(); v.UsagePanelRunning || calls.Load() != 1 { |
| 353 | t.Fatal("ordinary visible poll restarted an expired failed batch") |
| 354 | } |
| 355 | open() |
| 356 | if calls.Load() != 2 || get().UsagePanelRunning { |
| 357 | t.Fatal("did not retry on the next real panel open") |
| 358 | } |
| 359 | } |