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