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

usageLimits.test.ts

1,106 lines37.2 KB

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