Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usageLimits.test.ts

1,168 lines39.1 KB

1import {
2 EnvironmentId,
3 ProviderDriverKind,
4 ProviderInstanceId,
5 type ServerProvider,
6 EventId,
7 type OrchestrationThreadActivity,
8 UsageLimitSourceId,
9} from "@t3tools/contracts";
10import { describe, expect, it } from "vite-plus/test";
11​
12import {
13 type LimitAccount,
14 isUsageLimitsCommand,
15 collectProviderUsageLimits,
16 sameUsageLimitCommandCoverage,
17 withUsageLimitsCommands,
18 collectLimitAccounts,
19 collectExternalUsageLinks,
20 collectLimitNotices,
21 collectLimitPools,
22 displayLimitWindows,
23 elapsedShare,
24 formatResetsIn,
25 limitsNotice,
26 paceOf,
27 providersWithLimits,
28 remainingPercent,
29 isChatGptUsageLimitError,
30 usesChatGptSharing,
31} from "./usageLimits.ts";
32​
33const now = Date.parse("2026-09-03T12:00:00.000Z");
34​
35const window = {
36 id: "five_hour",
37 kind: "session",
38 label: "Session",
39 usedPercent: 40,
40 windowDurationMins: 300,
41 resetsAt: "2026-09-03T14:00:00.000Z",
42} as const;
43​
44function provider(overrides: Partial<ServerProvider>): ServerProvider {
45 return {
46 instanceId: ProviderInstanceId.make("codex"),
47 driver: ProviderDriverKind.make("codex"),
48 enabled: true,
49 installed: true,
50 version: null,
51 status: "ready",
52 auth: { status: "authenticated" },
53 checkedAt: "2026-09-03T11:00:00.000Z",
54 models: [],
55 slashCommands: [],
56 skills: [],
57 ...overrides,
58 };
60​
61describe("pace", () => {
62 it("places the clock three fifths through a five-hour window with two hours left", () => {
63 expect(elapsedShare(window, now)).toBeCloseTo(0.6);
64 expect(paceOf(window, now)).toBe("under");
65 expect(paceOf({ ...window, usedPercent: 62 }, now)).toBe("on");
66 expect(paceOf({ ...window, usedPercent: 80 }, now)).toBe("ahead");
67 });
68​
69 it("has no pace without a reset or a duration", () => {
70 expect(paceOf({ ...window, resetsAt: undefined }, now)).toBeNull();
71 expect(paceOf({ ...window, windowDurationMins: undefined }, now)).toBeNull();
72 expect(formatResetsIn({ ...window, resetsAt: undefined }, now)).toBeNull();
73 });
74​
75 it("phrases the reset as a countdown", () => {
76 expect(formatResetsIn(window, now)).toBe("resets in 2h 0m");
77 expect(formatResetsIn({ ...window, resetsAt: "2026-09-06T15:30:00.000Z" }, now)).toBe(
78 "resets in 3d 3h",
79 );
80 expect(formatResetsIn({ ...window, resetsAt: "2026-09-03T11:00:00.000Z" }, now)).toBe(
81 "resets now",
82 );
83 });
84});
85​
86describe("limitsNotice", () => {
87 it("explains empty bars and passes provider messages through", () => {
88 const checkedAt = "2026-09-03T11:00:00.000Z";
89 expect(limitsNotice({ checkedAt, windows: [window] })).toBeNull();
90 expect(limitsNotice({ checkedAt, windows: [] })).toBe("No limits reported.");
91 expect(limitsNotice({ checkedAt, windows: [], unavailable: { reason: "unsupported" } })).toBe(
92 "This account has no subscription limits.",
93 );
94 expect(
95 limitsNotice({
96 checkedAt,
97 windows: [],
98 unavailable: { reason: "probeFailed", message: "Codex timed out." },
99 }),
100 ).toBe("Codex timed out.");
101 });
102});
103​
104describe("providersWithLimits", () => {
105 it("keeps only usable providers whose driver reports limits at all", () => {
106 const limits = { checkedAt: "2026-09-03T11:00:00.000Z", windows: [window] };
107 const codex = provider({ usageLimits: limits });
108 expect(
109 providersWithLimits([
110 codex,
111 provider({
112 instanceId: ProviderInstanceId.make("cursor"),
113 driver: ProviderDriverKind.make("cursor"),
114 }),
115 provider({
116 instanceId: ProviderInstanceId.make("off"),
117 enabled: false,
118 usageLimits: limits,
119 }),
120 provider({
121 instanceId: ProviderInstanceId.make("gone"),
122 installed: false,
123 usageLimits: limits,
124 }),
125 provider({
126 instanceId: ProviderInstanceId.make("shadow"),
127 availability: "unavailable",
128 usageLimits: limits,
129 }),
130 ]),
131 ).toEqual([codex]);
132 });
133});
134​
135describe("pools", () => {
136 const checkedAt = "2026-09-03T11:00:00.000Z";
137 const weekly = {
138 id: "seven_day",
139 kind: "weekly",
140 label: "Weekly",
141 windowDurationMins: 7 * 24 * 60,
142 resetsAt: "2026-09-06T12:00:00.000Z",
143 } as const;
144 const claude = ProviderDriverKind.make("claudeAgent");
145 const source = {
146 id: UsageLimitSourceId.make("hub"),
147 kind: "cliproxy" as const,
148 label: "hub",
149 checkedAt,
150 };
151 const laptop = { entry: { target: { label: "Laptop" } } };
152​
153 it("merges one account reported natively on two environments and by a hub into one entry", () => {
154 const native = provider({
155 driver: claude,
156 instanceId: ProviderInstanceId.make("claude"),
157 auth: { status: "authenticated", email: "Same@example.com" },
158 usageLimits: { checkedAt, windows: [{ ...window, usedPercent: 40 }] },
159 });
160 const input = new Map([
161 [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { providers: [native] } }],
162 [
163 EnvironmentId.make("env-b"),
164 {
165 entry: { target: { label: "Desktop" } },
166 serverConfig: {
167 providers: [
168 {
169 ...native,
170 usageLimits: {
171 checkedAt: "2026-09-03T11:30:00.000Z",
172 windows: [{ ...window, usedPercent: 55 }],
173 },
174 },
175 ],
176 usageLimitSources: [
177 {
178 ...source,
179 accounts: [
180 {
181 id: "claude-same@example.com.json",
182 driver: claude,
183 email: "same@example.com",
184 plan: "Claude Subscription",
185 usageLimits: { checkedAt, windows: [{ ...window, usedPercent: 10 }] },
186 },
187 ],
188 },
189 ],
190 },
191 },
192 ],
193 ]);
194 const accounts = collectLimitAccounts(input);
195 expect(accounts).toHaveLength(1);
196 expect(accounts[0]).toMatchObject({
197 key: "env-a:claude",
198 sourceLabel: null,
199 // Desktop's read is fresher, so its credits and its redeem are the ones on show.
200 redeem: { environmentId: "env-b", input: { instanceId: "claude" } },
201 environments: [
202 { environmentId: "env-a", label: "Laptop" },
203 { environmentId: "env-b", label: "Desktop" },
204 ],
205 });
206 // The fresher native snapshot wins; the hub row is pre-filtered by email.
207 expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(55);
208 });
209​
210 it("takes windows from a fresher hub read but credits and redeem from the native instance", () => {
211 const native = provider({
212 driver: claude,
213 instanceId: ProviderInstanceId.make("claude"),
214 auth: { status: "authenticated", email: "same@example.com" },
215 usageLimits: {
216 checkedAt,
217 windows: [{ ...window, usedPercent: 40 }],
218 resetCredits: { availableCount: 2 },
219 },
220 });
221 const input = new Map([
222 [
223 EnvironmentId.make("env-a"),
224 {
225 ...laptop,
226 serverConfig: {
227 providers: [native],
228 usageLimitSources: [
229 {
230 ...source,
231 accounts: [
232 {
233 id: "claude-same@example.com.json",
234 driver: claude,
235 email: "same@example.com",
236 usageLimits: {
237 checkedAt: "2026-09-03T11:30:00.000Z",
238 windows: [{ ...window, usedPercent: 55 }],
239 },
240 },
241 ],
242 },
243 ],
244 },
245 },
246 ],
247 ]);
248 const [account] = collectLimitAccounts(input);
249 expect(account?.limits.windows[0]?.usedPercent).toBe(55);
250 expect(account?.limits.resetCredits?.availableCount).toBe(2);
251 expect(account?.redeem).toEqual({ environmentId: "env-a", input: { instanceId: "claude" } });
252 expect(account?.environments).toEqual([{ environmentId: "env-a", label: "Laptop" }]);
253 });
254​
255 it("redeems through the hub when it holds a credit, even with a fresher native read", () => {
256 const native = provider({
257 driver: claude,
258 instanceId: ProviderInstanceId.make("claude"),
259 auth: { status: "authenticated", email: "same@example.com" },
260 usageLimits: {
261 checkedAt: "2026-09-03T11:30:00.000Z",
262 windows: [{ ...window, usedPercent: 40 }],
263 resetCredits: { availableCount: 3, nextCreditId: "native-credit" },
264 },
265 });
266 const input = new Map([
267 [
268 EnvironmentId.make("env-a"),
269 {
270 ...laptop,
271 serverConfig: {
272 providers: [native],
273 usageLimitSources: [
274 {
275 ...source,
276 accounts: [
277 {
278 id: "claude-same@example.com.json",
279 driver: claude,
280 email: "same@example.com",
281 usageLimits: {
282 checkedAt,
283 windows: [{ ...window, usedPercent: 55 }],
284 resetCredits: { availableCount: 2, nextCreditId: "hub-credit" },
285 },
286 },
287 ],
288 },
289 ],
290 },
291 },
292 ],
293 ]);
294 const [account] = collectLimitAccounts(input);
295 // Only the hub path clears the routing cooldown it holds for this account.
296 expect(account?.redeem).toEqual({
297 environmentId: "env-a",
298 input: { sourceId: "hub", accountId: "claude-same@example.com.json", creditId: "hub-credit" },
299 });
300 // The fresher native balance is still the one shown.
301 expect(account?.limits.resetCredits?.availableCount).toBe(3);
302 });
303​
304 it("redeems on the environment whose snapshot supplied the credits on show", () => {
305 const stale = provider({
306 auth: { status: "authenticated", email: "same@example.com" },
307 usageLimits: {
308 checkedAt,
309 windows: [window],
310 resetCredits: { availableCount: 0 },
311 },
312 });
313 const fresh = {
314 ...stale,
315 usageLimits: {
316 checkedAt: "2026-09-03T11:30:00.000Z",
317 windows: [window],
318 resetCredits: { availableCount: 2 },
319 },
320 };
321 const input = new Map([
322 [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { providers: [stale] } }],
323 [
324 EnvironmentId.make("env-b"),
325 { entry: { target: { label: "Desktop" } }, serverConfig: { providers: [fresh] } },
326 ],
327 ]);
328 const [account] = collectLimitAccounts(input);
329 expect(account?.limits.resetCredits?.availableCount).toBe(2);
330 expect(account?.redeem).toEqual({ environmentId: "env-b", input: { instanceId: "codex" } });
331 });
332​
333 it("uses the freshest hub credit and its environment even when the account is also native", () => {
334 const native = provider({
335 auth: { status: "authenticated", email: "same@example.com" },
336 usageLimits: { checkedAt, windows: [window], resetCredits: { availableCount: 1 } },
337 });
338 const hubAccount = {
339 id: "codex-same.json",
340 driver: native.driver,
341 email: "same@example.com",
342 usageLimits: {
343 checkedAt: "2026-09-03T11:30:00.000Z",
344 windows: [window],
345 resetCredits: { availableCount: 2, nextCreditId: "credit-2" },
346 },
347 };
348 const input = new Map([
349 [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { providers: [native] } }],
350 [
351 EnvironmentId.make("env-b"),
352 {
353 ...laptop,
354 serverConfig: {
355 providers: [],
356 usageLimitSources: [{ ...source, accounts: [hubAccount] }],
357 },
358 },
359 ],
360 ]);
361 const [account] = collectLimitAccounts(input);
362 expect(account?.limits.resetCredits?.availableCount).toBe(2);
363 expect(account?.redeem).toEqual({
364 environmentId: "env-b",
365 input: { sourceId: "hub", accountId: "codex-same.json", creditId: "credit-2" },
366 });
367 hubAccount.usageLimits.resetCredits.availableCount = 0;
368 expect(collectLimitAccounts(input)[0]?.limits.resetCredits?.availableCount).toBe(0);
369 });
370​
371 it("keeps distinct hub accounts redeemable through their own source", () => {
372 const hubAccounts = ["first", "second"].map((id) => ({
373 id,
374 driver: ProviderDriverKind.make("codex"),
375 email: `${id}@example.com`,
376 usageLimits: {
377 checkedAt,
378 windows: [window],
379 resetCredits: { availableCount: 2, nextCreditId: `${id}-credit` },
380 },
381 }));
382 const input = new Map([
383 [
384 EnvironmentId.make("env-a"),
385 {
386 ...laptop,
387 serverConfig: {
388 providers: [],
389 usageLimitSources: [{ ...source, accounts: hubAccounts }],
390 },
391 },
392 ],
393 ]);
394 expect(collectLimitAccounts(input).map((account) => account.redeem)).toEqual(
395 hubAccounts.map((account) => ({
396 environmentId: "env-a",
397 input: { sourceId: "hub", accountId: account.id, creditId: `${account.id}-credit` },
398 })),
399 );
400 });
401​
402 it("does not give old credits the timestamp of a newer window-only read", () => {
403 const snapshots = [
404 { checkedAt, windows: [window], resetCredits: { availableCount: 2 } },
405 { checkedAt: "2026-09-03T12:00:00.000Z", windows: [window] },
406 {
407 checkedAt: "2026-09-03T11:30:00.000Z",
408 windows: [window],
409 resetCredits: { availableCount: 1 },
410 },
411 ];
412 const input = new Map(
413 snapshots.map((usageLimits, i) => [
414 EnvironmentId.make(`env-${i}`),
415 {
416 ...laptop,
417 serverConfig: {
418 providers: [
419 provider({
420 auth: { status: "authenticated", email: "same@example.com" },
421 usageLimits,
422 }),
423 ],
424 },
425 },
426 ]),
427 );
428 const [account] = collectLimitAccounts(input);
429 expect(account?.limits.checkedAt).toBe("2026-09-03T12:00:00.000Z");
430 expect(account?.limits.resetCredits?.availableCount).toBe(1);
431 expect(account?.redeem?.environmentId).toBe("env-2");
432 });
433​
434 it("names an environment once however many of its instances share the account", () => {
435 const shared = provider({
436 auth: { status: "authenticated", email: "same@example.com" },
437 usageLimits: { checkedAt, windows: [window] },
438 });
439 const input = new Map([
440 [
441 EnvironmentId.make("env-a"),
442 {
443 ...laptop,
444 serverConfig: {
445 providers: [shared, { ...shared, instanceId: ProviderInstanceId.make("work") }],
446 },
447 },
448 ],
449 ]);
450 expect(collectLimitAccounts(input)[0]?.environments).toEqual([
451 { environmentId: "env-a", label: "Laptop" },
452 ]);
453 });
454​
455 it("keys a hub account without an email by hub, so two environments on one hub share it", () => {
456 const seat = {
457 id: "claude-team-seat.json",
458 driver: claude,
459 usageLimits: { checkedAt, windows: [window] },
460 };
461 const hub = { ...source, accounts: [seat] };
462 const input = new Map([
463 [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { usageLimitSources: [hub] } }],
464 [
465 EnvironmentId.make("env-b"),
466 { entry: { target: { label: "Desktop" } }, serverConfig: { usageLimitSources: [hub] } },
467 ],
468 ]);
469 const accounts = collectLimitAccounts(input);
470 expect(accounts.map((account) => account.key)).toEqual(["hub:claude-team-seat.json"]);
471 expect(accounts[0]?.displayName).toBe("claude-team-seat");
472 });
473​
474 it("pools windows by id across accounts and orders resets by when they land", () => {
475 const input = new Map([
476 [
477 EnvironmentId.make("env-a"),
478 {
479 ...laptop,
480 serverConfig: {
481 providers: [],
482 usageLimitSources: [
483 {
484 ...source,
485 accounts: [
486 {
487 id: "a",
488 driver: claude,
489 usageLimits: {
490 checkedAt,
491 windows: [
492 { ...window, usedPercent: 80, resetsAt: "2026-09-03T13:00:00.000Z" },
493 { ...weekly, usedPercent: 20 },
494 ],
495 },
496 },
497 {
498 id: "b",
499 driver: claude,
500 usageLimits: {
501 checkedAt,
502 windows: [{ ...window, usedPercent: 40 }],
503 },
504 },
505 {
506 id: "c",
507 driver: ProviderDriverKind.make("codex"),
508 usageLimits: { checkedAt, windows: [{ ...weekly, usedPercent: 50 }] },
509 },
510 {
511 id: "unsupported",
512 driver: claude,
513 usageLimits: {
514 checkedAt,
515 windows: [],
516 unavailable: { reason: "unsupported" as const },
517 },
518 },
519 ],
520 },
521 ],
522 },
523 },
524 ],
525 ]);
526 const pools = collectLimitPools(collectLimitAccounts(input), now);
527 expect(pools.map((pool) => [pool.driver, pool.accounts.length])).toEqual([
528 ["claudeAgent", 2],
529 ["codex", 1],
530 ]);
531 const [session, week] = pools[0]!.windows;
532 // A member with no reset has no clock, so it does not vote on pace.
533 const untimed = collectLimitPools(
534 collectLimitAccounts(input).map((account) =>
535 account.key === "hub:b"
536 ? {
537 ...account,
538 limits: {
539 ...account.limits,
540 windows: account.limits.windows.map((w) => ({ ...w, resetsAt: undefined })),
541 },
542 }
543 : account,
544 ),
545 now,
546 );
547 // Only a votes: 80% used, 80% elapsed.
548 expect(untimed[0]?.windows[0]?.pace).toBe("on");
549 // a is 80% through its window and b 60%: the pool is 70% elapsed, 60% used.
550 expect(session).toMatchObject({
551 id: "five_hour",
552 remainingPercent: 40,
553 usedPercent: 60,
554 pace: "under",
555 });
556 expect(
557 session?.resets.map((reset) => [reset.member.account.key, reset.restoresPercent]),
558 ).toEqual([
559 ["hub:a", 40],
560 ["hub:b", 20],
561 ]);
562 expect(week).toMatchObject({ id: "seven_day", remainingPercent: 80, members: [{}] });
563 // Codex reports `primary` for both its five-hour and (on Go) monthly window.
564 const mixed = collectLimitPools(
565 [
566 ...collectLimitAccounts(input),
567 {
568 key: "go",
569 driver: claude,
570 displayName: "Go",
571 email: undefined,
572 plan: undefined,
573 accentColor: undefined,
574 environments: [],
575 sourceLabel: null,
576 redeem: null,
577 limits: {
578 checkedAt,
579 windows: [
580 {
581 id: "five_hour",
582 kind: "monthly",
583 label: "Monthly",
584 usedPercent: 82,
585 windowDurationMins: 30 * 24 * 60,
586 resetsAt: "2026-09-14T12:00:00.000Z",
587 },
588 ],
589 },
590 },
591 ],
592 now,
593 );
594 expect(mixed[0]?.windows.map((window) => [window.kind, window.members.length])).toEqual([
595 ["session", 2],
596 ["weekly", 1],
597 ["monthly", 1],
598 ]);
599 // Session resets determine the account order for every row.
600 expect(session?.members.map((member) => member.account.key)).toEqual(["hub:a", "hub:b"]);
601 expect(pools[0]?.accounts.map((account) => account.key)).toEqual(["hub:a", "hub:b"]);
602 });
603});
604​
605describe("pooled account columns", () => {
606 const weekly = {
607 ...window,
608 id: "seven_day",
609 kind: "weekly",
610 label: "Weekly",
611 windowDurationMins: 7 * 24 * 60,
612 } as const;
613 const account = (key: string, windows: LimitAccount["limits"]["windows"]): LimitAccount => ({
614 key,
615 driver: ProviderDriverKind.make("claudeAgent"),
616 displayName: key,
617 email: undefined,
618 plan: undefined,
619 accentColor: undefined,
620 environments: [],
621 sourceLabel: "Hub",
622 redeem: null,
623 limits: { checkedAt: "2026-09-03T11:00:00.000Z", windows },
624 });
625 const keys = (pool: ReturnType<typeof collectLimitPools>[number]) =>
626 pool.windows.map((row) =>
627 row.columns.map((member) => (member.window ? member.account.key : null)),
628 );
629​
630 it("keeps session columns across rows with opposite reset and usage orders", () => {
631 const accounts = [
632 account("a", [
633 { ...weekly, usedPercent: 80, resetsAt: "2026-09-05T12:00:00.000Z" },
634 { ...window, usedPercent: 10, resetsAt: "2026-09-03T15:00:00.000Z" },
635 ]),
636 account("b", [
637 { ...weekly, usedPercent: 20, resetsAt: "2026-09-06T12:00:00.000Z" },
638 { ...window, usedPercent: 90, resetsAt: "2026-09-03T13:00:00.000Z" },
639 ]),
640 ];
641 const [pool] = collectLimitPools(accounts, now);
642 expect(pool!.accounts.map((account) => account.key)).toEqual(["b", "a"]);
643 expect(keys(pool!)).toEqual([
644 ["b", "a"],
645 ["b", "a"],
646 ]);
647 expect(pool!.windows[1]!.resets.map((reset) => reset.member.account.key)).toEqual(["a", "b"]);
648 expect(pool!.windows[1]!.remainingPercent).toBe(50);
649 expect(keys(collectLimitPools(accounts.toReversed(), now)[0]!)).toEqual(keys(pool!));
650 });
651​
652 it("preserves gaps without counting missing windows toward pooled quota", () => {
653 const [pool] = collectLimitPools(
654 [
655 account("a", [window]),
656 account("b", [
657 { ...window, resetsAt: "2026-09-03T15:00:00.000Z" },
658 { ...weekly, usedPercent: 80 },
659 ]),
660 account("c", [weekly]),
661 ],
662 now,
663 );
664 expect(keys(pool!)).toEqual([
665 ["a", "b", null],
666 [null, "b", "c"],
667 ]);
668 expect(pool!.windows[1]!.members.map((member) => member.account.key)).toEqual(["b", "c"]);
669 expect(pool!.windows[1]!.remainingPercent).toBe(40);
670 expect(pool!.windows[1]!.resets.map((reset) => reset.restoresPercent)).toEqual([40, 20]);
671 });
672​
673 it("falls back to weekly resets when no account reports a session", () => {
674 const [pool] = collectLimitPools(
675 [
676 account("a", [{ ...weekly, resetsAt: "2026-09-06T12:00:00.000Z" }]),
677 account("b", [{ ...weekly, resetsAt: "2026-09-05T12:00:00.000Z" }]),
678 ],
679 now,
680 );
681 expect(keys(pool!)).toEqual([["b", "a"]]);
682 });
683​
684 it("sorts unknown resets last and breaks ties consistently", () => {
685 const accounts = [
686 account("z", [{ ...window, resetsAt: undefined }]),
687 account("b", [window]),
688 account("a", [window]),
689 account("y", [{ ...window, resetsAt: "invalid" }]),
690 ];
691 expect(keys(collectLimitPools(accounts, now)[0]!)).toEqual([["a", "b", "y", "z"]]);
692 expect(keys(collectLimitPools(accounts.toReversed(), now)[0]!)).toEqual([["a", "b", "y", "z"]]);
693 });
694});
695​
696describe("Cursor limit presentation", () => {
697 const cursorAccount: LimitAccount = {
698 key: "cursor",
699 driver: ProviderDriverKind.make("cursor"),
700 displayName: "Cursor",
701 email: undefined,
702 plan: undefined,
703 accentColor: undefined,
704 environments: [],
705 sourceLabel: "Cursor",
706 redeem: null,
707 limits: {
708 checkedAt: "2026-09-03T11:00:00.000Z",
709 windows: [
710 { id: "apiPercentUsed", kind: "monthly", label: "Other Models", usedPercent: 49 },
711 { id: "autoPercentUsed", kind: "monthly", label: "Cursor Models", usedPercent: 9 },
712 { id: "totalPercentUsed", kind: "monthly", label: "Overall", usedPercent: 15 },
713 ],
714 },
715 };
716​
717 it("hides the combined percentage and orders the two pools", () => {
718 const [pool] = collectLimitPools([cursorAccount], now);
719 const display = displayLimitWindows(pool!);
720 expect(display.map((window) => window.id)).toEqual(["autoPercentUsed", "apiPercentUsed"]);
721 });
722​
723 it("keeps the combined percentage as a card if either allowance is missing", () => {
724 const [pool] = collectLimitPools(
725 [
726 {
727 ...cursorAccount,
728 limits: {
729 ...cursorAccount.limits,
730 windows: cursorAccount.limits.windows.filter(
731 (window) => window.id !== "apiPercentUsed",
732 ),
733 },
734 },
735 ],
736 now,
737 );
738 const display = displayLimitWindows(pool!);
739 expect(display.map((window) => window.id)).toEqual(["totalPercentUsed", "autoPercentUsed"]);
740 });
741});
742​
743describe("collectLimitNotices", () => {
744 const checkedAt = "2026-09-03T11:00:00.000Z";
745 const claude = ProviderDriverKind.make("claudeAgent");
746 const laptop = { entry: { target: { label: "Laptop" } } };
747 const hub = {
748 id: UsageLimitSourceId.make("hub"),
749 kind: "cliproxy" as const,
750 label: "hub",
751 checkedAt,
752 accounts: [],
753 };
754​
755 it("names failures and silence, skips unsupported accounts, and labels environments only when several", () => {
756 const failed = provider({
757 instanceId: ProviderInstanceId.make("claude"),
758 driver: claude,
759 displayName: "Claude Max",
760 usageLimits: { checkedAt, windows: [], unavailable: { reason: "probeFailed" } },
761 });
762 const apiKey = provider({
763 instanceId: ProviderInstanceId.make("api"),
764 driver: claude,
765 usageLimits: { checkedAt, windows: [], unavailable: { reason: "unsupported" } },
766 });
767 const silent = provider({ usageLimits: { checkedAt, windows: [] } });
768 const one = new Map([
769 [
770 EnvironmentId.make("env-a"),
771 {
772 ...laptop,
773 serverConfig: {
774 providers: [failed, apiKey, silent],
775 usageLimitSources: [
776 hub,
777 { ...hub, id: UsageLimitSourceId.make("down"), label: "down", error: "ECONNREFUSED" },
778 ],
779 },
780 },
781 ],
782 ]);
783 expect(collectLimitNotices(one)).toEqual([
784 "Claude Max: Could not read limits.",
785 "codex: No limits reported.",
786 "hub: No accounts reported.",
787 "down: ECONNREFUSED",
788 ]);
789​
790 one.set(EnvironmentId.make("env-b"), {
791 entry: { target: { label: "Desktop" } },
792 serverConfig: { providers: [], usageLimitSources: [] },
793 });
794 expect(collectLimitNotices(one)[0]).toBe("Laptop · Claude Max: Could not read limits.");
795 });
796});
797​
798describe("/usage-limits", () => {
799 const limits = { checkedAt: "2026-09-03T11:00:00.000Z", windows: [window] };
800 const selected = provider({
801 usageLimits: limits,
802 auth: { status: "authenticated", email: "same@example.com" },
803 });
804 const sources = [
805 {
806 id: UsageLimitSourceId.make("hub"),
807 kind: "cliproxy" as const,
808 label: "Accounts",
809 checkedAt: limits.checkedAt,
810 accounts: [
811 {
812 id: "duplicate",
813 driver: selected.driver,
814 email: "SAME@example.com",
815 usageLimits: limits,
816 },
817 { id: "oss", driver: selected.driver, plan: "Codex OSS", usageLimits: limits },
818 { id: "other-provider", driver: ProviderDriverKind.make("claude"), usageLimits: limits },
819 ],
820 },
821 ];
822​
823 it("uses hub credit balances and redemption targets in the composer, including native duplicates", () => {
824 const hubs = sources.map((source) => ({
825 ...source,
826 accounts: source.accounts.map((account) => ({
827 ...account,
828 usageLimits: {
829 ...account.usageLimits,
830 resetCredits: { availableCount: 2, nextCreditId: `${account.id}-credit` },
831 },
832 })),
833 }));
834 const report = collectProviderUsageLimits(selected.instanceId, [selected], hubs, now);
835 expect(report?.accounts[0]?.limits.resetCredits?.availableCount).toBe(2);
836 expect(report?.accounts[0]?.resetCreditInput).toEqual({
837 sourceId: "hub",
838 accountId: "duplicate",
839 creditId: "duplicate-credit",
840 });
841 expect(report?.accounts.find((account) => account.id === "hub:oss")?.resetCreditInput).toEqual({
842 sourceId: "hub",
843 accountId: "oss",
844 creditId: "oss-credit",
845 });
846 });
847​
848 it("redeems a native duplicate through the hub even when the native snapshot is fresher", () => {
849 const fresher = provider({
850 usageLimits: {
851 checkedAt: "2026-09-03T11:30:00.000Z",
852 windows: [window],
853 resetCredits: { availableCount: 3, nextCreditId: "native-credit" },
854 },
855 auth: { status: "authenticated", email: "same@example.com" },
856 });
857 const stale = [
858 {
859 id: UsageLimitSourceId.make("hub"),
860 kind: "cliproxy" as const,
861 label: "Accounts",
862 checkedAt: limits.checkedAt,
863 accounts: [
864 {
865 id: "duplicate",
866 driver: fresher.driver,
867 email: "SAME@example.com",
868 usageLimits: {
869 ...limits,
870 resetCredits: { availableCount: 2, nextCreditId: "hub-credit" },
871 },
872 },
873 ],
874 },
875 ];
876 const report = collectProviderUsageLimits(fresher.instanceId, [fresher], stale, now);
877 // Only redeeming through the hub clears the routing cooldown it holds for
878 // this account, so the hub wins the path even with a staler balance.
879 expect(report?.accounts[0]?.resetCreditInput).toEqual({
880 sourceId: "hub",
881 accountId: "duplicate",
882 creditId: "hub-credit",
883 });
884 // The fresher native balance is still the one shown.
885 expect(report?.accounts[0]?.limits.resetCredits?.availableCount).toBe(3);
886 });
887​
888 it("keeps accounts and custom instances separate, filtering by driver", () => {
889 const report = collectProviderUsageLimits(
890 selected.instanceId,
891 [
892 selected,
893 provider({
894 instanceId: ProviderInstanceId.make("codex-work"),
895 displayName: "Work",
896 usageLimits: { ...limits, resetCredits: { availableCount: 2 } },
897 }),
898 provider({
899 driver: ProviderDriverKind.make("claude"),
900 instanceId: ProviderInstanceId.make("claude"),
901 usageLimits: limits,
902 }),
903 ],
904 sources,
905 now,
906 );
907 expect(report?.createdAt).toBe("2026-09-03T12:00:00.000Z");
908 expect(report?.accounts.map((account) => account.id)).toEqual([
909 "codex",
910 "codex-work",
911 "hub:oss",
912 ]);
913 expect(report?.accounts[0]).toMatchObject({
914 instanceId: selected.instanceId,
915 email: selected.auth.email,
916 });
917 expect(report?.accounts[1]).toMatchObject({
918 displayName: "Work",
919 limits: { resetCredits: { availableCount: 2 } },
920 });
921 expect(report?.accounts[2]).toMatchObject({
922 label: "Accounts · oss",
923 sourceLabel: "CLI Proxy",
924 plan: "Codex OSS",
925 });
926 expect(report?.notices).toEqual([]);
927 });
928​
929 it("supports a source-only provider and keeps duplicates when the native probe failed", () => {
930 expect(
931 collectProviderUsageLimits(selected.instanceId, [provider({})], sources, now)?.accounts.map(
932 (account) => account.id,
933 ),
934 ).toEqual(["hub:duplicate", "hub:oss"]);
935 const failed = provider({ usageLimits: { ...limits, unavailable: { reason: "probeFailed" } } });
936 expect(
937 collectProviderUsageLimits(selected.instanceId, [failed], sources, now)?.accounts.map(
938 (account) => account.id,
939 ),
940 ).toEqual(["codex", "hub:duplicate", "hub:oss"]);
941 expect(collectProviderUsageLimits(selected.instanceId, [provider({})], [], now)).toBeNull();
942 expect(
943 collectProviderUsageLimits(
944 selected.instanceId,
945 [provider({ enabled: false, usageLimits: limits })],
946 [],
947 now,
948 ),
949 ).toBeNull();
950 });
951​
952 it("surfaces source errors only for sources that carry the selected driver", () => {
953 const failing = { ...sources[0]!, error: "token expired" };
954 expect(
955 collectProviderUsageLimits(selected.instanceId, [selected], [failing], now)?.notices,
956 ).toEqual(["Accounts: token expired"]);
957 const claudeOnly = { ...failing, accounts: failing.accounts.slice(2) };
958 expect(
959 collectProviderUsageLimits(selected.instanceId, [selected], [claudeOnly], now)?.notices,
960 ).toEqual([]);
961 // A read failure clears the accounts, so the error must not depend on a match.
962 const unreadable = { ...failing, accounts: [] };
963 expect(
964 collectProviderUsageLimits(selected.instanceId, [selected], [unreadable], now)?.notices,
965 ).toEqual(["Accounts: token expired"]);
966 // A source-only provider still gets the report, carrying only the error.
967 const sourceOnly = collectProviderUsageLimits(
968 selected.instanceId,
969 [provider({})],
970 [unreadable],
971 now,
972 );
973 expect(sourceOnly?.accounts).toEqual([]);
974 expect(sourceOnly?.notices).toEqual(["Accounts: token expired"]);
975 });
976​
977 it("advertises global and workspace commands only for providers present in Limits", () => {
978 const withWorkspace = provider({
979 workspaceSnapshots: [
980 { cwd: "/tmp/project", checkedAt: limits.checkedAt, slashCommands: [], skills: [] },
981 ],
982 });
983 const [supported] = withUsageLimitsCommands([withWorkspace], sources);
984 expect(supported?.slashCommands.map((command) => command.name)).toEqual(["usage-limits"]);
985 expect(
986 supported?.workspaceSnapshots?.[0]?.slashCommands.map((command) => command.name),
987 ).toEqual(["usage-limits"]);
988 expect(withUsageLimitsCommands([withWorkspace], [])[0]?.slashCommands).toEqual([]);
989 // A provider's own command of the same name is left alone without coverage.
990 const ownCommand = provider({
991 slashCommands: [{ name: "usage-limits", description: "Provider's own" }],
992 });
993 expect(withUsageLimitsCommands([ownCommand], [])[0]?.slashCommands).toEqual([
994 { name: "usage-limits", description: "Provider's own" },
995 ]);
996 const unreadable = { ...sources[0]!, accounts: [], error: "token expired" };
997 expect(
998 withUsageLimitsCommands([withWorkspace], [unreadable])[0]?.slashCommands.map(
999 (command) => command.name,
1000 ),
1001 ).toEqual(["usage-limits"]);
1002 expect(
1003 withUsageLimitsCommands([selected], [])[0]?.slashCommands.map((command) => command.name),
1004 ).toEqual(["usage-limits"]);
1005 });
1006});
1007​
1008describe("sameUsageLimitCommandCoverage", () => {
1009 const codexAccount = {
1010 id: "a",
1011 driver: ProviderDriverKind.make("codex"),
1012 usageLimits: { checkedAt: "2026-09-03T11:00:00.000Z", windows: [] },
1013 };
1014 const base = {
1015 id: UsageLimitSourceId.make("hub"),
1016 kind: "cliproxy" as const,
1017 label: "Accounts",
1018 checkedAt: "2026-09-03T11:00:00.000Z",
1019 };
1020 it("ignores quota movement but not the drivers offered the command", () => {
1021 const withCodex = [{ ...base, accounts: [codexAccount] }];
1022 const withCodexLater = [
1024 ...base,
1025 accounts: [
1027 ...codexAccount,
1028 usageLimits: { ...codexAccount.usageLimits, checkedAt: "2026-09-03T12:00:00.000Z" },
1029 },
1030 ],
1031 },
1032 ];
1033 expect(sameUsageLimitCommandCoverage(withCodex, withCodexLater)).toBe(true);
1034 expect(sameUsageLimitCommandCoverage(withCodex, [{ ...base, accounts: [] }])).toBe(false);
1035 });
1036 it("treats a failed read as a change in coverage, in both directions", () => {
1037 const empty = [{ ...base, accounts: [] }];
1038 const failed = [{ ...base, accounts: [], error: "token expired" }];
1039 expect(sameUsageLimitCommandCoverage(empty, failed)).toBe(false);
1040 expect(sameUsageLimitCommandCoverage(failed, empty)).toBe(false);
1041 expect(
1042 sameUsageLimitCommandCoverage(failed, [{ ...base, accounts: [], error: "still down" }]),
1043 ).toBe(true);
1044 });
1045});
1046​
1047describe("remainingPercent", () => {
1048 it("inverts and clamps the reported usage", () => {
1049 expect(remainingPercent(window)).toBe(60);
1050 expect(remainingPercent({ ...window, usedPercent: 0 })).toBe(100);
1051 expect(remainingPercent({ ...window, usedPercent: 100 })).toBe(0);
1052 expect(remainingPercent({ ...window, usedPercent: 33.4 })).toBe(67);
1053 });
1054});
1055​
1056describe("isUsageLimitsCommand", () => {
1057 it("recognizes only the standalone local action", () => {
1058 expect(isUsageLimitsCommand(" /USAGE-LIMITS\n")).toBe(true);
1059 expect(isUsageLimitsCommand("/usage-limits explain")).toBe(false);
1060 expect(isUsageLimitsCommand("Explain /usage-limits")).toBe(false);
1061 expect(isUsageLimitsCommand("/usage")).toBe(false);
1062 });
1063});
1064​
1065describe("external usage settings", () => {
1066 it("deduplicates destinations across accounts and environments without inventing quota pools", () => {
1067 const managed = provider({
1068 usageLimits: {
1069 checkedAt: "2026-09-03T11:00:00.000Z",
1070 windows: [],
1071 unavailable: { reason: "unsupported", message: "Track usage in ChatGPT." },
1072 externalUsage: { label: "ChatGPT usage", url: "https://chatgpt.com/#settings/Usage" },
1073 },
1074 });
1075 const presentations = new Map([
1077 EnvironmentId.make("a"),
1079 entry: { target: { label: "A" } },
1080 serverConfig: {
1081 providers: [managed, { ...managed, instanceId: ProviderInstanceId.make("personal") }],
1082 },
1083 },
1084 ],
1086 EnvironmentId.make("b"),
1087 { entry: { target: { label: "B" } }, serverConfig: { providers: [managed] } },
1088 ],
1089 ]);
1090 expect(collectExternalUsageLinks(presentations)).toEqual([
1092 ...managed.usageLimits!.externalUsage,
1093 message: "Track usage in ChatGPT.",
1094 accounts: [`${managed.instanceId} on A`, "personal on A", `${managed.instanceId} on B`],
1095 },
1096 ]);
1097 expect(collectLimitAccounts(presentations)).toEqual([]);
1098 expect(collectLimitNotices(presentations)).toEqual([]);
1099 });
1100 it("omits disabled, uninstalled and signed-out providers", () => {
1101 const managed = provider({
1102 usageLimits: {
1103 checkedAt: "2026-09-03T11:00:00.000Z",
1104 windows: [],
1105 externalUsage: { label: "ChatGPT usage", url: "https://chatgpt.com/#settings/Usage" },
1106 },
1107 });
1108 const presentations = new Map([
1110 EnvironmentId.make("a"),
1112 entry: { target: { label: "A" } },
1113 serverConfig: {
1114 providers: [
1115 { ...managed, enabled: false },
1116 { ...managed, installed: false },
1117 { ...managed, auth: { status: "unauthenticated" as const } },
1118 provider({}),
1119 ],
1120 },
1121 },
1122 ],
1123 ]);
1124 expect(collectExternalUsageLinks(presentations)).toEqual([]);
1125 });
1126});
1127​
1128describe("ChatGPT sharing presentation", () => {
1129 it("requires verified sharing metadata rather than the Codex driver or login type", () => {
1130 const codex = provider({ auth: { status: "authenticated", type: "chatgpt" } });
1131 expect(usesChatGptSharing(codex)).toBe(false);
1132 expect(
1133 usesChatGptSharing({ ...codex, auth: { ...codex.auth, subscriptionSharing: true } }),
1134 ).toBe(true);
1135 expect(
1136 usesChatGptSharing({
1137 ...codex,
1138 auth: { status: "unauthenticated", subscriptionSharing: true },
1139 }),
1140 ).toBe(false);
1141 });
1142 it("only gives the matching current structured limit error a management action", () => {
1143 const limit: OrchestrationThreadActivity = {
1144 id: EventId.make("sharing-limit"),
1145 tone: "error",
1146 kind: "runtime.error",
1147 summary: "Runtime error",
1148 turnId: null,
1149 createdAt: "2026-09-03T12:00:00.000Z",
1150 payload: { code: "subscription_sharing_usage_limit_exceeded", message: "Limit reached" },
1151 };
1152 expect(isChatGptUsageLimitError([limit], "Limit reached")).toBe(true);
1153 expect(isChatGptUsageLimitError([limit], "A different failure")).toBe(false);
1154 expect(isChatGptUsageLimitError([limit], null)).toBe(false);
1155 expect(
1156 isChatGptUsageLimitError(
1157 [{ ...limit, payload: { message: "Limit reached" } }],
1158 "Limit reached",
1159 ),
1160 ).toBe(false);
1161 expect(
1162 isChatGptUsageLimitError(
1163 [limit, { ...limit, payload: { code: "unrelated", message: "Limit reached" } }],
1164 "Limit reached",
1165 ),
1166 ).toBe(false);
1167 });
1168});