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