Open History to see the last commit
1import {
2 DEFAULT_SERVER_SETTINGS,
3 EnvironmentId,
4 ProviderDriverKind,
5 ProviderInstanceId,
6 type ServerProvider,
7 UsageLimitSourceId,
8} from "@t3tools/contracts";
9import { describe, expect, it } from "vite-plus/test";
10
11import {
12 type LimitAccount,
13 collectProviderUsageLimits,
14 sameUsageLimitCommandCoverage,
15 withUsageLimitsCommands,
16 collectLimitAccounts,
17 collectExternalUsageLinks,
18 collectLimitNotices,
19 collectLimitPools,
20 elapsedShare,
21 exhaustedUsageWindow,
22 paceOf,
23 paceRemainingPercent,
24 usesChatGptSharing,
25 resolveNewThreadModelSelection,
26} from "./usageLimits.ts";
27
28const now = Date.parse("2026-09-03T12:00:00.000Z");
29
30const window = {
31 id: "five_hour",
32 kind: "session",
33 label: "Session",
34 usedPercent: 40,
35 windowDurationMins: 300,
36 resetsAt: "2026-09-03T14:00:00.000Z",
37} as const;
38
39function provider(overrides: Partial<ServerProvider>): ServerProvider {
40 return {
41 instanceId: ProviderInstanceId.make("codex"),
42 driver: ProviderDriverKind.make("codex"),
43 enabled: true,
44 installed: true,
45 version: null,
46 status: "ready",
47 auth: { status: "authenticated" },
48 checkedAt: "2026-09-03T11:00:00.000Z",
49 models: [],
50 slashCommands: [],
51 skills: [],
52 ...overrides,
53 };
54}
55
56describe("new thread model fallback", () => {
57 const selection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6.1-sol" };
58 const fallback = { instanceId: ProviderInstanceId.make("claude"), model: "claude-fable-5-1" };
59 const limited = provider({
60 usageLimits: {
61 checkedAt: "2026-09-03T11:00:00.000Z",
62 windows: [{ ...window, usedPercent: 100 }],
63 },
64 });
65 const available = provider({
66 instanceId: fallback.instanceId,
67 driver: ProviderDriverKind.make("claudeAgent"),
68 });
69
70 const defaults = {
71 defaultSelection: selection,
72 fallbackSelection: fallback,
73 providers: [limited, available],
74 now,
75 };
76 it.each([
77 ["exhausted default", {}, fallback],
78 ["explicit selection", { explicitSelection: selection }, selection],
79 ["missing default", { defaultSelection: null }, null],
80 ["no fallback", { fallbackSelection: null }, selection],
81 ["expired window", { now: Date.parse("2026-09-04T00:00:00Z") }, selection],
82 [
83 "environment disabled",
84 {
85 settings: {
86 ...DEFAULT_SERVER_SETTINGS,
87 providerInstances: {
88 [fallback.instanceId]: { driver: available.driver, enabled: false, config: {} },
89 },
90 },
91 },
92 selection,
93 ],
94 ] as const)("resolves %s", (_name, overrides, expected) => {
95 expect(resolveNewThreadModelSelection({ ...defaults, ...overrides }).selection).toEqual(
96 expected,
97 );
98 });
99 it.each([
100 { enabled: false },
101 { installed: false },
102 { auth: { status: "unauthenticated" as const } },
103 { availability: "unavailable" as const },
104 { usageLimits: limited.usageLimits },
105 ])("rejects an unusable fallback: %j", (overrides) => {
106 expect(
107 resolveNewThreadModelSelection({
108 ...defaults,
109 providers: [limited, { ...available, ...overrides }],
110 }).selection,
111 ).toEqual(selection);
112 });
113 it.each([undefined, "invalid"])("treats an unknown reset as exhausted: %s", (resetsAt) => {
114 expect(
115 exhaustedUsageWindow(
116 provider({
117 usageLimits: {
118 checkedAt: limited.checkedAt,
119 windows: [{ ...window, usedPercent: 100, resetsAt }],
120 },
121 }),
122 now,
123 ),
124 ).toBeDefined();
125 });
126 it.each([
127 ["cursor", ["autoPercentUsed"], "claude-opus-5-5", false],
128 ["cursor", ["autoPercentUsed"], "composer-2.5", false],
129 ["cursor", ["autoPercentUsed", "apiPercentUsed"], "composer-2.5", true],
130 ["antigravity", ["gemini-weekly"], "claude-opus-5-5", false],
131 ["antigravity", ["3p-weekly"], "claude-opus-5-5", true],
132 ["antigravity", ["gemini-weekly"], "antigravity-default", true],
133 ["opencode", ["go_weekly"], "opencode/big-pickle", false],
134 ["opencode", ["go_weekly"], "opencode-go/big-pickle", true],
135 ] as const)("matches %s pools %s to %s", (driver, ids, model, usesFallback) => {
136 const defaultSelection = { ...selection, model };
137 expect(
138 resolveNewThreadModelSelection({
139 ...defaults,
140 defaultSelection,
141 providers: [
142 provider({
143 driver: ProviderDriverKind.make(driver),
144 usageLimits: {
145 checkedAt: limited.checkedAt,
146 windows: ids.map((id) => ({ ...window, id, usedPercent: 100 })),
147 },
148 }),
149 available,
150 ],
151 }).selection,
152 ).toEqual(usesFallback ? fallback : defaultSelection);
153 });
154});
155
156describe("pace", () => {
157 it("places the clock three fifths through a five-hour window with two hours left", () => {
158 expect(elapsedShare(window, now)).toBeCloseTo(0.6);
159 expect(paceRemainingPercent(window, now)).toBe(40);
160 expect(paceOf(window, now)).toBe("under");
161 expect(paceOf({ ...window, usedPercent: 62 }, now)).toBe("on");
162 expect(paceOf({ ...window, usedPercent: 80 }, now)).toBe("ahead");
163 });
164});
165
166describe("pools", () => {
167 const checkedAt = "2026-09-03T11:00:00.000Z";
168 const weekly = {
169 id: "seven_day",
170 kind: "weekly",
171 label: "Weekly",
172 windowDurationMins: 7 * 24 * 60,
173 resetsAt: "2026-09-06T12:00:00.000Z",
174 } as const;
175 const claude = ProviderDriverKind.make("claudeAgent");
176 const source = {
177 id: UsageLimitSourceId.make("hub"),
178 kind: "cliproxy" as const,
179 label: "hub",
180 checkedAt,
181 };
182 const laptop = { entry: { target: { label: "Laptop" } } };
183
184 it("merges one account reported natively on two environments and by a hub into one entry", () => {
185 const native = provider({
186 driver: claude,
187 instanceId: ProviderInstanceId.make("claude"),
188 auth: { status: "authenticated", email: "Same@example.com" },
189 usageLimits: { checkedAt, windows: [{ ...window, usedPercent: 40 }] },
190 });
191 const input = new Map([
192 [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { providers: [native] } }],
193 [
194 EnvironmentId.make("env-b"),
195 {
196 entry: { target: { label: "Desktop" } },
197 serverConfig: {
198 providers: [
199 {
200 ...native,
201 usageLimits: {
202 checkedAt: "2026-09-03T11:30:00.000Z",
203 windows: [{ ...window, usedPercent: 55 }],
204 },
205 },
206 ],
207 usageLimitSources: [
208 {
209 ...source,
210 accounts: [
211 {
212 id: "claude-same@example.com.json",
213 driver: claude,
214 email: "same@example.com",
215 plan: "Claude Subscription",
216 usageLimits: { checkedAt, windows: [{ ...window, usedPercent: 10 }] },
217 },
218 ],
219 },
220 ],
221 },
222 },
223 ],
224 ]);
225 const accounts = collectLimitAccounts(input);
226 expect(accounts).toHaveLength(1);
227 expect(accounts[0]).toMatchObject({
228 key: "env-a:claude",
229 sourceLabel: null,
230 redeem: { environmentId: "env-b", input: { instanceId: "claude" } },
231 environments: [
232 { environmentId: "env-a", label: "Laptop" },
233 { environmentId: "env-b", label: "Desktop" },
234 ],
235 });
236 expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(55);
237 });
238
239 it("uses the freshest reported plan even when the newest quota has no plan", () => {
240 const snapshot = (label: string | undefined, checkedAt: string, usedPercent: number) =>
241 provider({
242 driver: claude,
243 auth: { status: "authenticated", email: "same@example.com", label },
244 usageLimits: { checkedAt, windows: [{ ...window, usedPercent }] },
245 });
246 const stale = snapshot("Claude Team Subscription", checkedAt, 40);
247 const fresh = snapshot("Claude Max Subscription", "2026-09-03T11:30:00.000Z", 7);
248 const newest = snapshot(undefined, "2026-09-03T12:00:00.000Z", 5);
249 for (const [reports, plan, usedPercent] of [
250 [[stale, fresh], "Claude Max Subscription", 7],
251 [[stale, newest], "Claude Team Subscription", 5],
252 [[stale, fresh, newest], "Claude Max Subscription", 5],
253 ] as const) {
254 for (const order of reports.length === 2
255 ? [reports, reports.toReversed()]
256 : [
257 [stale, fresh, newest],
258 [stale, newest, fresh],
259 [fresh, stale, newest],
260 [fresh, newest, stale],
261 [newest, stale, fresh],
262 [newest, fresh, stale],
263 ]) {
264 const accounts = collectLimitAccounts(
265 new Map(
266 order.map((entry, index) => [
267 EnvironmentId.make(`env-${index}`),
268 { ...laptop, serverConfig: { providers: [entry] } },
269 ]),
270 ),
271 );
272 expect(accounts).toHaveLength(1);
273 expect(accounts[0]?.plan).toBe(plan);
274 expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(usedPercent);
275 }
276 }
277 });
278
279 it("merges OpenCode Go limits from machines with the same API key", () => {
280 const go = provider({
281 driver: ProviderDriverKind.make("opencode"),
282 instanceId: ProviderInstanceId.make("opencode"),
283 auth: { status: "authenticated" },
284 usageLimits: {
285 checkedAt,
286 credentialFingerprint: "shared-go-key",
287 windows: [{ ...window, id: "go_rolling", usedPercent: 3 }],
288 },
289 });
290 const input = new Map([
291 [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { providers: [go] } }],
292 [
293 EnvironmentId.make("env-b"),
294 {
295 entry: { target: { label: "Desktop" } },
296 serverConfig: {
297 providers: [
298 {
299 ...go,
300 usageLimits: {
301 ...go.usageLimits!,
302 checkedAt: "2026-09-03T11:30:00.000Z",
303 windows: [{ ...window, id: "go_rolling", usedPercent: 4 }],
304 },
305 },
306 ],
307 },
308 },
309 ],
310 ]);
311 const accounts = collectLimitAccounts(input);
312 expect(accounts).toHaveLength(1);
313 expect(accounts[0]?.environments).toEqual([
314 { environmentId: "env-a", label: "Laptop" },
315 { environmentId: "env-b", label: "Desktop" },
316 ]);
317 expect(collectLimitPools(accounts, now)[0]?.windows[0]?.members).toHaveLength(1);
318 expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(4);
319
320 const differentKey = {
321 ...go,
322 usageLimits: { ...go.usageLimits!, credentialFingerprint: "other-go-key" },
323 };
324 input.set(EnvironmentId.make("env-b"), {
325 entry: { target: { label: "Desktop" } },
326 serverConfig: { providers: [differentKey] },
327 });
328 expect(collectLimitAccounts(input)).toHaveLength(2);
329
330 input.set(EnvironmentId.make("env-a"), {
331 ...laptop,
332 serverConfig: {
333 providers: [{ ...go, auth: { status: "authenticated", email: "same@example.com" } }],
334 },
335 });
336 input.set(EnvironmentId.make("env-b"), {
337 entry: { target: { label: "Desktop" } },
338 serverConfig: {
339 providers: [
340 { ...differentKey, auth: { status: "authenticated", email: "SAME@example.com" } },
341 ],
342 },
343 });
344 expect(collectLimitAccounts(input)).toHaveLength(1);
345 });
346
347 it("takes windows from a fresher hub read but credits and redeem from the native instance", () => {
348 const native = provider({
349 driver: claude,
350 instanceId: ProviderInstanceId.make("claude"),
351 auth: { status: "authenticated", email: "same@example.com" },
352 usageLimits: {
353 checkedAt,
354 windows: [{ ...window, usedPercent: 40 }],
355 resetCredits: { availableCount: 2 },
356 },
357 });
358 const input = new Map([
359 [
360 EnvironmentId.make("env-a"),
361 {
362 ...laptop,
363 serverConfig: {
364 providers: [native],
365 usageLimitSources: [
366 {
367 ...source,
368 accounts: [
369 {
370 id: "claude-same@example.com.json",
371 driver: claude,
372 email: "same@example.com",
373 usageLimits: {
374 checkedAt: "2026-09-03T11:30:00.000Z",
375 windows: [{ ...window, usedPercent: 55 }],
376 },
377 },
378 ],
379 },
380 ],
381 },
382 },
383 ],
384 ]);
385 const [account] = collectLimitAccounts(input);
386 expect(account?.limits.windows[0]?.usedPercent).toBe(55);
387 expect(account?.limits.resetCredits?.availableCount).toBe(2);
388 expect(account?.redeem).toEqual({ environmentId: "env-a", input: { instanceId: "claude" } });
389 expect(account?.environments).toEqual([{ environmentId: "env-a", label: "Laptop" }]);
390 });
391
392 it("redeems through the hub when it holds a credit, even with a fresher native read", () => {
393 const native = provider({
394 driver: claude,
395 instanceId: ProviderInstanceId.make("claude"),
396 auth: { status: "authenticated", email: "same@example.com" },
397 usageLimits: {
398 checkedAt: "2026-09-03T11:30:00.000Z",
399 windows: [{ ...window, usedPercent: 40 }],
400 resetCredits: { availableCount: 3, nextCreditId: "native-credit" },
401 },
402 });
403 const input = new Map([
404 [
405 EnvironmentId.make("env-a"),
406 {
407 ...laptop,
408 serverConfig: {
409 providers: [native],
410 usageLimitSources: [
411 {
412 ...source,
413 accounts: [
414 {
415 id: "claude-same@example.com.json",
416 driver: claude,
417 email: "same@example.com",
418 usageLimits: {
419 checkedAt,
420 windows: [{ ...window, usedPercent: 55 }],
421 resetCredits: { availableCount: 2, nextCreditId: "hub-credit" },
422 },
423 },
424 ],
425 },
426 ],
427 },
428 },
429 ],
430 ]);
431 const [account] = collectLimitAccounts(input);
432 expect(account?.redeem).toEqual({
433 environmentId: "env-a",
434 input: { sourceId: "hub", accountId: "claude-same@example.com.json", creditId: "hub-credit" },
435 });
436 expect(account?.limits.resetCredits?.availableCount).toBe(3);
437 });
438
439 it("redeems on the environment whose snapshot supplied the credits on show", () => {
440 const stale = provider({
441 auth: { status: "authenticated", email: "same@example.com" },
442 usageLimits: {
443 checkedAt,
444 windows: [window],
445 resetCredits: { availableCount: 0 },
446 },
447 });
448 const fresh = {
449 ...stale,
450 usageLimits: {
451 checkedAt: "2026-09-03T11:30:00.000Z",
452 windows: [window],
453 resetCredits: { availableCount: 2 },
454 },
455 };
456 const input = new Map([
457 [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { providers: [stale] } }],
458 [
459 EnvironmentId.make("env-b"),
460 { entry: { target: { label: "Desktop" } }, serverConfig: { providers: [fresh] } },
461 ],
462 ]);
463 const [account] = collectLimitAccounts(input);
464 expect(account?.limits.resetCredits?.availableCount).toBe(2);
465 expect(account?.redeem).toEqual({ environmentId: "env-b", input: { instanceId: "codex" } });
466 });
467
468 it("keeps distinct hub accounts redeemable through their own source", () => {
469 const hubAccounts = ["first", "second"].map((id) => ({
470 id,
471 driver: ProviderDriverKind.make("codex"),
472 email: `${id}@example.com`,
473 usageLimits: {
474 checkedAt,
475 windows: [window],
476 resetCredits: { availableCount: 2, nextCreditId: `${id}-credit` },
477 },
478 }));
479 const input = new Map([
480 [
481 EnvironmentId.make("env-a"),
482 {
483 ...laptop,
484 serverConfig: {
485 providers: [],
486 usageLimitSources: [{ ...source, accounts: hubAccounts }],
487 },
488 },
489 ],
490 ]);
491 expect(collectLimitAccounts(input).map((account) => account.redeem)).toEqual(
492 hubAccounts.map((account) => ({
493 environmentId: "env-a",
494 input: { sourceId: "hub", accountId: account.id, creditId: `${account.id}-credit` },
495 })),
496 );
497 });
498
499 it("does not give old credits the timestamp of a newer window-only read", () => {
500 const snapshots = [
501 { checkedAt, windows: [window], resetCredits: { availableCount: 2 } },
502 { checkedAt: "2026-09-03T12:00:00.000Z", windows: [window] },
503 {
504 checkedAt: "2026-09-03T11:30:00.000Z",
505 windows: [window],
506 resetCredits: { availableCount: 1 },
507 },
508 ];
509 const input = new Map(
510 snapshots.map((usageLimits, i) => [
511 EnvironmentId.make(`env-${i}`),
512 {
513 ...laptop,
514 serverConfig: {
515 providers: [
516 provider({
517 auth: { status: "authenticated", email: "same@example.com" },
518 usageLimits,
519 }),
520 ],
521 },
522 },
523 ]),
524 );
525 const [account] = collectLimitAccounts(input);
526 expect(account?.limits.checkedAt).toBe("2026-09-03T12:00:00.000Z");
527 expect(account?.limits.resetCredits?.availableCount).toBe(1);
528 expect(account?.redeem?.environmentId).toBe("env-2");
529 });
530
531 it("keeps one email in two workspaces apart while merging each workspace's duplicates", () => {
532 const login = (instanceId: string, workspaceId: string, usedPercent: number) =>
533 provider({
534 instanceId: ProviderInstanceId.make(instanceId),
535 auth: { status: "authenticated", email: "same@example.com", workspaceId },
536 usageLimits: { checkedAt, windows: [{ ...weekly, usedPercent }] },
537 });
538 const hubAccount = (id: string, workspaceId?: string) => ({
539 id,
540 driver: ProviderDriverKind.make("codex"),
541 email: "same@example.com",
542 ...(workspaceId ? { workspaceId } : {}),
543 usageLimits: { checkedAt, windows: [{ ...weekly, usedPercent: 50 }] },
544 });
545 const input = new Map([
546 [
547 EnvironmentId.make("env-a"),
548 {
549 ...laptop,
550 serverConfig: {
551 providers: [login("business", "ws-business", 8), login("personal", "ws-plus", 26)],
552 usageLimitSources: [
553 { ...source, accounts: [hubAccount("plus.json", "ws-plus"), hubAccount("x.json")] },
554 ],
555 },
556 },
557 ],
558 [
559 EnvironmentId.make("env-b"),
560 {
561 entry: { target: { label: "Desktop" } },
562 serverConfig: { providers: [login("personal", "ws-plus", 26)] },
563 },
564 ],
565 ]);
566 const accounts = collectLimitAccounts(input);
567 expect(accounts.map((account) => account.key)).toEqual([
568 "env-a:business",
569 "env-a:personal",
570 "hub:x.json",
571 ]);
572 expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(8);
573 const withoutEmail = (id: string, workspaceId: string) => {
574 const { email: _email, ...account } = hubAccount(id, workspaceId);
575 return account;
576 };
577 const sameFile = new Map([
578 [
579 EnvironmentId.make("env-a"),
580 {
581 ...laptop,
582 serverConfig: {
583 providers: [],
584 usageLimitSources: [{ ...source, accounts: [withoutEmail("a.json", "ws-1")] }],
585 },
586 },
587 ],
588 [
589 EnvironmentId.make("env-b"),
590 {
591 ...laptop,
592 serverConfig: {
593 providers: [],
594 usageLimitSources: [{ ...source, accounts: [withoutEmail("a.json", "ws-2")] }],
595 },
596 },
597 ],
598 ]);
599 expect(collectLimitAccounts(sameFile).map((account) => account.key)).toEqual([
600 "hub:a.json:ws-1",
601 "hub:a.json:ws-2",
602 ]);
603 expect(accounts[1]?.environments.map((environment) => environment.label)).toEqual([
604 "Laptop",
605 "Desktop",
606 ]);
607 });
608
609 it("joins a report without a workspace to the only workspace signed in with its email", () => {
610 const native = provider({
611 driver: claude,
612 auth: { status: "authenticated", email: "same@example.com", workspaceId: "org-a" },
613 usageLimits: { checkedAt, windows: [window] },
614 });
615 const hubAccount = {
616 id: "claude.json",
617 driver: claude,
618 email: "same@example.com",
619 usageLimits: { checkedAt, windows: [window] },
620 };
621 const withOther = (other: ServerProvider) =>
622 new Map([
623 [
624 EnvironmentId.make("env-a"),
625 {
626 ...laptop,
627 serverConfig: {
628 providers: [native, other],
629 usageLimitSources: [{ ...source, accounts: [hubAccount] }],
630 },
631 },
632 ],
633 ]);
634 const unrelated = provider({ instanceId: ProviderInstanceId.make("codex-2") });
635 expect(collectLimitAccounts(withOther(unrelated)).map((account) => account.key)).toEqual([
636 "env-a:codex",
637 ]);
638 const unreadable = provider({
639 ...native,
640 instanceId: ProviderInstanceId.make("team"),
641 auth: { ...native.auth, workspaceId: "org-b" },
642 usageLimits: { checkedAt, windows: [], unavailable: { reason: "probeFailed" } },
643 });
644 expect(collectLimitAccounts(withOther(unreadable)).map((account) => account.key)).toEqual([
645 "env-a:codex",
646 "hub:claude.json",
647 ]);
648 });
649
650 it("keys a hub account without an email by hub, so two environments on one hub share it", () => {
651 const seat = {
652 id: "claude-team-seat.json",
653 driver: claude,
654 usageLimits: { checkedAt, windows: [window] },
655 };
656 const hub = { ...source, accounts: [seat] };
657 const input = new Map([
658 [
659 EnvironmentId.make("env-a"),
660 { ...laptop, serverConfig: { providers: [], usageLimitSources: [hub] } },
661 ],
662 [
663 EnvironmentId.make("env-b"),
664 {
665 entry: { target: { label: "Desktop" } },
666 serverConfig: { providers: [], usageLimitSources: [hub] },
667 },
668 ],
669 ]);
670 const accounts = collectLimitAccounts(input);
671 expect(accounts.map((account) => account.key)).toEqual(["hub:claude-team-seat.json"]);
672 expect(accounts[0]?.displayName).toBe("claude-team-seat");
673 });
674
675 it("pools Codex windows by kind, whichever slot reported them", () => {
676 const codexAccount = (id: string, slots: readonly string[]) => ({
677 id,
678 driver: ProviderDriverKind.make("codex"),
679 usageLimits: {
680 checkedAt,
681 windows: slots.map((slot) => ({ ...weekly, id: slot, usedPercent: 50 })),
682 },
683 });
684 const pooled = (accounts: ReturnType<typeof codexAccount>[]) =>
685 collectLimitPools(
686 collectLimitAccounts(
687 new Map([
688 [
689 EnvironmentId.make("env-a"),
690 {
691 ...laptop,
692 serverConfig: { providers: [], usageLimitSources: [{ ...source, accounts }] },
693 },
694 ],
695 ]),
696 ),
697 now,
698 )[0]?.windows ?? [];
699 for (const order of [
700 [codexAccount("business", ["primary"]), codexAccount("plus", ["secondary"])],
701 [codexAccount("plus", ["secondary"]), codexAccount("business", ["primary"])],
702 ]) {
703 const windows = pooled(order);
704 expect(windows.map((window) => window.id)).toEqual(["weekly"]);
705 expect(windows[0]?.members).toHaveLength(2);
706 }
707 expect(
708 pooled([codexAccount("a", ["secondary"]), codexAccount("b", ["primary", "secondary"])]).map(
709 (window) => window.id,
710 ),
711 ).toEqual(["weekly", "weekly:secondary"]);
712 });
713
714 it("pools windows by id across accounts and orders resets by when they land", () => {
715 const input = new Map([
716 [
717 EnvironmentId.make("env-a"),
718 {
719 ...laptop,
720 serverConfig: {
721 providers: [],
722 usageLimitSources: [
723 {
724 ...source,
725 accounts: [
726 {
727 id: "a",
728 driver: claude,
729 usageLimits: {
730 checkedAt,
731 windows: [
732 { ...window, usedPercent: 80, resetsAt: "2026-09-03T13:00:00.000Z" },
733 { ...weekly, usedPercent: 20 },
734 ],
735 },
736 },
737 {
738 id: "b",
739 driver: claude,
740 usageLimits: {
741 checkedAt,
742 windows: [{ ...window, usedPercent: 40 }],
743 },
744 },
745 {
746 id: "c",
747 driver: ProviderDriverKind.make("codex"),
748 usageLimits: { checkedAt, windows: [{ ...weekly, usedPercent: 50 }] },
749 },
750 {
751 id: "unsupported",
752 driver: claude,
753 usageLimits: {
754 checkedAt,
755 windows: [],
756 unavailable: { reason: "unsupported" as const },
757 },
758 },
759 ],
760 },
761 ],
762 },
763 },
764 ],
765 ]);
766 const pools = collectLimitPools(collectLimitAccounts(input), now);
767 expect(pools.map((pool) => [pool.driver, pool.accounts.length])).toEqual([
768 ["claudeAgent", 2],
769 ["codex", 1],
770 ]);
771 const [session, week] = pools[0]!.windows;
772 const untimed = collectLimitPools(
773 collectLimitAccounts(input).map((account) =>
774 account.key === "hub:b"
775 ? {
776 ...account,
777 limits: {
778 ...account.limits,
779 windows: account.limits.windows.map((w) => ({ ...w, resetsAt: undefined })),
780 },
781 }
782 : account,
783 ),
784 now,
785 );
786 expect(untimed[0]?.windows[0]?.pace).toBe("on");
787 expect(session).toMatchObject({
788 id: "five_hour",
789 remainingPercent: 40,
790 usedPercent: 60,
791 pace: "under",
792 });
793 expect(
794 session?.resets.map((reset) => [reset.member.account.key, reset.restoresPercent]),
795 ).toEqual([
796 ["hub:a", 40],
797 ["hub:b", 20],
798 ]);
799 expect(week).toMatchObject({ id: "seven_day", remainingPercent: 80, members: [{}] });
800 // Codex reports `primary` for both its five-hour and (on Go) monthly window.
801 const mixed = collectLimitPools(
802 [
803 ...collectLimitAccounts(input),
804 {
805 key: "go",
806 driver: claude,
807 displayName: "Go",
808 email: undefined,
809 plan: undefined,
810 accentColor: undefined,
811 environments: [],
812 sourceLabel: null,
813 redeem: null,
814 limits: {
815 checkedAt,
816 windows: [
817 {
818 id: "five_hour",
819 kind: "monthly",
820 label: "Monthly",
821 usedPercent: 82,
822 windowDurationMins: 30 * 24 * 60,
823 resetsAt: "2026-09-14T12:00:00.000Z",
824 },
825 ],
826 },
827 },
828 ],
829 now,
830 );
831 expect(mixed[0]?.windows.map((window) => [window.kind, window.members.length])).toEqual([
832 ["session", 2],
833 ["weekly", 1],
834 ["monthly", 1],
835 ]);
836 expect(session?.members.map((member) => member.account.key)).toEqual(["hub:a", "hub:b"]);
837 expect(pools[0]?.accounts.map((account) => account.key)).toEqual(["hub:a", "hub:b"]);
838 });
839});
840
841describe("pooled account columns", () => {
842 const weekly = {
843 ...window,
844 id: "seven_day",
845 kind: "weekly",
846 label: "Weekly",
847 windowDurationMins: 7 * 24 * 60,
848 } as const;
849 const account = (key: string, windows: LimitAccount["limits"]["windows"]): LimitAccount => ({
850 key,
851 driver: ProviderDriverKind.make("claudeAgent"),
852 displayName: key,
853 email: undefined,
854 plan: undefined,
855 accentColor: undefined,
856 environments: [],
857 sourceLabel: "Hub",
858 redeem: null,
859 limits: { checkedAt: "2026-09-03T11:00:00.000Z", windows },
860 });
861 const keys = (pool: ReturnType<typeof collectLimitPools>[number]) =>
862 pool.windows.map((row) =>
863 row.columns.map((member) => (member.window ? member.account.key : null)),
864 );
865
866 // regression: #20349 sessions stay visible while the weekly quota is exhausted
867 it.each([
868 ["claudeAgent", "13:00", 40, "14:00", 100],
869 ["codex", "14:00", 100, "14:00", 100],
870 ["claudeAgent", "15:00", 100, "15:00", 100],
871 ["codex", "15:00", 40, "14:00", 60],
872 ] as const)(
873 "%s session resetting at %s with %i percent spent becomes usable at %s with %i percent restored",
874 (driver, sessionReset, usedPercent, usableAt, restoresPercent) => {
875 const at = (time: string) => `2026-09-03T${time}:00.000Z`;
876 const a = {
877 ...account("a", [
878 {
879 ...window,
880 id: driver === "codex" ? "primary" : window.id,
881 usedPercent,
882 resetsAt: at(sessionReset),
883 },
884 {
885 ...weekly,
886 id: driver === "codex" ? "secondary" : weekly.id,
887 usedPercent: 100,
888 resetsAt: at("14:00"),
889 },
890 ]),
891 driver: ProviderDriverKind.make(driver),
892 };
893 const [session] = collectLimitPools([a], now)[0]!.windows;
894 expect.soft(session?.remainingPercent).toBe(0);
895 expect(session?.resets[0]).toMatchObject({
896 at: Date.parse(at(usableAt)),
897 restoresPercent,
898 });
899 },
900 );
901
902 it("excludes weekly-blocked sessions from the pool without changing snapshots or model allowances", () => {
903 const blocked = account("blocked", [
904 window,
905 { ...weekly, usedPercent: 100 },
906 { ...weekly, id: "seven_day_fable", usedPercent: 20 },
907 ]);
908 const accounts = [
909 blocked,
910 account("available", [
911 { ...window, usedPercent: 20 },
912 { ...weekly, usedPercent: 99 },
913 { ...weekly, id: "seven_day_fable", usedPercent: 40 },
914 ]),
915 { ...blocked, key: "cursor", driver: ProviderDriverKind.make("cursor") },
916 ];
917 const snapshot = structuredClone(accounts);
918 const [claude, cursor] = collectLimitPools(accounts, now);
919 expect.soft(claude?.windows.map((row) => row.remainingPercent)).toEqual([40, 1, 70]);
920 expect.soft(cursor?.windows.map((row) => row.remainingPercent)).toEqual([60, 0, 80]);
921 expect(accounts).toEqual(snapshot);
922 });
923
924 it("keeps session columns across rows with opposite reset and usage orders", () => {
925 const accounts = [
926 account("a", [
927 { ...weekly, usedPercent: 80, resetsAt: "2026-09-05T12:00:00.000Z" },
928 { ...window, usedPercent: 10, resetsAt: "2026-09-03T15:00:00.000Z" },
929 ]),
930 account("b", [
931 { ...weekly, usedPercent: 20, resetsAt: "2026-09-06T12:00:00.000Z" },
932 { ...window, usedPercent: 90, resetsAt: "2026-09-03T13:00:00.000Z" },
933 ]),
934 ];
935 const [pool] = collectLimitPools(accounts, now);
936 expect(pool!.accounts.map((account) => account.key)).toEqual(["b", "a"]);
937 expect(keys(pool!)).toEqual([
938 ["b", "a"],
939 ["b", "a"],
940 ]);
941 expect(pool!.windows[1]!.resets.map((reset) => reset.member.account.key)).toEqual(["a", "b"]);
942 expect(pool!.windows[1]!.remainingPercent).toBe(50);
943 expect(keys(collectLimitPools(accounts.toReversed(), now)[0]!)).toEqual(keys(pool!));
944 });
945
946 it.each([undefined, "invalid", "2026-09-03T11:30:00.000Z"])(
947 "keeps blocked sessions empty without predicting a refill from a missing or stale clock (%s)",
948 (resetsAt) => {
949 const [pool] = collectLimitPools(
950 [
951 account("session-clock", [
952 { ...window, resetsAt },
953 { ...weekly, usedPercent: 100 },
954 ]),
955 account("weekly-clock", [window, { ...weekly, usedPercent: 100, resetsAt }]),
956 ],
957 now,
958 );
959 expect(pool!.windows[0]).toMatchObject({ remainingPercent: 0, pace: null, resets: [] });
960 expect(pool!.windows[0]!.columns.map((column) => column.window?.resetsAt)).toEqual([
961 undefined,
962 undefined,
963 ]);
964 },
965 );
966
967 it("orders by usable session refill and clears suppression after a fresh weekly reading", () => {
968 const blocked = account("blocked", [
969 { ...window, resetsAt: "2026-09-03T13:00:00.000Z" },
970 { ...weekly, usedPercent: 100, resetsAt: "2026-09-03T15:00:00.000Z" },
971 ]);
972 const available = account("available", [window]);
973 const [before] = collectLimitPools([blocked, available], now);
974 expect(before!.accounts.map((account) => account.key)).toEqual(["available", "blocked"]);
975 expect(before!.windows[0]!.remainingPercent).toBe(30);
976 const refreshed = {
977 ...blocked,
978 limits: {
979 checkedAt: "2026-09-03T12:00:00.000Z",
980 windows: [blocked.limits.windows[0]!, { ...weekly, usedPercent: 10 }],
981 },
982 };
983 const [after] = collectLimitPools([refreshed, available], now);
984 expect(after!.accounts.map((account) => account.key)).toEqual(["blocked", "available"]);
985 expect(after!.windows[0]!.remainingPercent).toBe(60);
986 expect(after!.windows[0]!.resets[0]).toMatchObject({
987 at: Date.parse("2026-09-03T13:00:00.000Z"),
988 restoresPercent: 20,
989 });
990 });
991
992 it("preserves gaps without counting missing windows toward pooled quota", () => {
993 const [pool] = collectLimitPools(
994 [
995 account("a", [window]),
996 account("b", [
997 { ...window, resetsAt: "2026-09-03T15:00:00.000Z" },
998 { ...weekly, usedPercent: 80 },
999 ]),
1000 account("c", [weekly]),
1001 ],
1002 now,
1003 );
1004 expect(keys(pool!)).toEqual([
1005 ["a", "b", null],
1006 [null, "b", "c"],
1007 ]);
1008 expect(pool!.windows[1]!.members.map((member) => member.account.key)).toEqual(["b", "c"]);
1009 expect(pool!.windows[1]!.remainingPercent).toBe(40);
1010 expect(pool!.windows[1]!.resets.map((reset) => reset.restoresPercent)).toEqual([40, 20]);
1011 });
1012
1013 it("falls back to weekly resets when no account reports a session", () => {
1014 const [pool] = collectLimitPools(
1015 [
1016 account("a", [{ ...weekly, resetsAt: "2026-09-06T12:00:00.000Z" }]),
1017 account("b", [{ ...weekly, resetsAt: "2026-09-05T12:00:00.000Z" }]),
1018 ],
1019 now,
1020 );
1021 expect(keys(pool!)).toEqual([["b", "a"]]);
1022 });
1023});
1024
1025describe("/usage-limits", () => {
1026 const limits = { checkedAt: "2026-09-03T11:00:00.000Z", windows: [window] };
1027 const selected = provider({
1028 usageLimits: limits,
1029 auth: { status: "authenticated", email: "same@example.com" },
1030 });
1031 const sources = [
1032 {
1033 id: UsageLimitSourceId.make("hub"),
1034 kind: "cliproxy" as const,
1035 label: "Accounts",
1036 checkedAt: limits.checkedAt,
1037 accounts: [
1038 {
1039 id: "duplicate",
1040 driver: selected.driver,
1041 email: "SAME@example.com",
1042 usageLimits: limits,
1043 },
1044 { id: "oss", driver: selected.driver, plan: "Codex OSS", usageLimits: limits },
1045 { id: "other-provider", driver: ProviderDriverKind.make("claude"), usageLimits: limits },
1046 ],
1047 },
1048 ];
1049
1050 it("uses hub credit balances and redemption targets in the composer, including native duplicates", () => {
1051 const hubs = sources.map((source) => ({
1052 ...source,
1053 accounts: source.accounts.map((account) => ({
1054 ...account,
1055 usageLimits: {
1056 ...account.usageLimits,
1057 resetCredits: { availableCount: 2, nextCreditId: `${account.id}-credit` },
1058 },
1059 })),
1060 }));
1061 const report = collectProviderUsageLimits(selected.instanceId, [selected], hubs, now);
1062 expect(report?.accounts[0]?.limits.resetCredits?.availableCount).toBe(2);
1063 expect(report?.accounts[0]?.resetCreditInput).toEqual({
1064 sourceId: "hub",
1065 accountId: "duplicate",
1066 creditId: "duplicate-credit",
1067 });
1068 expect(report?.accounts.find((account) => account.id === "hub:oss")?.resetCreditInput).toEqual({
1069 sourceId: "hub",
1070 accountId: "oss",
1071 creditId: "oss-credit",
1072 });
1073 });
1074
1075 it("gives a hub credit to no native row when its email is signed in to two workspaces", () => {
1076 const workspaces = ["ws-a", "ws-b"].map((workspaceId) =>
1077 provider({
1078 instanceId: ProviderInstanceId.make(workspaceId),
1079 usageLimits: limits,
1080 auth: { status: "authenticated", email: "same@example.com", workspaceId },
1081 }),
1082 );
1083 const hub = [
1084 {
1085 ...sources[0]!,
1086 accounts: [
1087 {
1088 id: "duplicate",
1089 driver: selected.driver,
1090 email: "same@example.com",
1091 usageLimits: { ...limits, resetCredits: { availableCount: 2, nextCreditId: "c" } },
1092 },
1093 ],
1094 },
1095 ];
1096 const report = collectProviderUsageLimits(workspaces[0]!.instanceId, workspaces, hub, now);
1097 expect(report?.accounts.map((account) => account.resetCreditInput)).toEqual([
1098 { instanceId: "ws-a" },
1099 { instanceId: "ws-b" },
1100 { sourceId: "hub", accountId: "duplicate", creditId: "c" },
1101 ]);
1102 });
1103
1104 it("redeems a native duplicate through the hub even when the native snapshot is fresher", () => {
1105 const fresher = provider({
1106 usageLimits: {
1107 checkedAt: "2026-09-03T11:30:00.000Z",
1108 windows: [window],
1109 resetCredits: { availableCount: 3, nextCreditId: "native-credit" },
1110 },
1111 auth: { status: "authenticated", email: "same@example.com" },
1112 });
1113 const stale = [
1114 {
1115 id: UsageLimitSourceId.make("hub"),
1116 kind: "cliproxy" as const,
1117 label: "Accounts",
1118 checkedAt: limits.checkedAt,
1119 accounts: [
1120 {
1121 id: "duplicate",
1122 driver: fresher.driver,
1123 email: "SAME@example.com",
1124 usageLimits: {
1125 ...limits,
1126 resetCredits: { availableCount: 2, nextCreditId: "hub-credit" },
1127 },
1128 },
1129 ],
1130 },
1131 ];
1132 const report = collectProviderUsageLimits(fresher.instanceId, [fresher], stale, now);
1133 expect(report?.accounts[0]?.resetCreditInput).toEqual({
1134 sourceId: "hub",
1135 accountId: "duplicate",
1136 creditId: "hub-credit",
1137 });
1138 expect(report?.accounts[0]?.limits.resetCredits?.availableCount).toBe(3);
1139 });
1140
1141 it("keeps unidentified custom instances separate, filtering by driver", () => {
1142 const report = collectProviderUsageLimits(
1143 selected.instanceId,
1144 [
1145 selected,
1146 provider({
1147 instanceId: ProviderInstanceId.make("codex-work"),
1148 displayName: "Work",
1149 usageLimits: { ...limits, resetCredits: { availableCount: 2 } },
1150 }),
1151 provider({
1152 driver: ProviderDriverKind.make("claude"),
1153 instanceId: ProviderInstanceId.make("claude"),
1154 usageLimits: limits,
1155 }),
1156 ],
1157 sources,
1158 now,
1159 );
1160 expect(report?.createdAt).toBe("2026-09-03T12:00:00.000Z");
1161 expect(report?.accounts.map((account) => account.id)).toEqual([
1162 "codex",
1163 "codex-work",
1164 "hub:oss",
1165 ]);
1166 expect(report?.accounts[0]).toMatchObject({
1167 instanceId: selected.instanceId,
1168 email: selected.auth.email,
1169 });
1170 expect(report?.accounts[1]).toMatchObject({
1171 displayName: "Work",
1172 limits: { resetCredits: { availableCount: 2 } },
1173 });
1174 expect(report?.accounts[2]).toMatchObject({
1175 label: "Accounts · oss",
1176 sourceLabel: "CLI Proxy",
1177 plan: "Codex OSS",
1178 });
1179 expect(report?.notices).toEqual([]);
1180 });
1181
1182 it("keeps the freshest usable native duplicate and the freshest native credits in either order", () => {
1183 const failed = provider({
1184 auth: selected.auth,
1185 usageLimits: {
1186 ...limits,
1187 checkedAt: "2026-09-03T11:40:00.000Z",
1188 unavailable: { reason: "probeFailed" },
1189 },
1190 });
1191 const credited = provider({
1192 instanceId: ProviderInstanceId.make("codex-credit"),
1193 auth: selected.auth,
1194 usageLimits: {
1195 checkedAt: "2026-09-03T11:20:00.000Z",
1196 windows: [{ ...window, usedPercent: 50 }],
1197 resetCredits: { availableCount: 2 },
1198 },
1199 });
1200 const staleCredit = provider({
1201 ...credited,
1202 instanceId: ProviderInstanceId.make("codex-stale-credit"),
1203 usageLimits: { ...limits, resetCredits: { availableCount: 3 } },
1204 });
1205 const freshest = provider({
1206 instanceId: ProviderInstanceId.make("codex-fresh"),
1207 auth: selected.auth,
1208 usageLimits: {
1209 checkedAt: "2026-09-03T11:30:00.000Z",
1210 windows: [{ ...window, usedPercent: 55 }],
1211 },
1212 });
1213 const duplicates = [failed, staleCredit, credited, freshest];
1214 for (const providers of [duplicates, duplicates.toReversed()]) {
1215 const report = collectProviderUsageLimits(failed.instanceId, providers, sources, now);
1216 expect(report?.accounts.map((account) => account.id)).toEqual(["codex-fresh", "hub:oss"]);
1217 expect(report?.accounts[0]).toMatchObject({
1218 limits: {
1219 checkedAt: "2026-09-03T11:30:00.000Z",
1220 windows: [{ usedPercent: 55 }],
1221 resetCredits: { availableCount: 2 },
1222 },
1223 resetCreditInput: { instanceId: "codex-credit" },
1224 });
1225 expect(report?.accounts[0]?.limits.unavailable).toBeUndefined();
1226 }
1227 });
1228
1229 it("merges native workspace duplicates only while the workspace evidence is unambiguous", () => {
1230 const known = provider({
1231 ...selected,
1232 instanceId: ProviderInstanceId.make("workspace-a"),
1233 auth: { ...selected.auth, workspaceId: "ws-a" },
1234 });
1235 const fresh = provider({
1236 ...known,
1237 instanceId: ProviderInstanceId.make("workspace-a-fresh"),
1238 usageLimits: { ...limits, checkedAt: "2026-09-03T11:30:00.000Z" },
1239 });
1240 const natives = [known, fresh, selected];
1241 expect(
1242 collectProviderUsageLimits(selected.instanceId, natives, [], now)?.accounts.map(
1243 (account) => account.id,
1244 ),
1245 ).toEqual(["workspace-a-fresh"]);
1246
1247 const unreadable = provider({
1248 instanceId: ProviderInstanceId.make("workspace-b"),
1249 auth: { ...selected.auth, workspaceId: "ws-b" },
1250 });
1251 expect(
1252 collectProviderUsageLimits(
1253 selected.instanceId,
1254 [...natives, unreadable],
1255 [],
1256 now,
1257 )?.accounts.map((account) => account.id),
1258 ).toEqual(["workspace-a-fresh", "codex"]);
1259 expect(
1260 collectProviderUsageLimits(
1261 selected.instanceId,
1262 [...natives, { ...unreadable, usageLimits: limits }],
1263 [],
1264 now,
1265 )?.accounts.map((account) => account.id),
1266 ).toEqual(["workspace-a-fresh", "codex", "workspace-b"]);
1267 });
1268
1269 it("supports a source-only provider and keeps duplicates when the native probe failed", () => {
1270 expect(
1271 collectProviderUsageLimits(selected.instanceId, [provider({})], sources, now)?.accounts.map(
1272 (account) => account.id,
1273 ),
1274 ).toEqual(["hub:duplicate", "hub:oss"]);
1275 const failed = provider({ usageLimits: { ...limits, unavailable: { reason: "probeFailed" } } });
1276 expect(
1277 collectProviderUsageLimits(selected.instanceId, [failed], sources, now)?.accounts.map(
1278 (account) => account.id,
1279 ),
1280 ).toEqual(["codex", "hub:duplicate", "hub:oss"]);
1281 expect(collectProviderUsageLimits(selected.instanceId, [provider({})], [], now)).toBeNull();
1282 expect(
1283 collectProviderUsageLimits(
1284 selected.instanceId,
1285 [provider({ enabled: false, usageLimits: limits })],
1286 [],
1287 now,
1288 ),
1289 ).toBeNull();
1290 });
1291
1292 it("surfaces source errors only for sources that carry the selected driver", () => {
1293 const failing = { ...sources[0]!, error: "token expired" };
1294 expect(
1295 collectProviderUsageLimits(selected.instanceId, [selected], [failing], now)?.notices,
1296 ).toEqual(["Accounts: token expired"]);
1297 const claudeOnly = { ...failing, accounts: failing.accounts.slice(2) };
1298 expect(
1299 collectProviderUsageLimits(selected.instanceId, [selected], [claudeOnly], now)?.notices,
1300 ).toEqual([]);
1301 const unreadable = { ...failing, accounts: [] };
1302 expect(
1303 collectProviderUsageLimits(selected.instanceId, [selected], [unreadable], now)?.notices,
1304 ).toEqual(["Accounts: token expired"]);
1305 const sourceOnly = collectProviderUsageLimits(
1306 selected.instanceId,
1307 [provider({})],
1308 [unreadable],
1309 now,
1310 );
1311 expect(sourceOnly?.accounts).toEqual([]);
1312 expect(sourceOnly?.notices).toEqual(["Accounts: token expired"]);
1313 });
1314
1315 it("advertises global and workspace commands only for providers present in Limits", () => {
1316 const withWorkspace = provider({
1317 workspaceSnapshots: [
1318 { cwd: "/tmp/project", checkedAt: limits.checkedAt, slashCommands: [], skills: [] },
1319 ],
1320 });
1321 const [supported] = withUsageLimitsCommands([withWorkspace], sources);
1322 expect(supported?.slashCommands.map((command) => command.name)).toEqual(["usage-limits"]);
1323 expect(
1324 supported?.workspaceSnapshots?.[0]?.slashCommands.map((command) => command.name),
1325 ).toEqual(["usage-limits"]);
1326 expect(withUsageLimitsCommands([withWorkspace], [])[0]?.slashCommands).toEqual([]);
1327 const ownCommand = provider({
1328 slashCommands: [{ name: "usage-limits", description: "Provider's own" }],
1329 });
1330 expect(withUsageLimitsCommands([ownCommand], [])[0]?.slashCommands).toEqual([
1331 { name: "usage-limits", description: "Provider's own" },
1332 ]);
1333 const unreadable = { ...sources[0]!, accounts: [], error: "token expired" };
1334 expect(
1335 withUsageLimitsCommands([withWorkspace], [unreadable])[0]?.slashCommands.map(
1336 (command) => command.name,
1337 ),
1338 ).toEqual(["usage-limits"]);
1339 expect(
1340 withUsageLimitsCommands([selected], [])[0]?.slashCommands.map((command) => command.name),
1341 ).toEqual(["usage-limits"]);
1342 });
1343});
1344
1345describe("sameUsageLimitCommandCoverage", () => {
1346 const codexAccount = {
1347 id: "a",
1348 driver: ProviderDriverKind.make("codex"),
1349 usageLimits: { checkedAt: "2026-09-03T11:00:00.000Z", windows: [] },
1350 };
1351 const base = {
1352 id: UsageLimitSourceId.make("hub"),
1353 kind: "cliproxy" as const,
1354 label: "Accounts",
1355 checkedAt: "2026-09-03T11:00:00.000Z",
1356 };
1357 it("ignores quota movement but not the drivers offered the command", () => {
1358 const withCodex = [{ ...base, accounts: [codexAccount] }];
1359 const withCodexLater = [
1360 {
1361 ...base,
1362 accounts: [
1363 {
1364 ...codexAccount,
1365 usageLimits: { ...codexAccount.usageLimits, checkedAt: "2026-09-03T12:00:00.000Z" },
1366 },
1367 ],
1368 },
1369 ];
1370 expect(sameUsageLimitCommandCoverage(withCodex, withCodexLater)).toBe(true);
1371 expect(sameUsageLimitCommandCoverage(withCodex, [{ ...base, accounts: [] }])).toBe(false);
1372 });
1373 it("treats a failed read as a change in coverage, in both directions", () => {
1374 const empty = [{ ...base, accounts: [] }];
1375 const failed = [{ ...base, accounts: [], error: "token expired" }];
1376 expect(sameUsageLimitCommandCoverage(empty, failed)).toBe(false);
1377 expect(sameUsageLimitCommandCoverage(failed, empty)).toBe(false);
1378 expect(
1379 sameUsageLimitCommandCoverage(failed, [{ ...base, accounts: [], error: "still down" }]),
1380 ).toBe(true);
1381 });
1382});
1383
1384describe("external usage settings", () => {
1385 it("deduplicates destinations across accounts and environments without inventing quota pools", () => {
1386 const managed = provider({
1387 usageLimits: {
1388 checkedAt: "2026-09-03T11:00:00.000Z",
1389 windows: [],
1390 unavailable: { reason: "unsupported", message: "Track usage in ChatGPT." },
1391 externalUsage: { label: "ChatGPT usage", url: "https://chatgpt.com/#settings/Usage" },
1392 },
1393 });
1394 const presentations = new Map([
1395 [
1396 EnvironmentId.make("a"),
1397 {
1398 entry: { target: { label: "A" } },
1399 serverConfig: {
1400 providers: [managed, { ...managed, instanceId: ProviderInstanceId.make("personal") }],
1401 },
1402 },
1403 ],
1404 [
1405 EnvironmentId.make("b"),
1406 { entry: { target: { label: "B" } }, serverConfig: { providers: [managed] } },
1407 ],
1408 ]);
1409 expect(collectExternalUsageLinks(presentations)).toEqual([
1410 {
1411 ...managed.usageLimits!.externalUsage,
1412 message: "Track usage in ChatGPT.",
1413 accounts: [`${managed.instanceId} on A`, "personal on A", `${managed.instanceId} on B`],
1414 },
1415 ]);
1416 expect(collectLimitAccounts(presentations)).toEqual([]);
1417 expect(collectLimitNotices(presentations)).toEqual([]);
1418 });
1419});
1420
1421describe("ChatGPT sharing presentation", () => {
1422 it("requires verified sharing metadata rather than the Codex driver or login type", () => {
1423 const codex = provider({ auth: { status: "authenticated", type: "chatgpt" } });
1424 expect(usesChatGptSharing(codex)).toBe(false);
1425 expect(
1426 usesChatGptSharing({ ...codex, auth: { ...codex.auth, subscriptionSharing: true } }),
1427 ).toBe(true);
1428 expect(
1429 usesChatGptSharing({
1430 ...codex,
1431 auth: { status: "unauthenticated", subscriptionSharing: true },
1432 }),
1433 ).toBe(false);
1434 });
1435});