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

usageLimits.test.ts

1,058 lines35.3 KB

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