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