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

usageLimits.test.ts

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