@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 1,906 lines 62.7 KB
Raw
1 import {
2 DEFAULT_SERVER_SETTINGS,
3 EnvironmentId,
4 ProviderDriverKind,
5 ProviderInstanceId,
6 type ServerProvider,
7 UsageLimitSourceId,
8 } from "@t3tools/contracts";
9 import { describe, expect, it } from "vite-plus/test";
10
11 import {
12 type LimitAccount,
13 displayLimitWindows,
14 cursorUsageWindowDetails,
15 collectProviderUsageLimits,
16 sameUsageLimitCommandCoverage,
17 withUsageLimitsCommands,
18 collectLimitAccounts,
19 collectExternalUsageLinks,
20 collectLimitPools,
21 elapsedShare,
22 exhaustedUsageWindow,
23 paceOf,
24 paceRemainingPercent,
25 usesChatGptSharing,
26 resolveNewThreadModelSelection,
27 } from "./usageLimits.ts";
28 import { collectLimitNotices } from "./usageLimitsCopy.ts";
29
30 const now = Date.parse("2026-09-03T12:00:00.000Z");
31
32 const window = {
33 id: "five_hour",
34 kind: "session",
35 label: "Session",
36 usedPercent: 40,
37 windowDurationMins: 300,
38 resetsAt: "2026-09-03T14:00:00.000Z",
39 } as const;
40
41 function provider(overrides: Partial<ServerProvider>): ServerProvider {
42 return {
43 instanceId: ProviderInstanceId.make("codex"),
44 driver: ProviderDriverKind.make("codex"),
45 enabled: true,
46 installed: true,
47 version: null,
48 status: "ready",
49 auth: { status: "authenticated" },
50 checkedAt: "2026-09-03T11:00:00.000Z",
51 models: [],
52 slashCommands: [],
53 skills: [],
54 ...overrides,
55 };
56 }
57
58 describe("new thread model fallback", () => {
59 const selection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6.1-sol" };
60 const fallback = { instanceId: ProviderInstanceId.make("claude"), model: "claude-fable-5-1" };
61 const limited = provider({
62 usageLimits: {
63 checkedAt: "2026-09-03T11:00:00.000Z",
64 windows: [{ ...window, usedPercent: 100 }],
65 },
66 });
67 const available = provider({
68 instanceId: fallback.instanceId,
69 driver: ProviderDriverKind.make("claudeAgent"),
70 });
71
72 const defaults = {
73 defaultSelection: selection,
74 fallbackSelection: fallback,
75 providers: [limited, available],
76 now,
77 };
78 it.each([
79 ["exhausted default", {}, fallback],
80 ["explicit selection", { explicitSelection: selection }, selection],
81 ["missing default", { defaultSelection: null }, null],
82 ["no fallback", { fallbackSelection: null }, selection],
83 ["expired window", { now: Date.parse("2026-09-04T00:00:00Z") }, selection],
84 [
85 "environment disabled",
86 {
87 settings: {
88 ...DEFAULT_SERVER_SETTINGS,
89 providerInstances: {
90 [fallback.instanceId]: { driver: available.driver, enabled: false, config: {} },
91 },
92 },
93 },
94 selection,
95 ],
96 ] as const)("resolves %s", (_name, overrides, expected) => {
97 expect(resolveNewThreadModelSelection({ ...defaults, ...overrides }).selection).toEqual(
98 expected,
99 );
100 });
101 it.each([
102 { enabled: false },
103 { installed: false },
104 { auth: { status: "unauthenticated" as const } },
105 { availability: "unavailable" as const },
106 { usageLimits: limited.usageLimits },
107 ])("rejects an unusable fallback: %j", (overrides) => {
108 expect(
109 resolveNewThreadModelSelection({
110 ...defaults,
111 providers: [limited, { ...available, ...overrides }],
112 }).selection,
113 ).toEqual(selection);
114 });
115 it.each([undefined, "invalid"])("treats an unknown reset as exhausted: %s", (resetsAt) => {
116 expect(
117 exhaustedUsageWindow(
118 provider({
119 usageLimits: {
120 checkedAt: limited.checkedAt,
121 windows: [{ ...window, usedPercent: 100, resetsAt }],
122 },
123 }),
124 now,
125 ),
126 ).toBeDefined();
127 });
128 it.each([
129 ["cursor", ["autoPercentUsed"], "claude-opus-5-5", false, undefined, undefined],
130 ["cursor", ["autoPercentUsed"], "composer-2.5", false, undefined, undefined],
131 ["cursor", ["autoPercentUsed", "apiPercentUsed"], "composer-2.5", true, undefined, undefined],
132 ["antigravity", ["gemini-weekly"], "claude-opus-5-5", false, undefined, undefined],
133 ["antigravity", ["3p-weekly"], "claude-opus-5-5", true, undefined, undefined],
134 ["antigravity", ["gemini-weekly"], "antigravity-default", true, undefined, undefined],
135 ["codex", ["individual"], "gpt-5.5", true, undefined, undefined],
136 ["opencode", ["go_weekly"], "opencode/big-pickle", false, undefined, undefined],
137 ["opencode", ["go_weekly"], "opencode-go/big-pickle", true, undefined, undefined],
138 ["opencode", ["budget_model"], "opencode/other", false, ["opencode/limited"], undefined],
139 ["opencode", ["budget_model"], "opencode/limited", true, ["opencode/limited"], undefined],
140 [
141 "opencode",
142 ["budget_set"],
143 "other/model",
144 false,
145 ["opencode/limited", "opencode/second"],
146 undefined,
147 ],
148 [
149 "opencode",
150 ["budget_set"],
151 "opencode/second",
152 true,
153 ["opencode/limited", "opencode/second"],
154 undefined,
155 ],
156 ["opencode", ["budget_empty"], "opencode/other", false, [], undefined],
157 [
158 "opencode",
159 ["budget_all"],
160 "anthropic/claude",
161 false,
162 undefined,
163 ["opencode", "console-custom"],
164 ],
165 [
166 "opencode",
167 ["budget_all"],
168 "opencode-go/model",
169 false,
170 undefined,
171 ["opencode", "console-custom"],
172 ],
173 ["opencode", ["budget_all"], "opencode/model", true, undefined, ["opencode", "console-custom"]],
174 [
175 "opencode",
176 ["budget_all"],
177 "console-custom/model",
178 true,
179 undefined,
180 ["opencode", "console-custom"],
181 ],
182 ["opencode", ["budget_all"], "opencode/model", false, undefined, []],
183 ] as const)(
184 "matches %s pools %s to %s",
185 (driver, ids, model, usesFallback, modelIds, providerIds) => {
186 const defaultSelection = { ...selection, model };
187 expect(
188 resolveNewThreadModelSelection({
189 ...defaults,
190 defaultSelection,
191 providers: [
192 provider({
193 driver: ProviderDriverKind.make(driver),
194 usageLimits: {
195 checkedAt: limited.checkedAt,
196 windows: ids.map((id) => ({
197 ...window,
198 id,
199 usedPercent: 100,
200 ...(modelIds === undefined ? {} : { modelIds }),
201 ...(providerIds === undefined ? {} : { providerIds }),
202 })),
203 },
204 }),
205 available,
206 ],
207 }).selection,
208 ).toEqual(usesFallback ? fallback : defaultSelection);
209 },
210 );
211 });
212
213 describe("pace", () => {
214 it("places the clock three fifths through a five-hour window with two hours left", () => {
215 expect(elapsedShare(window, now)).toBeCloseTo(0.6);
216 expect(paceRemainingPercent(window, now)).toBe(40);
217 expect(paceOf(window, now)).toBe("under");
218 expect(paceOf({ ...window, usedPercent: 62 }, now)).toBe("on");
219 expect(paceOf({ ...window, usedPercent: 80 }, now)).toBe("ahead");
220 });
221 });
222
223 describe("pools", () => {
224 const checkedAt = "2026-09-03T11:00:00.000Z";
225 const weekly = {
226 id: "seven_day",
227 kind: "weekly",
228 label: "Weekly",
229 windowDurationMins: 7 * 24 * 60,
230 resetsAt: "2026-09-06T12:00:00.000Z",
231 } as const;
232 const claude = ProviderDriverKind.make("claudeAgent");
233 const source = {
234 id: UsageLimitSourceId.make("hub"),
235 kind: "cliproxy" as const,
236 label: "hub",
237 checkedAt,
238 };
239 const laptop = { entry: { target: { label: "Laptop" } } };
240
241 it("merges one account reported natively on two environments and by a hub into one entry", () => {
242 const native = provider({
243 driver: claude,
244 instanceId: ProviderInstanceId.make("claude"),
245 auth: { status: "authenticated", email: "Same@example.com" },
246 usageLimits: { checkedAt, windows: [{ ...window, usedPercent: 40 }] },
247 });
248 const input = new Map([
249 [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { providers: [native] } }],
250 [
251 EnvironmentId.make("env-b"),
252 {
253 entry: { target: { label: "Desktop" } },
254 serverConfig: {
255 providers: [
256 {
257 ...native,
258 usageLimits: {
259 checkedAt: "2026-09-03T11:30:00.000Z",
260 windows: [{ ...window, usedPercent: 55 }],
261 },
262 },
263 ],
264 usageLimitSources: [
265 {
266 ...source,
267 accounts: [
268 {
269 id: "claude-same@example.com.json",
270 driver: claude,
271 email: "same@example.com",
272 plan: "Claude Subscription",
273 usageLimits: { checkedAt, windows: [{ ...window, usedPercent: 10 }] },
274 },
275 ],
276 },
277 ],
278 },
279 },
280 ],
281 ]);
282 const accounts = collectLimitAccounts(input);
283 expect(accounts).toHaveLength(1);
284 expect(accounts[0]).toMatchObject({
285 key: "env-a:claude",
286 sourceLabel: null,
287 redeem: { environmentId: "env-b", input: { instanceId: "claude" } },
288 environments: [
289 { environmentId: "env-a", label: "Laptop" },
290 { environmentId: "env-b", label: "Desktop" },
291 ],
292 });
293 expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(55);
294 });
295
296 it("uses the freshest reported plan even when the newest quota has no plan", () => {
297 const snapshot = (label: string | undefined, checkedAt: string, usedPercent: number) =>
298 provider({
299 driver: claude,
300 auth: { status: "authenticated", email: "same@example.com", label },
301 usageLimits: { checkedAt, windows: [{ ...window, usedPercent }] },
302 });
303 const stale = snapshot("Claude Team Subscription", checkedAt, 40);
304 const fresh = snapshot("Claude Max Subscription", "2026-09-03T11:30:00.000Z", 7);
305 const newest = snapshot(undefined, "2026-09-03T12:00:00.000Z", 5);
306 for (const [reports, plan, usedPercent] of [
307 [[stale, fresh], "Claude Max Subscription", 7],
308 [[stale, newest], "Claude Team Subscription", 5],
309 [[stale, fresh, newest], "Claude Max Subscription", 5],
310 ] as const) {
311 for (const order of reports.length === 2
312 ? [reports, reports.toReversed()]
313 : [
314 [stale, fresh, newest],
315 [stale, newest, fresh],
316 [fresh, stale, newest],
317 [fresh, newest, stale],
318 [newest, stale, fresh],
319 [newest, fresh, stale],
320 ]) {
321 const accounts = collectLimitAccounts(
322 new Map(
323 order.map((entry, index) => [
324 EnvironmentId.make(`env-${index}`),
325 { ...laptop, serverConfig: { providers: [entry] } },
326 ]),
327 ),
328 );
329 expect(accounts).toHaveLength(1);
330 expect(accounts[0]?.plan).toBe(plan);
331 expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(usedPercent);
332 }
333 }
334 });
335
336 it("merges OpenCode Go limits from machines with the same API key", () => {
337 const go = provider({
338 driver: ProviderDriverKind.make("opencode"),
339 instanceId: ProviderInstanceId.make("opencode"),
340 auth: { status: "authenticated" },
341 usageLimits: {
342 checkedAt,
343 credentialFingerprint: "shared-go-key",
344 windows: [{ ...window, id: "go_rolling", usedPercent: 3 }],
345 },
346 });
347 const input = new Map([
348 [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { providers: [go] } }],
349 [
350 EnvironmentId.make("env-b"),
351 {
352 entry: { target: { label: "Desktop" } },
353 serverConfig: {
354 providers: [
355 {
356 ...go,
357 usageLimits: {
358 ...go.usageLimits!,
359 checkedAt: "2026-09-03T11:30:00.000Z",
360 windows: [{ ...window, id: "go_rolling", usedPercent: 4 }],
361 },
362 },
363 ],
364 },
365 },
366 ],
367 ]);
368 const accounts = collectLimitAccounts(input);
369 expect(accounts).toHaveLength(1);
370 expect(accounts[0]?.environments).toEqual([
371 { environmentId: "env-a", label: "Laptop" },
372 { environmentId: "env-b", label: "Desktop" },
373 ]);
374 expect(collectLimitPools(accounts, now)[0]?.windows[0]?.members).toHaveLength(1);
375 expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(4);
376
377 const differentKey = {
378 ...go,
379 usageLimits: { ...go.usageLimits!, credentialFingerprint: "other-go-key" },
380 };
381 input.set(EnvironmentId.make("env-b"), {
382 entry: { target: { label: "Desktop" } },
383 serverConfig: { providers: [differentKey] },
384 });
385 expect(collectLimitAccounts(input)).toHaveLength(2);
386
387 input.set(EnvironmentId.make("env-a"), {
388 ...laptop,
389 serverConfig: {
390 providers: [{ ...go, auth: { status: "authenticated", email: "same@example.com" } }],
391 },
392 });
393 input.set(EnvironmentId.make("env-b"), {
394 entry: { target: { label: "Desktop" } },
395 serverConfig: {
396 providers: [
397 { ...differentKey, auth: { status: "authenticated", email: "SAME@example.com" } },
398 ],
399 },
400 });
401 expect(collectLimitAccounts(input)).toHaveLength(1);
402 });
403
404 it("merges a local Antigravity login with its hub account by Google account fingerprint", () => {
405 const antigravity = ProviderDriverKind.make("antigravity");
406 const local = provider({
407 driver: antigravity,
408 instanceId: ProviderInstanceId.make("antigravity"),
409 auth: { status: "authenticated" },
410 usageLimits: {
411 checkedAt,
412 credentialFingerprint: "google-key",
413 windows: [{ ...window, id: "gemini-weekly", usedPercent: 20 }],
414 },
415 });
416 const hubAccount = {
417 id: "antigravity-g@example.com.json",
418 driver: antigravity,
419 usageLimits: {
420 checkedAt: "2026-09-03T11:30:00.000Z",
421 credentialFingerprint: "google-key",
422 windows: [{ ...window, id: "gemini-weekly", usedPercent: 30 }],
423 },
424 };
425 const accounts = collectLimitAccounts(
426 new Map([
427 [
428 EnvironmentId.make("env-a"),
429 {
430 ...laptop,
431 serverConfig: {
432 providers: [local],
433 usageLimitSources: [{ ...source, accounts: [hubAccount] }],
434 },
435 },
436 ],
437 ]),
438 );
439 expect(accounts).toHaveLength(1);
440 expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(30);
441 });
442
443 it("takes windows from a fresher hub read but credits and redeem from the native instance", () => {
444 const native = provider({
445 driver: claude,
446 instanceId: ProviderInstanceId.make("claude"),
447 auth: { status: "authenticated", email: "same@example.com" },
448 usageLimits: {
449 checkedAt,
450 windows: [{ ...window, usedPercent: 40 }],
451 resetCredits: { availableCount: 2 },
452 },
453 });
454 const input = new Map([
455 [
456 EnvironmentId.make("env-a"),
457 {
458 ...laptop,
459 serverConfig: {
460 providers: [native],
461 usageLimitSources: [
462 {
463 ...source,
464 accounts: [
465 {
466 id: "claude-same@example.com.json",
467 driver: claude,
468 email: "same@example.com",
469 usageLimits: {
470 checkedAt: "2026-09-03T11:30:00.000Z",
471 windows: [{ ...window, usedPercent: 55 }],
472 },
473 },
474 ],
475 },
476 ],
477 },
478 },
479 ],
480 ]);
481 const [account] = collectLimitAccounts(input);
482 expect(account?.limits.windows[0]?.usedPercent).toBe(55);
483 expect(account?.limits.resetCredits?.availableCount).toBe(2);
484 expect(account?.redeem).toEqual({ environmentId: "env-a", input: { instanceId: "claude" } });
485 expect(account?.environments).toEqual([{ environmentId: "env-a", label: "Laptop" }]);
486 });
487
488 it("redeems through the hub when it holds a credit, even with a fresher native read", () => {
489 const native = provider({
490 driver: claude,
491 instanceId: ProviderInstanceId.make("claude"),
492 auth: { status: "authenticated", email: "same@example.com" },
493 usageLimits: {
494 checkedAt: "2026-09-03T11:30:00.000Z",
495 windows: [{ ...window, usedPercent: 40 }],
496 resetCredits: { availableCount: 3, nextCreditId: "native-credit" },
497 },
498 });
499 const input = new Map([
500 [
501 EnvironmentId.make("env-a"),
502 {
503 ...laptop,
504 serverConfig: {
505 providers: [native],
506 usageLimitSources: [
507 {
508 ...source,
509 accounts: [
510 {
511 id: "claude-same@example.com.json",
512 driver: claude,
513 email: "same@example.com",
514 usageLimits: {
515 checkedAt,
516 windows: [{ ...window, usedPercent: 55 }],
517 resetCredits: { availableCount: 2, nextCreditId: "hub-credit" },
518 },
519 },
520 ],
521 },
522 ],
523 },
524 },
525 ],
526 ]);
527 const [account] = collectLimitAccounts(input);
528 expect(account?.redeem).toEqual({
529 environmentId: "env-a",
530 input: { sourceId: "hub", accountId: "claude-same@example.com.json", creditId: "hub-credit" },
531 });
532 expect(account?.limits.resetCredits?.availableCount).toBe(3);
533 });
534
535 it("redeems on the environment whose snapshot supplied the credits on show", () => {
536 const stale = provider({
537 auth: { status: "authenticated", email: "same@example.com" },
538 usageLimits: {
539 checkedAt,
540 windows: [window],
541 resetCredits: { availableCount: 0 },
542 },
543 });
544 const fresh = {
545 ...stale,
546 usageLimits: {
547 checkedAt: "2026-09-03T11:30:00.000Z",
548 windows: [window],
549 resetCredits: { availableCount: 2 },
550 },
551 };
552 const input = new Map([
553 [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { providers: [stale] } }],
554 [
555 EnvironmentId.make("env-b"),
556 { entry: { target: { label: "Desktop" } }, serverConfig: { providers: [fresh] } },
557 ],
558 ]);
559 const [account] = collectLimitAccounts(input);
560 expect(account?.limits.resetCredits?.availableCount).toBe(2);
561 expect(account?.redeem).toEqual({ environmentId: "env-b", input: { instanceId: "codex" } });
562 });
563
564 it("keeps distinct hub accounts redeemable through their own source", () => {
565 const hubAccounts = ["first", "second"].map((id) => ({
566 id,
567 driver: ProviderDriverKind.make("codex"),
568 email: `${id}@example.com`,
569 usageLimits: {
570 checkedAt,
571 windows: [window],
572 resetCredits: { availableCount: 2, nextCreditId: `${id}-credit` },
573 },
574 }));
575 const input = new Map([
576 [
577 EnvironmentId.make("env-a"),
578 {
579 ...laptop,
580 serverConfig: {
581 providers: [],
582 usageLimitSources: [{ ...source, accounts: hubAccounts }],
583 },
584 },
585 ],
586 ]);
587 expect(collectLimitAccounts(input).map((account) => account.redeem)).toEqual(
588 hubAccounts.map((account) => ({
589 environmentId: "env-a",
590 input: { sourceId: "hub", accountId: account.id, creditId: `${account.id}-credit` },
591 })),
592 );
593 });
594
595 it("does not give old credits the timestamp of a newer window-only read", () => {
596 const snapshots = [
597 { checkedAt, windows: [window], resetCredits: { availableCount: 2 } },
598 { checkedAt: "2026-09-03T12:00:00.000Z", windows: [window] },
599 {
600 checkedAt: "2026-09-03T11:30:00.000Z",
601 windows: [window],
602 resetCredits: { availableCount: 1 },
603 },
604 ];
605 const input = new Map(
606 snapshots.map((usageLimits, i) => [
607 EnvironmentId.make(`env-${i}`),
608 {
609 ...laptop,
610 serverConfig: {
611 providers: [
612 provider({
613 auth: { status: "authenticated", email: "same@example.com" },
614 usageLimits,
615 }),
616 ],
617 },
618 },
619 ]),
620 );
621 const [account] = collectLimitAccounts(input);
622 expect(account?.limits.checkedAt).toBe("2026-09-03T12:00:00.000Z");
623 expect(account?.limits.resetCredits?.availableCount).toBe(1);
624 expect(account?.redeem?.environmentId).toBe("env-2");
625 });
626
627 it("keeps one email in two workspaces apart while merging each workspace's duplicates", () => {
628 const login = (instanceId: string, workspaceId: string, usedPercent: number) =>
629 provider({
630 instanceId: ProviderInstanceId.make(instanceId),
631 auth: { status: "authenticated", email: "same@example.com", workspaceId },
632 usageLimits: { checkedAt, windows: [{ ...weekly, usedPercent }] },
633 });
634 const hubAccount = (id: string, workspaceId?: string) => ({
635 id,
636 driver: ProviderDriverKind.make("codex"),
637 email: "same@example.com",
638 ...(workspaceId ? { workspaceId } : {}),
639 usageLimits: { checkedAt, windows: [{ ...weekly, usedPercent: 50 }] },
640 });
641 const input = new Map([
642 [
643 EnvironmentId.make("env-a"),
644 {
645 ...laptop,
646 serverConfig: {
647 providers: [login("business", "ws-business", 8), login("personal", "ws-plus", 26)],
648 usageLimitSources: [
649 { ...source, accounts: [hubAccount("plus.json", "ws-plus"), hubAccount("x.json")] },
650 ],
651 },
652 },
653 ],
654 [
655 EnvironmentId.make("env-b"),
656 {
657 entry: { target: { label: "Desktop" } },
658 serverConfig: { providers: [login("personal", "ws-plus", 26)] },
659 },
660 ],
661 ]);
662 const accounts = collectLimitAccounts(input);
663 expect(accounts.map((account) => account.key)).toEqual([
664 "env-a:business",
665 "env-a:personal",
666 "env-a:hub:x.json",
667 ]);
668 expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(8);
669 const withoutEmail = (id: string, workspaceId: string) => {
670 const { email: _email, ...account } = hubAccount(id, workspaceId);
671 return account;
672 };
673 const sameFile = new Map([
674 [
675 EnvironmentId.make("env-a"),
676 {
677 ...laptop,
678 serverConfig: {
679 providers: [],
680 usageLimitSources: [{ ...source, accounts: [withoutEmail("a.json", "ws-1")] }],
681 },
682 },
683 ],
684 [
685 EnvironmentId.make("env-b"),
686 {
687 ...laptop,
688 serverConfig: {
689 providers: [],
690 usageLimitSources: [{ ...source, accounts: [withoutEmail("a.json", "ws-2")] }],
691 },
692 },
693 ],
694 ]);
695 expect(collectLimitAccounts(sameFile).map((account) => account.key)).toEqual([
696 "env-a:hub:a.json:ws-1",
697 "env-b:hub:a.json:ws-2",
698 ]);
699 expect(accounts[1]?.environments.map((environment) => environment.label)).toEqual([
700 "Laptop",
701 "Desktop",
702 ]);
703 });
704
705 it("joins a report without a workspace to the only workspace signed in with its email", () => {
706 const native = provider({
707 driver: claude,
708 auth: { status: "authenticated", email: "same@example.com", workspaceId: "org-a" },
709 usageLimits: { checkedAt, windows: [window] },
710 });
711 const hubAccount = {
712 id: "claude.json",
713 driver: claude,
714 email: "same@example.com",
715 usageLimits: { checkedAt, windows: [window] },
716 };
717 const withOther = (other: ServerProvider) =>
718 new Map([
719 [
720 EnvironmentId.make("env-a"),
721 {
722 ...laptop,
723 serverConfig: {
724 providers: [native, other],
725 usageLimitSources: [{ ...source, accounts: [hubAccount] }],
726 },
727 },
728 ],
729 ]);
730 const unrelated = provider({ instanceId: ProviderInstanceId.make("codex-2") });
731 expect(collectLimitAccounts(withOther(unrelated)).map((account) => account.key)).toEqual([
732 "env-a:codex",
733 ]);
734 const unreadable = provider({
735 ...native,
736 instanceId: ProviderInstanceId.make("team"),
737 auth: { ...native.auth, workspaceId: "org-b" },
738 usageLimits: { checkedAt, windows: [], unavailable: { reason: "probeFailed" } },
739 });
740 expect(collectLimitAccounts(withOther(unreadable)).map((account) => account.key)).toEqual([
741 "env-a:codex",
742 "env-a:hub:claude.json",
743 ]);
744 });
745
746 it.each([
747 [
748 "one remote hub under environment-local ids",
749 "http://hub:8317",
750 "laptop-hub",
751 "http://hub:8317",
752 1,
753 ],
754 ["two remote hubs under one id", "http://hub:8317", "hub", "http://hub-8317", 2],
755 [
756 "two remote hubs under paths of one origin",
757 "https://proxy.example/team-a",
758 "hub-b",
759 "https://proxy.example/team-b",
760 2,
761 ],
762 [
763 "a shared IPv6 tailnet hub",
764 "http://[fd7a:115c:a1e0::1]:8317",
765 "hub",
766 "http://[fd7a:115c:a1e0::1]:8317",
767 1,
768 ],
769 [
770 "each machine's own localhost hub",
771 "http://localhost:8317",
772 "hub",
773 "http://localhost:8317",
774 2,
775 ],
776 ["each machine's own IPv6 loopback hub", "http://[::1]:8317", "hub", "http://[::1]:8317", 2],
777 [
778 "each machine's own localhost subdomain hub",
779 "http://hub.localhost:8317",
780 "hub",
781 "http://hub.localhost:8317",
782 2,
783 ],
784 [
785 "each machine's own trailing-dot localhost subdomain hub",
786 "http://hub.localhost.:8317",
787 "hub",
788 "http://hub.localhost.:8317",
789 2,
790 ],
791 [
792 "each machine's own mapped IPv4 loopback hub",
793 "http://[::ffff:7f00:1]:8317",
794 "hub",
795 "http://[::ffff:7f00:1]:8317",
796 2,
797 ],
798 ["each machine's own wildcard hub", "http://0.0.0.0:8317", "hub", "http://0.0.0.0:8317", 2],
799 ["hubs that report no endpoint", undefined, "hub", undefined, 2],
800 ] as const)(
801 "keeps email-less hub identity across environments: %s",
802 (_, firstEndpoint, secondId, secondEndpoint, count) => {
803 const seat = {
804 id: "claude-team-seat.json",
805 driver: claude,
806 usageLimits: { checkedAt, windows: [window] },
807 };
808 const hubAt = (id: string, endpoint: string | undefined) => ({
809 ...source,
810 id: UsageLimitSourceId.make(id),
811 ...(endpoint ? { origin: new URL(endpoint).origin, endpoint } : {}),
812 accounts: [seat],
813 });
814 const input = new Map([
815 [
816 EnvironmentId.make("env-a"),
817 {
818 ...laptop,
819 serverConfig: { providers: [], usageLimitSources: [hubAt("hub", firstEndpoint)] },
820 },
821 ],
822 [
823 EnvironmentId.make("env-b"),
824 {
825 entry: { target: { label: "Desktop" } },
826 serverConfig: { providers: [], usageLimitSources: [hubAt(secondId, secondEndpoint)] },
827 },
828 ],
829 ]);
830 const accounts = collectLimitAccounts(input);
831 expect(accounts).toHaveLength(count);
832 expect(accounts[0]?.displayName).toBe("claude-team-seat");
833 },
834 );
835
836 it("keeps public keys apart for different logins in one hub file", () => {
837 const hubAt = (id: string, email: string, usedPercent: number) => ({
838 ...source,
839 id: UsageLimitSourceId.make(id),
840 origin: "https://hub.test",
841 endpoint: "https://hub.test",
842 accounts: [
843 {
844 id: "seat.json",
845 driver: claude,
846 email,
847 usageLimits: { checkedAt, windows: [{ ...window, usedPercent }] },
848 },
849 ],
850 });
851 const input = new Map([
852 [
853 EnvironmentId.make("env-a"),
854 {
855 ...laptop,
856 serverConfig: {
857 providers: [],
858 usageLimitSources: [hubAt("first", "old@example.com", 10)],
859 },
860 },
861 ],
862 [
863 EnvironmentId.make("env-b"),
864 {
865 entry: { target: { label: "Desktop" } },
866 serverConfig: {
867 providers: [],
868 usageLimitSources: [hubAt("second", "new@example.com", 80)],
869 },
870 },
871 ],
872 ]);
873 const accounts = collectLimitAccounts(input);
874 expect(accounts.map((account) => account.key)).toEqual([
875 "env-a:first:seat.json",
876 "env-b:second:seat.json",
877 ]);
878 const columns = collectLimitPools(accounts, Date.parse(checkedAt))[0]?.windows[0]?.columns;
879 expect(columns?.map((column) => [column.account.email, column.window?.usedPercent])).toEqual([
880 ["new@example.com", 80],
881 ["old@example.com", 10],
882 ]);
883 });
884
885 it("labels a default-named instance merged with a hub account by e-mail, keeping a chosen name", () => {
886 const native = provider({
887 driver: claude,
888 instanceId: ProviderInstanceId.make("claudeAgent"),
889 displayName: "Claude",
890 auth: { status: "authenticated", email: "a@example.com" },
891 usageLimits: { checkedAt, windows: [window] },
892 });
893 const named = provider({
894 driver: claude,
895 instanceId: ProviderInstanceId.make("claude-work"),
896 displayName: "Work",
897 auth: { status: "authenticated", email: "b@example.com" },
898 usageLimits: { checkedAt, windows: [window] },
899 });
900 const hubAccount = (email: string) => ({
901 id: `claude-${email}.json`,
902 driver: claude,
903 email,
904 usageLimits: { checkedAt, windows: [window] },
905 });
906 const input = new Map([
907 [
908 EnvironmentId.make("env-a"),
909 {
910 ...laptop,
911 serverConfig: {
912 providers: [native, named],
913 usageLimitSources: [
914 {
915 ...source,
916 accounts: [
917 hubAccount("a@example.com"),
918 hubAccount("b@example.com"),
919 hubAccount("c@example.com"),
920 ],
921 },
922 ],
923 },
924 },
925 ],
926 ]);
927 expect(
928 collectLimitAccounts(input).map(({ displayName, email }) => ({ displayName, email })),
929 ).toEqual([
930 { displayName: null, email: "a@example.com" },
931 { displayName: "Work", email: "b@example.com" },
932 { displayName: null, email: "c@example.com" },
933 ]);
934 });
935
936 it("pools Codex windows by kind, whichever slot reported them", () => {
937 const codexAccount = (id: string, slots: readonly string[]) => ({
938 id,
939 driver: ProviderDriverKind.make("codex"),
940 usageLimits: {
941 checkedAt,
942 windows: slots.map((slot) => ({ ...weekly, id: slot, usedPercent: 50 })),
943 },
944 });
945 const pooled = (accounts: ReturnType<typeof codexAccount>[]) =>
946 collectLimitPools(
947 collectLimitAccounts(
948 new Map([
949 [
950 EnvironmentId.make("env-a"),
951 {
952 ...laptop,
953 serverConfig: { providers: [], usageLimitSources: [{ ...source, accounts }] },
954 },
955 ],
956 ]),
957 ),
958 now,
959 )[0]?.windows ?? [];
960 for (const order of [
961 [codexAccount("business", ["primary"]), codexAccount("plus", ["secondary"])],
962 [codexAccount("plus", ["secondary"]), codexAccount("business", ["primary"])],
963 ]) {
964 const windows = pooled(order);
965 expect(windows.map((window) => window.id)).toEqual(["weekly"]);
966 expect(windows[0]?.members).toHaveLength(2);
967 }
968 expect(
969 pooled([codexAccount("a", ["secondary"]), codexAccount("b", ["primary", "secondary"])]).map(
970 (window) => window.id,
971 ),
972 ).toEqual(["weekly", "weekly:secondary"]);
973 });
974
975 it("weights pooled Codex quota and resets by each account's plan capacity", () => {
976 const [pool] = collectLimitPools(
977 collectLimitAccounts(
978 new Map([
979 [
980 EnvironmentId.make("env-a"),
981 {
982 ...laptop,
983 serverConfig: {
984 providers: [],
985 usageLimitSources: [
986 {
987 ...source,
988 accounts: [
989 ["pro", "ChatGPT Pro 200 Subscription", 100],
990 ["plus", "ChatGPT Plus Subscription", 0],
991 ].map(([id, plan, usedPercent]) => ({
992 id: String(id),
993 email: `${id}@example.com`,
994 driver: ProviderDriverKind.make("codex"),
995 plan: String(plan),
996 usageLimits: {
997 checkedAt,
998 windows: [{ ...weekly, id: "secondary", usedPercent: Number(usedPercent) }],
999 },
1000 })),
1001 },
1002 ],
1003 },
1004 },
1005 ],
1006 ]),
1007 ),
1008 now,
1009 );
1010 const [pooledWeekly] = pool?.windows ?? [];
1011 // Pro 20x holds 20 of the pool's 21 capacity parts.
1012 expect(pooledWeekly?.remainingPercent).toBe(5);
1013 expect(
1014 pooledWeekly?.resets.map(({ member, restoresPercent }) => [
1015 member.account.email,
1016 restoresPercent,
1017 ]),
1018 ).toContainEqual(["pro@example.com", 95]);
1019 });
1020
1021 it("pools windows by id across accounts and orders resets by when they land", () => {
1022 const input = new Map([
1023 [
1024 EnvironmentId.make("env-a"),
1025 {
1026 ...laptop,
1027 serverConfig: {
1028 providers: [],
1029 usageLimitSources: [
1030 {
1031 ...source,
1032 accounts: [
1033 {
1034 id: "a",
1035 driver: claude,
1036 usageLimits: {
1037 checkedAt,
1038 windows: [
1039 { ...window, usedPercent: 80, resetsAt: "2026-09-03T13:00:00.000Z" },
1040 { ...weekly, usedPercent: 20 },
1041 ],
1042 },
1043 },
1044 {
1045 id: "b",
1046 driver: claude,
1047 usageLimits: {
1048 checkedAt,
1049 windows: [{ ...window, usedPercent: 40 }],
1050 },
1051 },
1052 {
1053 id: "c",
1054 driver: ProviderDriverKind.make("codex"),
1055 usageLimits: { checkedAt, windows: [{ ...weekly, usedPercent: 50 }] },
1056 },
1057 {
1058 id: "unsupported",
1059 driver: claude,
1060 usageLimits: {
1061 checkedAt,
1062 windows: [],
1063 unavailable: { reason: "unsupported" as const },
1064 },
1065 },
1066 ],
1067 },
1068 ],
1069 },
1070 },
1071 ],
1072 ]);
1073 const pools = collectLimitPools(collectLimitAccounts(input), now);
1074 expect(pools.map((pool) => [pool.driver, pool.accounts.length])).toEqual([
1075 ["claudeAgent", 2],
1076 ["codex", 1],
1077 ]);
1078 const [session, week] = pools[0]!.windows;
1079 const untimed = collectLimitPools(
1080 collectLimitAccounts(input).map((account) =>
1081 account.key === "env-a:hub:b"
1082 ? {
1083 ...account,
1084 limits: {
1085 ...account.limits,
1086 windows: account.limits.windows.map((w) => ({ ...w, resetsAt: undefined })),
1087 },
1088 }
1089 : account,
1090 ),
1091 now,
1092 );
1093 expect(untimed[0]?.windows[0]?.pace).toBe("on");
1094 expect(session).toMatchObject({
1095 id: "five_hour",
1096 remainingPercent: 40,
1097 usedPercent: 60,
1098 pace: "under",
1099 });
1100 expect(
1101 session?.resets.map((reset) => [reset.member.account.key, reset.restoresPercent]),
1102 ).toEqual([
1103 ["env-a:hub:a", 40],
1104 ["env-a:hub:b", 20],
1105 ]);
1106 expect(week).toMatchObject({ id: "seven_day", remainingPercent: 80, members: [{}] });
1107 // Codex reports `primary` for both its five-hour and (on Go) monthly window.
1108 const mixed = collectLimitPools(
1109 [
1110 ...collectLimitAccounts(input),
1111 {
1112 key: "go",
1113 driver: claude,
1114 displayName: "Go",
1115 email: undefined,
1116 plan: undefined,
1117 accentColor: undefined,
1118 environments: [],
1119 sourceLabel: null,
1120 redeem: null,
1121 limits: {
1122 checkedAt,
1123 windows: [
1124 {
1125 id: "five_hour",
1126 kind: "monthly",
1127 label: "Monthly",
1128 usedPercent: 82,
1129 windowDurationMins: 30 * 24 * 60,
1130 resetsAt: "2026-09-14T12:00:00.000Z",
1131 },
1132 ],
1133 },
1134 },
1135 ],
1136 now,
1137 );
1138 expect(mixed[0]?.windows.map((window) => [window.kind, window.members.length])).toEqual([
1139 ["session", 2],
1140 ["weekly", 1],
1141 ["monthly", 1],
1142 ]);
1143 expect(session?.members.map((member) => member.account.key)).toEqual([
1144 "env-a:hub:a",
1145 "env-a:hub:b",
1146 ]);
1147 expect(pools[0]?.accounts.map((account) => account.key)).toEqual([
1148 "env-a:hub:a",
1149 "env-a:hub:b",
1150 ]);
1151 });
1152 });
1153
1154 describe("pooled account columns", () => {
1155 const weekly = {
1156 ...window,
1157 id: "seven_day",
1158 kind: "weekly",
1159 label: "Weekly",
1160 windowDurationMins: 7 * 24 * 60,
1161 } as const;
1162 const account = (key: string, windows: LimitAccount["limits"]["windows"]): LimitAccount => ({
1163 key,
1164 driver: ProviderDriverKind.make("claudeAgent"),
1165 displayName: key,
1166 email: undefined,
1167 plan: undefined,
1168 accentColor: undefined,
1169 environments: [],
1170 sourceLabel: "Hub",
1171 redeem: null,
1172 limits: { checkedAt: "2026-09-03T11:00:00.000Z", windows },
1173 });
1174 const keys = (pool: ReturnType<typeof collectLimitPools>[number]) =>
1175 pool.windows.map((row) =>
1176 row.columns.map((member) => (member.window ? member.account.key : null)),
1177 );
1178
1179 it.each([
1180 {
1181 reports: [
1182 [14, 14],
1183 [14, 14],
1184 ],
1185 ids: ["autoPercentUsed"],
1186 remaining: [86],
1187 label: null,
1188 },
1189 {
1190 reports: [
1191 [14, 14],
1192 [80, 70],
1193 ],
1194 ids: ["totalPercentUsed", "autoPercentUsed"],
1195 remaining: [53, 58],
1196 label: "Cursor Models",
1197 },
1198 {
1199 reports: [[undefined, 14]],
1200 ids: ["autoPercentUsed"],
1201 remaining: [86],
1202 label: "Cursor Models",
1203 },
1204 { reports: [[14, undefined]], ids: ["totalPercentUsed"], remaining: [86], label: null },
1205 ])("preserves Cursor totals and scope for $reports", ({ reports, ids, remaining, label }) => {
1206 const accounts = reports.map(([total, auto], index) => ({
1207 ...account(String(index), [
1208 ...(total === undefined ? [] : [{ ...weekly, id: "totalPercentUsed", usedPercent: total }]),
1209 ...(auto === undefined ? [] : [{ ...weekly, id: "autoPercentUsed", usedPercent: auto }]),
1210 ]),
1211 driver: ProviderDriverKind.make("cursor"),
1212 }));
1213 const pool = collectLimitPools(accounts, now)[0]!;
1214 const visible = displayLimitWindows(pool);
1215 expect(visible.map((window) => window.id)).toEqual(ids);
1216 expect(visible.map((window) => window.remainingPercent)).toEqual(remaining);
1217 expect(cursorUsageWindowDetails(ids.at(-1)!, pool)?.label).toBe(label);
1218 });
1219
1220 // regression: #20349 sessions stay visible while the weekly quota is exhausted
1221 it.each([
1222 ["claudeAgent", "13:00", 40, "14:00", 100],
1223 ["codex", "14:00", 100, "14:00", 100],
1224 ["claudeAgent", "15:00", 100, "15:00", 100],
1225 ["codex", "15:00", 40, "14:00", 60],
1226 ] as const)(
1227 "%s session resetting at %s with %i percent spent becomes usable at %s with %i percent restored",
1228 (driver, sessionReset, usedPercent, usableAt, restoresPercent) => {
1229 const at = (time: string) => `2026-09-03T${time}:00.000Z`;
1230 const a = {
1231 ...account("a", [
1232 {
1233 ...window,
1234 id: driver === "codex" ? "primary" : window.id,
1235 usedPercent,
1236 resetsAt: at(sessionReset),
1237 },
1238 {
1239 ...weekly,
1240 id: driver === "codex" ? "secondary" : weekly.id,
1241 usedPercent: 100,
1242 resetsAt: at("14:00"),
1243 },
1244 ]),
1245 driver: ProviderDriverKind.make(driver),
1246 };
1247 const [session] = collectLimitPools([a], now)[0]!.windows;
1248 expect.soft(session?.remainingPercent).toBe(0);
1249 expect(session?.resets[0]).toMatchObject({
1250 at: Date.parse(at(usableAt)),
1251 restoresPercent,
1252 });
1253 },
1254 );
1255
1256 it("excludes weekly-blocked sessions from the pool without changing snapshots or model allowances", () => {
1257 const blocked = account("blocked", [
1258 window,
1259 { ...weekly, usedPercent: 100 },
1260 { ...weekly, id: "seven_day_fable", usedPercent: 20 },
1261 ]);
1262 const accounts = [
1263 blocked,
1264 account("available", [
1265 { ...window, usedPercent: 20 },
1266 { ...weekly, usedPercent: 99 },
1267 { ...weekly, id: "seven_day_fable", usedPercent: 40 },
1268 ]),
1269 { ...blocked, key: "cursor", driver: ProviderDriverKind.make("cursor") },
1270 ];
1271 const snapshot = structuredClone(accounts);
1272 const [claude, cursor] = collectLimitPools(accounts, now);
1273 expect.soft(claude?.windows.map((row) => row.remainingPercent)).toEqual([40, 1, 70]);
1274 expect.soft(cursor?.windows.map((row) => row.remainingPercent)).toEqual([60, 0, 80]);
1275 expect(accounts).toEqual(snapshot);
1276 });
1277
1278 it("keeps session columns across rows with opposite reset and usage orders", () => {
1279 const accounts = [
1280 account("a", [
1281 { ...weekly, usedPercent: 80, resetsAt: "2026-09-05T12:00:00.000Z" },
1282 { ...window, usedPercent: 10, resetsAt: "2026-09-03T15:00:00.000Z" },
1283 ]),
1284 account("b", [
1285 { ...weekly, usedPercent: 20, resetsAt: "2026-09-06T12:00:00.000Z" },
1286 { ...window, usedPercent: 90, resetsAt: "2026-09-03T13:00:00.000Z" },
1287 ]),
1288 ];
1289 const [pool] = collectLimitPools(accounts, now);
1290 expect(pool!.accounts.map((account) => account.key)).toEqual(["b", "a"]);
1291 expect(keys(pool!)).toEqual([
1292 ["b", "a"],
1293 ["b", "a"],
1294 ]);
1295 expect(pool!.windows[1]!.resets.map((reset) => reset.member.account.key)).toEqual(["a", "b"]);
1296 expect(pool!.windows[1]!.remainingPercent).toBe(50);
1297 expect(keys(collectLimitPools(accounts.toReversed(), now)[0]!)).toEqual(keys(pool!));
1298 });
1299
1300 it.each([undefined, "invalid", "2026-09-03T11:30:00.000Z"])(
1301 "keeps blocked sessions empty without predicting a refill from a missing or stale clock (%s)",
1302 (resetsAt) => {
1303 const [pool] = collectLimitPools(
1304 [
1305 account("session-clock", [
1306 { ...window, resetsAt },
1307 { ...weekly, usedPercent: 100 },
1308 ]),
1309 account("weekly-clock", [window, { ...weekly, usedPercent: 100, resetsAt }]),
1310 ],
1311 now,
1312 );
1313 expect(pool!.windows[0]).toMatchObject({ remainingPercent: 0, pace: null, resets: [] });
1314 expect(pool!.windows[0]!.columns.map((column) => column.window?.resetsAt)).toEqual([
1315 undefined,
1316 undefined,
1317 ]);
1318 },
1319 );
1320
1321 it("orders by usable session refill and clears suppression after a fresh weekly reading", () => {
1322 const blocked = account("blocked", [
1323 { ...window, resetsAt: "2026-09-03T13:00:00.000Z" },
1324 { ...weekly, usedPercent: 100, resetsAt: "2026-09-03T15:00:00.000Z" },
1325 ]);
1326 const available = account("available", [window]);
1327 const [before] = collectLimitPools([blocked, available], now);
1328 expect(before!.accounts.map((account) => account.key)).toEqual(["available", "blocked"]);
1329 expect(before!.windows[0]!.remainingPercent).toBe(30);
1330 const refreshed = {
1331 ...blocked,
1332 limits: {
1333 checkedAt: "2026-09-03T12:00:00.000Z",
1334 windows: [blocked.limits.windows[0]!, { ...weekly, usedPercent: 10 }],
1335 },
1336 };
1337 const [after] = collectLimitPools([refreshed, available], now);
1338 expect(after!.accounts.map((account) => account.key)).toEqual(["blocked", "available"]);
1339 expect(after!.windows[0]!.remainingPercent).toBe(60);
1340 expect(after!.windows[0]!.resets[0]).toMatchObject({
1341 at: Date.parse("2026-09-03T13:00:00.000Z"),
1342 restoresPercent: 20,
1343 });
1344 });
1345
1346 it("preserves gaps without counting missing windows toward pooled quota", () => {
1347 const [pool] = collectLimitPools(
1348 [
1349 account("a", [window]),
1350 account("b", [
1351 { ...window, resetsAt: "2026-09-03T15:00:00.000Z" },
1352 { ...weekly, usedPercent: 80 },
1353 ]),
1354 account("c", [weekly]),
1355 ],
1356 now,
1357 );
1358 expect(keys(pool!)).toEqual([
1359 ["a", "b", null],
1360 [null, "b", "c"],
1361 ]);
1362 expect(pool!.windows[1]!.members.map((member) => member.account.key)).toEqual(["b", "c"]);
1363 expect(pool!.windows[1]!.remainingPercent).toBe(40);
1364 expect(pool!.windows[1]!.resets.map((reset) => reset.restoresPercent)).toEqual([40, 20]);
1365 });
1366
1367 it("falls back to weekly resets when no account reports a session", () => {
1368 const [pool] = collectLimitPools(
1369 [
1370 account("a", [{ ...weekly, resetsAt: "2026-09-06T12:00:00.000Z" }]),
1371 account("b", [{ ...weekly, resetsAt: "2026-09-05T12:00:00.000Z" }]),
1372 ],
1373 now,
1374 );
1375 expect(keys(pool!)).toEqual([["b", "a"]]);
1376 });
1377 });
1378
1379 describe("/usage-limits", () => {
1380 const limits = { checkedAt: "2026-09-03T11:00:00.000Z", windows: [window] };
1381 const selected = provider({
1382 usageLimits: limits,
1383 auth: { status: "authenticated", email: "same@example.com" },
1384 });
1385 const sources = [
1386 {
1387 id: UsageLimitSourceId.make("hub"),
1388 kind: "cliproxy" as const,
1389 label: "Accounts",
1390 origin: "http://hub:8317",
1391 checkedAt: limits.checkedAt,
1392 accounts: [
1393 {
1394 id: "duplicate",
1395 driver: selected.driver,
1396 email: "SAME@example.com",
1397 usageLimits: limits,
1398 },
1399 { id: "oss", driver: selected.driver, plan: "Codex OSS", usageLimits: limits },
1400 { id: "other-provider", driver: ProviderDriverKind.make("claude"), usageLimits: limits },
1401 ],
1402 },
1403 ];
1404
1405 it("uses hub credit balances and redemption targets in the composer, including native duplicates", () => {
1406 const hubs = sources.map((source) => ({
1407 ...source,
1408 accounts: source.accounts.map((account) => ({
1409 ...account,
1410 usageLimits: {
1411 ...account.usageLimits,
1412 resetCredits: { availableCount: 2, nextCreditId: `${account.id}-credit` },
1413 },
1414 })),
1415 }));
1416 const report = collectProviderUsageLimits(selected.instanceId, [selected], hubs, now);
1417 expect(report?.accounts[0]?.limits.resetCredits?.availableCount).toBe(2);
1418 expect(report?.accounts[0]?.resetCreditInput).toEqual({
1419 sourceId: "hub",
1420 accountId: "duplicate",
1421 creditId: "duplicate-credit",
1422 });
1423 expect(report?.accounts.find((account) => account.id === "hub:oss")?.resetCreditInput).toEqual({
1424 sourceId: "hub",
1425 accountId: "oss",
1426 creditId: "oss-credit",
1427 });
1428 });
1429
1430 it("gives a hub credit to no native row when its email is signed in to two workspaces", () => {
1431 const workspaces = ["ws-a", "ws-b"].map((workspaceId) =>
1432 provider({
1433 instanceId: ProviderInstanceId.make(workspaceId),
1434 usageLimits: limits,
1435 auth: { status: "authenticated", email: "same@example.com", workspaceId },
1436 }),
1437 );
1438 const hub = [
1439 {
1440 ...sources[0]!,
1441 accounts: [
1442 {
1443 id: "duplicate",
1444 driver: selected.driver,
1445 email: "same@example.com",
1446 usageLimits: { ...limits, resetCredits: { availableCount: 2, nextCreditId: "c" } },
1447 },
1448 ],
1449 },
1450 ];
1451 const report = collectProviderUsageLimits(workspaces[0]!.instanceId, workspaces, hub, now);
1452 expect(report?.accounts.map((account) => account.resetCreditInput)).toEqual([
1453 { instanceId: "ws-a" },
1454 { instanceId: "ws-b" },
1455 { sourceId: "hub", accountId: "duplicate", creditId: "c" },
1456 ]);
1457 });
1458
1459 it("redeems a native duplicate through the hub even when the native snapshot is fresher", () => {
1460 const fresher = provider({
1461 usageLimits: {
1462 checkedAt: "2026-09-03T11:30:00.000Z",
1463 windows: [window],
1464 resetCredits: { availableCount: 3, nextCreditId: "native-credit" },
1465 },
1466 auth: { status: "authenticated", email: "same@example.com" },
1467 });
1468 const stale = [
1469 {
1470 id: UsageLimitSourceId.make("hub"),
1471 kind: "cliproxy" as const,
1472 label: "Accounts",
1473 checkedAt: limits.checkedAt,
1474 accounts: [
1475 {
1476 id: "duplicate",
1477 driver: fresher.driver,
1478 email: "SAME@example.com",
1479 usageLimits: {
1480 ...limits,
1481 resetCredits: { availableCount: 2, nextCreditId: "hub-credit" },
1482 },
1483 },
1484 ],
1485 },
1486 ];
1487 const report = collectProviderUsageLimits(fresher.instanceId, [fresher], stale, now);
1488 expect(report?.accounts[0]?.resetCreditInput).toEqual({
1489 sourceId: "hub",
1490 accountId: "duplicate",
1491 creditId: "hub-credit",
1492 });
1493 expect(report?.accounts[0]?.limits.resetCredits?.availableCount).toBe(3);
1494 });
1495
1496 it("labels hub rows by account id without .json", () => {
1497 const hub = [
1498 {
1499 ...sources[0]!,
1500 label: "CLIProxyAPI",
1501 accounts: [
1502 {
1503 id: "claude-b@example.com.json",
1504 driver: selected.driver,
1505 email: "b@example.com",
1506 usageLimits: limits,
1507 },
1508 { id: "team-seat.json", driver: selected.driver, usageLimits: limits },
1509 ],
1510 },
1511 ];
1512 const report = collectProviderUsageLimits(selected.instanceId, [selected], hub, now);
1513 expect(
1514 report?.accounts.filter((account) => account.sourceLabel).map((account) => account.label),
1515 ).toEqual(["CLIProxyAPI · claude-b@example.com", "CLIProxyAPI · team-seat"]);
1516 });
1517
1518 it("keeps unidentified custom instances separate, filtering by driver", () => {
1519 const report = collectProviderUsageLimits(
1520 selected.instanceId,
1521 [
1522 selected,
1523 provider({
1524 instanceId: ProviderInstanceId.make("codex-work"),
1525 displayName: "Work",
1526 usageLimits: { ...limits, resetCredits: { availableCount: 2 } },
1527 }),
1528 provider({
1529 driver: ProviderDriverKind.make("claude"),
1530 instanceId: ProviderInstanceId.make("claude"),
1531 usageLimits: limits,
1532 }),
1533 ],
1534 sources,
1535 now,
1536 );
1537 expect(report?.createdAt).toBe("2026-09-03T12:00:00.000Z");
1538 expect(report?.accounts.map((account) => account.id)).toEqual([
1539 "codex",
1540 "codex-work",
1541 "hub:oss",
1542 ]);
1543 expect(report?.accounts[0]).toMatchObject({
1544 instanceId: selected.instanceId,
1545 email: selected.auth.email,
1546 });
1547 expect(report?.accounts[1]).toMatchObject({
1548 displayName: "Work",
1549 limits: { resetCredits: { availableCount: 2 } },
1550 });
1551 expect(report?.accounts[2]).toMatchObject({
1552 label: "Accounts · oss",
1553 sourceLabel: "CLI Proxy",
1554 plan: "Codex OSS",
1555 });
1556 expect(report?.notices).toEqual([]);
1557 });
1558
1559 it("shows a proxied instance the hub accounts its model routes to, of any driver", () => {
1560 const routed = [
1561 {
1562 ...sources[0]!,
1563 accounts: sources[0]!.accounts.map((account) =>
1564 account.id === "oss" ? { ...account, models: ["gpt-5.6-sol"] } : account,
1565 ),
1566 },
1567 ];
1568 const proxy = provider({
1569 instanceId: ProviderInstanceId.make("claudex"),
1570 driver: ProviderDriverKind.make("claudeAgent"),
1571 auth: { status: "authenticated", type: "customEndpoint", endpoint: "http://hub:8317" },
1572 });
1573 // regression: #30778 a local login the hub does not route to is not this thread's account
1574 const unrelated = provider({
1575 instanceId: ProviderInstanceId.make("codex-personal"),
1576 usageLimits: limits,
1577 auth: { status: "authenticated", email: "personal@example.com" },
1578 });
1579 const ids = (instance: ServerProvider, model: string | null) =>
1580 collectProviderUsageLimits(
1581 instance.instanceId,
1582 [selected, proxy, unrelated],
1583 routed,
1584 now,
1585 model,
1586 )?.accounts.map((account) => account.id);
1587 expect(ids(proxy, "gpt-5.6-sol[1m]")).toEqual(["codex", "hub:oss"]);
1588 // regression: #30778 another hub's model list does not decide this hub's routing
1589 const other = {
1590 ...routed[0]!,
1591 id: UsageLimitSourceId.make("other"),
1592 origin: "http://other:8317",
1593 accounts: [
1594 {
1595 id: "x",
1596 driver: ProviderDriverKind.make("grok"),
1597 models: ["gpt-5.6-sol"],
1598 usageLimits: limits,
1599 },
1600 ],
1601 };
1602 expect(
1603 collectProviderUsageLimits(
1604 proxy.instanceId,
1605 [selected, proxy],
1606 [other, ...routed],
1607 now,
1608 "gpt-5.6-sol",
1609 )?.accounts.map((account) => account.id),
1610 ).toEqual(["codex", "hub:oss"]);
1611 // regression: #30778 a custom endpoint other than the hub does not follow the hub's routing
1612 const elsewhere = { ...proxy, auth: { ...proxy.auth, endpoint: "http://other:8317" } };
1613 expect(
1614 collectProviderUsageLimits(
1615 proxy.instanceId,
1616 [selected, elsewhere],
1617 routed,
1618 now,
1619 "gpt-5.6-sol",
1620 ),
1621 ).toBeNull();
1622 expect(ids(selected, "gpt-5.6-sol")).toEqual(["codex", "codex-personal", "hub:oss"]);
1623 });
1624
1625 it("keeps the freshest usable native duplicate and the freshest native credits in either order", () => {
1626 const failed = provider({
1627 auth: selected.auth,
1628 usageLimits: {
1629 ...limits,
1630 checkedAt: "2026-09-03T11:40:00.000Z",
1631 unavailable: { reason: "probeFailed" },
1632 },
1633 });
1634 const credited = provider({
1635 instanceId: ProviderInstanceId.make("codex-credit"),
1636 auth: selected.auth,
1637 usageLimits: {
1638 checkedAt: "2026-09-03T11:20:00.000Z",
1639 windows: [{ ...window, usedPercent: 50 }],
1640 resetCredits: { availableCount: 2 },
1641 },
1642 });
1643 const staleCredit = provider({
1644 ...credited,
1645 instanceId: ProviderInstanceId.make("codex-stale-credit"),
1646 usageLimits: { ...limits, resetCredits: { availableCount: 3 } },
1647 });
1648 const freshest = provider({
1649 instanceId: ProviderInstanceId.make("codex-fresh"),
1650 auth: selected.auth,
1651 usageLimits: {
1652 checkedAt: "2026-09-03T11:30:00.000Z",
1653 windows: [{ ...window, usedPercent: 55 }],
1654 },
1655 });
1656 const duplicates = [failed, staleCredit, credited, freshest];
1657 for (const providers of [duplicates, duplicates.toReversed()]) {
1658 const report = collectProviderUsageLimits(failed.instanceId, providers, sources, now);
1659 expect(report?.accounts.map((account) => account.id)).toEqual(["codex-fresh", "hub:oss"]);
1660 expect(report?.accounts[0]).toMatchObject({
1661 limits: {
1662 checkedAt: "2026-09-03T11:30:00.000Z",
1663 windows: [{ usedPercent: 55 }],
1664 resetCredits: { availableCount: 2 },
1665 },
1666 resetCreditInput: { instanceId: "codex-credit" },
1667 });
1668 expect(report?.accounts[0]?.limits.unavailable).toBeUndefined();
1669 }
1670 });
1671
1672 it("merges native workspace duplicates only while the workspace evidence is unambiguous", () => {
1673 const known = provider({
1674 ...selected,
1675 instanceId: ProviderInstanceId.make("workspace-a"),
1676 auth: { ...selected.auth, workspaceId: "ws-a" },
1677 });
1678 const fresh = provider({
1679 ...known,
1680 instanceId: ProviderInstanceId.make("workspace-a-fresh"),
1681 usageLimits: { ...limits, checkedAt: "2026-09-03T11:30:00.000Z" },
1682 });
1683 const natives = [known, fresh, selected];
1684 expect(
1685 collectProviderUsageLimits(selected.instanceId, natives, [], now)?.accounts.map(
1686 (account) => account.id,
1687 ),
1688 ).toEqual(["workspace-a-fresh"]);
1689
1690 const unreadable = provider({
1691 instanceId: ProviderInstanceId.make("workspace-b"),
1692 auth: { ...selected.auth, workspaceId: "ws-b" },
1693 });
1694 expect(
1695 collectProviderUsageLimits(
1696 selected.instanceId,
1697 [...natives, unreadable],
1698 [],
1699 now,
1700 )?.accounts.map((account) => account.id),
1701 ).toEqual(["workspace-a-fresh", "codex"]);
1702 expect(
1703 collectProviderUsageLimits(
1704 selected.instanceId,
1705 [...natives, { ...unreadable, usageLimits: limits }],
1706 [],
1707 now,
1708 )?.accounts.map((account) => account.id),
1709 ).toEqual(["workspace-a-fresh", "codex", "workspace-b"]);
1710 });
1711
1712 it("supports a source-only provider and keeps duplicates when the native probe failed", () => {
1713 expect(
1714 collectProviderUsageLimits(selected.instanceId, [provider({})], sources, now)?.accounts.map(
1715 (account) => account.id,
1716 ),
1717 ).toEqual(["hub:duplicate", "hub:oss"]);
1718 const failed = provider({ usageLimits: { ...limits, unavailable: { reason: "probeFailed" } } });
1719 expect(
1720 collectProviderUsageLimits(selected.instanceId, [failed], sources, now)?.accounts.map(
1721 (account) => account.id,
1722 ),
1723 ).toEqual(["codex", "hub:duplicate", "hub:oss"]);
1724 expect(collectProviderUsageLimits(selected.instanceId, [provider({})], [], now)).toBeNull();
1725 expect(
1726 collectProviderUsageLimits(
1727 selected.instanceId,
1728 [provider({ enabled: false, usageLimits: limits })],
1729 [],
1730 now,
1731 ),
1732 ).toBeNull();
1733 });
1734
1735 it("surfaces source errors only for sources that carry the selected driver", () => {
1736 const failing = { ...sources[0]!, error: "token expired" };
1737 expect(
1738 collectProviderUsageLimits(selected.instanceId, [selected], [failing], now)?.notices,
1739 ).toEqual(["Accounts: token expired"]);
1740 const claudeOnly = { ...failing, accounts: failing.accounts.slice(2) };
1741 expect(
1742 collectProviderUsageLimits(selected.instanceId, [selected], [claudeOnly], now)?.notices,
1743 ).toEqual([]);
1744 const unreadable = { ...failing, accounts: [] };
1745 expect(
1746 collectProviderUsageLimits(selected.instanceId, [selected], [unreadable], now)?.notices,
1747 ).toEqual(["Accounts: token expired"]);
1748 const sourceOnly = collectProviderUsageLimits(
1749 selected.instanceId,
1750 [provider({})],
1751 [unreadable],
1752 now,
1753 );
1754 expect(sourceOnly?.accounts).toEqual([]);
1755 expect(sourceOnly?.notices).toEqual(["Accounts: token expired"]);
1756 });
1757
1758 it("advertises global and workspace commands only for providers present in Limits", () => {
1759 const withWorkspace = provider({
1760 workspaceSnapshots: [
1761 { cwd: "/tmp/project", checkedAt: limits.checkedAt, slashCommands: [], skills: [] },
1762 ],
1763 });
1764 const [supported] = withUsageLimitsCommands([withWorkspace], sources);
1765 expect(supported?.slashCommands.map((command) => command.name)).toEqual(["usage-limits"]);
1766 expect(
1767 supported?.workspaceSnapshots?.[0]?.slashCommands.map((command) => command.name),
1768 ).toEqual(["usage-limits"]);
1769 expect(withUsageLimitsCommands([withWorkspace], [])[0]?.slashCommands).toEqual([]);
1770 const ownCommand = provider({
1771 slashCommands: [{ name: "usage-limits", description: "Provider's own" }],
1772 });
1773 expect(withUsageLimitsCommands([ownCommand], [])[0]?.slashCommands).toEqual([
1774 { name: "usage-limits", description: "Provider's own" },
1775 ]);
1776 const unreadable = { ...sources[0]!, accounts: [], error: "token expired" };
1777 expect(
1778 withUsageLimitsCommands([withWorkspace], [unreadable])[0]?.slashCommands.map(
1779 (command) => command.name,
1780 ),
1781 ).toEqual(["usage-limits"]);
1782 expect(
1783 withUsageLimitsCommands([selected], [])[0]?.slashCommands.map((command) => command.name),
1784 ).toEqual(["usage-limits"]);
1785 const unrelated = provider({ driver: ProviderDriverKind.make("claudeAgent") });
1786 const disabled = provider({ ...unrelated, enabled: false, usageLimits: limits });
1787 const mixed = withUsageLimitsCommands([selected, withWorkspace, unrelated, disabled], []);
1788 expect(mixed.map((entry) => entry.slashCommands.map((command) => command.name))).toEqual([
1789 ["usage-limits"],
1790 ["usage-limits"],
1791 [],
1792 [],
1793 ]);
1794 expect(mixed[2]).toBe(unrelated);
1795 expect(mixed[3]).toBe(disabled);
1796 });
1797 });
1798
1799 describe("sameUsageLimitCommandCoverage", () => {
1800 const codexAccount = {
1801 id: "a",
1802 driver: ProviderDriverKind.make("codex"),
1803 usageLimits: { checkedAt: "2026-09-03T11:00:00.000Z", windows: [] },
1804 };
1805 const base = {
1806 id: UsageLimitSourceId.make("hub"),
1807 kind: "cliproxy" as const,
1808 label: "Accounts",
1809 checkedAt: "2026-09-03T11:00:00.000Z",
1810 };
1811 it("ignores quota movement but not the drivers offered the command", () => {
1812 const withCodex = [{ ...base, accounts: [codexAccount] }];
1813 const withCodexLater = [
1814 {
1815 ...base,
1816 accounts: [
1817 {
1818 ...codexAccount,
1819 usageLimits: { ...codexAccount.usageLimits, checkedAt: "2026-09-03T12:00:00.000Z" },
1820 },
1821 ],
1822 },
1823 ];
1824 expect(sameUsageLimitCommandCoverage(withCodex, withCodexLater)).toBe(true);
1825 expect(sameUsageLimitCommandCoverage(withCodex, [{ ...base, accounts: [] }])).toBe(false);
1826 });
1827 it("treats a failed read as a change in coverage, in both directions", () => {
1828 const empty = [{ ...base, accounts: [] }];
1829 const failed = [{ ...base, accounts: [], error: "token expired" }];
1830 expect(sameUsageLimitCommandCoverage(empty, failed)).toBe(false);
1831 expect(sameUsageLimitCommandCoverage(failed, empty)).toBe(false);
1832 expect(
1833 sameUsageLimitCommandCoverage(failed, [{ ...base, accounts: [], error: "still down" }]),
1834 ).toBe(true);
1835 });
1836 });
1837
1838 describe("external usage settings", () => {
1839 it("deduplicates destinations across accounts and environments without inventing quota pools", () => {
1840 const managed = provider({
1841 usageLimits: {
1842 checkedAt: "2026-09-03T11:00:00.000Z",
1843 windows: [],
1844 unavailable: { reason: "unsupported", message: "Track usage in ChatGPT." },
1845 externalUsage: { label: "ChatGPT usage", url: "https://chatgpt.com/#settings/Usage" },
1846 },
1847 });
1848 const presentations = new Map([
1849 [
1850 EnvironmentId.make("a"),
1851 {
1852 entry: { target: { label: "A" } },
1853 serverConfig: {
1854 providers: [managed, { ...managed, instanceId: ProviderInstanceId.make("personal") }],
1855 },
1856 },
1857 ],
1858 [
1859 EnvironmentId.make("b"),
1860 { entry: { target: { label: "B" } }, serverConfig: { providers: [managed] } },
1861 ],
1862 ]);
1863 expect(collectExternalUsageLinks(presentations)).toEqual([
1864 {
1865 ...managed.usageLimits!.externalUsage,
1866 message: "Track usage in ChatGPT.",
1867 accounts: [`${managed.instanceId} on A`, "personal on A", `${managed.instanceId} on B`],
1868 },
1869 ]);
1870 expect(collectLimitAccounts(presentations)).toEqual([]);
1871 expect(collectLimitNotices(presentations)).toEqual([]);
1872 });
1873
1874 it("shows a notice once when environments with one label report the same failure", () => {
1875 const failing = provider({
1876 usageLimits: {
1877 checkedAt: "2026-09-03T11:00:00.000Z",
1878 windows: [],
1879 unavailable: { reason: "probeFailed" },
1880 },
1881 });
1882 const host = { entry: { target: { label: "Host" } }, serverConfig: { providers: [failing] } };
1883 const presentations = new Map([
1884 [EnvironmentId.make("a"), host],
1885 [EnvironmentId.make("b"), host],
1886 [EnvironmentId.make("c"), host],
1887 ]);
1888 expect(collectLimitNotices(presentations)).toEqual(["Host · codex: Could not read limits."]);
1889 });
1890 });
1891
1892 describe("ChatGPT sharing presentation", () => {
1893 it("requires verified sharing metadata rather than the Codex driver or login type", () => {
1894 const codex = provider({ auth: { status: "authenticated", type: "chatgpt" } });
1895 expect(usesChatGptSharing(codex)).toBe(false);
1896 expect(
1897 usesChatGptSharing({ ...codex, auth: { ...codex.auth, subscriptionSharing: true } }),
1898 ).toBe(true);
1899 expect(
1900 usesChatGptSharing({
1901 ...codex,
1902 auth: { status: "unauthenticated", subscriptionSharing: true },
1903 }),
1904 ).toBe(false);
1905 });
1906 });