Open History to see the last commit
1import {
2 EnvironmentId,
3 ProviderDriverKind,
4 ProviderInstanceId,
5 type ServerProvider,
6 type UsageLimitSourceAccount,
7 UsageLimitSourceId,
8} from "@t3tools/contracts";
9import { describe, expect, it } from "vite-plus/test";
10
11import {
12 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 };
55}
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", 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", instanceId: "claude" });
433 expect(account?.environments).toEqual([{ environmentId: "env-a", label: "Laptop" }]);
434 });
435
436 it("redeems on the environment whose snapshot supplied the credits on show", () => {
437 const stale = provider({
438 auth: { status: "authenticated", email: "same@example.com" },
439 usageLimits: {
440 checkedAt,
441 windows: [window],
442 resetCredits: { availableCount: 0 },
443 },
444 });
445 const fresh = {
446 ...stale,
447 usageLimits: {
448 checkedAt: "2026-09-03T11:30:00.000Z",
449 windows: [window],
450 resetCredits: { availableCount: 2 },
451 },
452 };
453 const input = new Map([
454 [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { providers: [stale] } }],
455 [
456 EnvironmentId.make("env-b"),
457 { entry: { target: { label: "Desktop" } }, serverConfig: { providers: [fresh] } },
458 ],
459 ]);
460 const [account] = collectLimitAccounts(input);
461 expect(account?.limits.resetCredits?.availableCount).toBe(2);
462 expect(account?.redeem).toEqual({ environmentId: "env-b", instanceId: "codex" });
463 });
464
465 it("names an environment once however many of its instances share the account", () => {
466 const shared = provider({
467 auth: { status: "authenticated", email: "same@example.com" },
468 usageLimits: { checkedAt, windows: [window] },
469 });
470 const input = new Map([
471 [
472 EnvironmentId.make("env-a"),
473 {
474 ...laptop,
475 serverConfig: {
476 providers: [shared, { ...shared, instanceId: ProviderInstanceId.make("work") }],
477 },
478 },
479 ],
480 ]);
481 expect(collectLimitAccounts(input)[0]?.environments).toEqual([
482 { environmentId: "env-a", label: "Laptop" },
483 ]);
484 });
485
486 it("keys a hub account without an email by hub, so two environments on one hub share it", () => {
487 const seat = {
488 id: "claude-team-seat.json",
489 driver: claude,
490 usageLimits: { checkedAt, windows: [window] },
491 };
492 const hub = { ...source, accounts: [seat] };
493 const input = new Map([
494 [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { usageLimitSources: [hub] } }],
495 [
496 EnvironmentId.make("env-b"),
497 { entry: { target: { label: "Desktop" } }, serverConfig: { usageLimitSources: [hub] } },
498 ],
499 ]);
500 const accounts = collectLimitAccounts(input);
501 expect(accounts.map((account) => account.key)).toEqual(["hub:claude-team-seat.json"]);
502 expect(accounts[0]?.displayName).toBe("claude-team-seat");
503 });
504
505 it("pools windows by id across accounts and orders resets by when they land", () => {
506 const input = new Map([
507 [
508 EnvironmentId.make("env-a"),
509 {
510 ...laptop,
511 serverConfig: {
512 providers: [],
513 usageLimitSources: [
514 {
515 ...source,
516 accounts: [
517 {
518 id: "a",
519 driver: claude,
520 usageLimits: {
521 checkedAt,
522 windows: [
523 { ...window, usedPercent: 80, resetsAt: "2026-09-03T13:00:00.000Z" },
524 { ...weekly, usedPercent: 20 },
525 ],
526 },
527 },
528 {
529 id: "b",
530 driver: claude,
531 usageLimits: {
532 checkedAt,
533 windows: [{ ...window, usedPercent: 40 }],
534 },
535 },
536 {
537 id: "c",
538 driver: ProviderDriverKind.make("codex"),
539 usageLimits: { checkedAt, windows: [{ ...weekly, usedPercent: 50 }] },
540 },
541 {
542 id: "unsupported",
543 driver: claude,
544 usageLimits: {
545 checkedAt,
546 windows: [],
547 unavailable: { reason: "unsupported" as const },
548 },
549 },
550 ],
551 },
552 ],
553 },
554 },
555 ],
556 ]);
557 const pools = collectLimitPools(collectLimitAccounts(input), now);
558 expect(pools.map((pool) => [pool.driver, pool.accounts.length])).toEqual([
559 ["claudeAgent", 2],
560 ["codex", 1],
561 ]);
562 const [session, week] = pools[0]!.windows;
563 // A member with no reset has no clock, so it does not vote on pace.
564 const untimed = collectLimitPools(
565 collectLimitAccounts(input).map((account) =>
566 account.key === "hub:b"
567 ? {
568 ...account,
569 limits: {
570 ...account.limits,
571 windows: account.limits.windows.map((w) => ({ ...w, resetsAt: undefined })),
572 },
573 }
574 : account,
575 ),
576 now,
577 );
578 // Only a votes: 80% used, 80% elapsed.
579 expect(untimed[0]?.windows[0]?.pace).toBe("on");
580 // a is 80% through its window and b 60%: the pool is 70% elapsed, 60% used.
581 expect(session).toMatchObject({
582 id: "five_hour",
583 remainingPercent: 40,
584 usedPercent: 60,
585 pace: "under",
586 });
587 expect(
588 session?.resets.map((reset) => [reset.member.account.key, reset.restoresPercent]),
589 ).toEqual([
590 ["hub:a", 40],
591 ["hub:b", 20],
592 ]);
593 expect(week).toMatchObject({ id: "seven_day", remainingPercent: 80, members: [{}] });
594 // Codex reports `primary` for both its five-hour and (on Go) monthly window.
595 const mixed = collectLimitPools(
596 [
597 ...collectLimitAccounts(input),
598 {
599 key: "go",
600 driver: claude,
601 displayName: "Go",
602 email: undefined,
603 plan: undefined,
604 accentColor: undefined,
605 environments: [],
606 sourceLabel: null,
607 redeem: null,
608 limits: {
609 checkedAt,
610 windows: [
611 {
612 id: "five_hour",
613 kind: "monthly",
614 label: "Monthly",
615 usedPercent: 82,
616 windowDurationMins: 30 * 24 * 60,
617 resetsAt: "2026-09-14T12:00:00.000Z",
618 },
619 ],
620 },
621 },
622 ],
623 now,
624 );
625 expect(mixed[0]?.windows.map((window) => [window.kind, window.members.length])).toEqual([
626 ["session", 2],
627 ["weekly", 1],
628 ["monthly", 1],
629 ]);
630 // Segments read left to right as "who refills next", matching the reset list.
631 expect(session?.members.map((member) => member.account.key)).toEqual(["hub:a", "hub:b"]);
632 expect(pools[0]?.accounts.map((account) => account.key)).toEqual(["hub:a", "hub:b"]);
633 });
634});
635
636describe("collectLimitNotices", () => {
637 const checkedAt = "2026-09-03T11:00:00.000Z";
638 const claude = ProviderDriverKind.make("claudeAgent");
639 const laptop = { entry: { target: { label: "Laptop" } } };
640 const hub = {
641 id: UsageLimitSourceId.make("hub"),
642 kind: "cliproxy" as const,
643 label: "hub",
644 checkedAt,
645 accounts: [],
646 };
647
648 it("names failures and silence, skips unsupported accounts, and labels environments only when several", () => {
649 const failed = provider({
650 instanceId: ProviderInstanceId.make("claude"),
651 driver: claude,
652 displayName: "Claude Max",
653 usageLimits: { checkedAt, windows: [], unavailable: { reason: "probeFailed" } },
654 });
655 const apiKey = provider({
656 instanceId: ProviderInstanceId.make("api"),
657 driver: claude,
658 usageLimits: { checkedAt, windows: [], unavailable: { reason: "unsupported" } },
659 });
660 const silent = provider({ usageLimits: { checkedAt, windows: [] } });
661 const one = new Map([
662 [
663 EnvironmentId.make("env-a"),
664 {
665 ...laptop,
666 serverConfig: {
667 providers: [failed, apiKey, silent],
668 usageLimitSources: [
669 hub,
670 { ...hub, id: UsageLimitSourceId.make("down"), label: "down", error: "ECONNREFUSED" },
671 ],
672 },
673 },
674 ],
675 ]);
676 expect(collectLimitNotices(one)).toEqual([
677 "Claude Max: Could not read limits.",
678 "codex: No limits reported.",
679 "hub: No accounts reported.",
680 "down: ECONNREFUSED",
681 ]);
682
683 one.set(EnvironmentId.make("env-b"), {
684 entry: { target: { label: "Desktop" } },
685 serverConfig: { providers: [], usageLimitSources: [] },
686 });
687 expect(collectLimitNotices(one)[0]).toBe("Laptop · Claude Max: Could not read limits.");
688 });
689});
690
691describe("/usage-limits", () => {
692 const limits = { checkedAt: "2026-09-03T11:00:00.000Z", windows: [window] };
693 const selected = provider({
694 usageLimits: limits,
695 auth: { status: "authenticated", email: "same@example.com" },
696 });
697 const sources = [
698 {
699 id: UsageLimitSourceId.make("hub"),
700 kind: "cliproxy" as const,
701 label: "Accounts",
702 checkedAt: limits.checkedAt,
703 accounts: [
704 {
705 id: "duplicate",
706 driver: selected.driver,
707 email: "SAME@example.com",
708 usageLimits: limits,
709 },
710 { id: "oss", driver: selected.driver, plan: "Codex OSS", usageLimits: limits },
711 { id: "other-provider", driver: ProviderDriverKind.make("claude"), usageLimits: limits },
712 ],
713 },
714 ];
715
716 it("keeps accounts and custom instances separate, filtering by driver", () => {
717 const report = collectProviderUsageLimits(
718 selected.instanceId,
719 [
720 selected,
721 provider({
722 instanceId: ProviderInstanceId.make("codex-work"),
723 displayName: "Work",
724 usageLimits: { ...limits, resetCredits: { availableCount: 2 } },
725 }),
726 provider({
727 driver: ProviderDriverKind.make("claude"),
728 instanceId: ProviderInstanceId.make("claude"),
729 usageLimits: limits,
730 }),
731 ],
732 sources,
733 now,
734 );
735 expect(report?.createdAt).toBe("2026-09-03T12:00:00.000Z");
736 expect(report?.accounts.map((account) => account.id)).toEqual([
737 "codex",
738 "codex-work",
739 "hub:oss",
740 ]);
741 expect(report?.accounts[0]).toMatchObject({
742 instanceId: selected.instanceId,
743 email: selected.auth.email,
744 });
745 expect(report?.accounts[1]).toMatchObject({
746 displayName: "Work",
747 limits: { resetCredits: { availableCount: 2 } },
748 });
749 expect(report?.accounts[2]).toMatchObject({
750 label: "Accounts · oss",
751 sourceLabel: "CLI Proxy",
752 plan: "Codex OSS",
753 });
754 expect(report?.notices).toEqual([]);
755 });
756
757 it("supports a source-only provider and keeps duplicates when the native probe failed", () => {
758 expect(
759 collectProviderUsageLimits(selected.instanceId, [provider({})], sources, now)?.accounts.map(
760 (account) => account.id,
761 ),
762 ).toEqual(["hub:duplicate", "hub:oss"]);
763 const failed = provider({ usageLimits: { ...limits, unavailable: { reason: "probeFailed" } } });
764 expect(
765 collectProviderUsageLimits(selected.instanceId, [failed], sources, now)?.accounts.map(
766 (account) => account.id,
767 ),
768 ).toEqual(["codex", "hub:duplicate", "hub:oss"]);
769 expect(collectProviderUsageLimits(selected.instanceId, [provider({})], [], now)).toBeNull();
770 expect(
771 collectProviderUsageLimits(
772 selected.instanceId,
773 [provider({ enabled: false, usageLimits: limits })],
774 [],
775 now,
776 ),
777 ).toBeNull();
778 });
779
780 it("surfaces source errors only for sources that carry the selected driver", () => {
781 const failing = { ...sources[0]!, error: "token expired" };
782 expect(
783 collectProviderUsageLimits(selected.instanceId, [selected], [failing], now)?.notices,
784 ).toEqual(["Accounts: token expired"]);
785 const claudeOnly = { ...failing, accounts: failing.accounts.slice(2) };
786 expect(
787 collectProviderUsageLimits(selected.instanceId, [selected], [claudeOnly], now)?.notices,
788 ).toEqual([]);
789 // A read failure clears the accounts, so the error must not depend on a match.
790 const unreadable = { ...failing, accounts: [] };
791 expect(
792 collectProviderUsageLimits(selected.instanceId, [selected], [unreadable], now)?.notices,
793 ).toEqual(["Accounts: token expired"]);
794 // A source-only provider still gets the report, carrying only the error.
795 const sourceOnly = collectProviderUsageLimits(
796 selected.instanceId,
797 [provider({})],
798 [unreadable],
799 now,
800 );
801 expect(sourceOnly?.accounts).toEqual([]);
802 expect(sourceOnly?.notices).toEqual(["Accounts: token expired"]);
803 });
804
805 it("advertises global and workspace commands only for providers present in Limits", () => {
806 const withWorkspace = provider({
807 workspaceSnapshots: [
808 { cwd: "/tmp/project", checkedAt: limits.checkedAt, slashCommands: [], skills: [] },
809 ],
810 });
811 const [supported] = withUsageLimitsCommands([withWorkspace], sources);
812 expect(supported?.slashCommands.map((command) => command.name)).toEqual(["usage-limits"]);
813 expect(
814 supported?.workspaceSnapshots?.[0]?.slashCommands.map((command) => command.name),
815 ).toEqual(["usage-limits"]);
816 expect(withUsageLimitsCommands([withWorkspace], [])[0]?.slashCommands).toEqual([]);
817 // A provider's own command of the same name is left alone without coverage.
818 const ownCommand = provider({
819 slashCommands: [{ name: "usage-limits", description: "Provider's own" }],
820 });
821 expect(withUsageLimitsCommands([ownCommand], [])[0]?.slashCommands).toEqual([
822 { name: "usage-limits", description: "Provider's own" },
823 ]);
824 const unreadable = { ...sources[0]!, accounts: [], error: "token expired" };
825 expect(
826 withUsageLimitsCommands([withWorkspace], [unreadable])[0]?.slashCommands.map(
827 (command) => command.name,
828 ),
829 ).toEqual(["usage-limits"]);
830 expect(
831 withUsageLimitsCommands([selected], [])[0]?.slashCommands.map((command) => command.name),
832 ).toEqual(["usage-limits"]);
833 });
834});
835
836describe("sameUsageLimitCommandCoverage", () => {
837 const codexAccount = {
838 id: "a",
839 driver: ProviderDriverKind.make("codex"),
840 usageLimits: { checkedAt: "2026-09-03T11:00:00.000Z", windows: [] },
841 };
842 const base = {
843 id: UsageLimitSourceId.make("hub"),
844 kind: "cliproxy" as const,
845 label: "Accounts",
846 checkedAt: "2026-09-03T11:00:00.000Z",
847 };
848 it("ignores quota movement but not the drivers offered the command", () => {
849 const withCodex = [{ ...base, accounts: [codexAccount] }];
850 const withCodexLater = [
851 {
852 ...base,
853 accounts: [
854 {
855 ...codexAccount,
856 usageLimits: { ...codexAccount.usageLimits, checkedAt: "2026-09-03T12:00:00.000Z" },
857 },
858 ],
859 },
860 ];
861 expect(sameUsageLimitCommandCoverage(withCodex, withCodexLater)).toBe(true);
862 expect(sameUsageLimitCommandCoverage(withCodex, [{ ...base, accounts: [] }])).toBe(false);
863 });
864 it("treats a failed read as a change in coverage, in both directions", () => {
865 const empty = [{ ...base, accounts: [] }];
866 const failed = [{ ...base, accounts: [], error: "token expired" }];
867 expect(sameUsageLimitCommandCoverage(empty, failed)).toBe(false);
868 expect(sameUsageLimitCommandCoverage(failed, empty)).toBe(false);
869 expect(
870 sameUsageLimitCommandCoverage(failed, [{ ...base, accounts: [], error: "still down" }]),
871 ).toBe(true);
872 });
873});
874
875describe("remainingPercent", () => {
876 it("inverts and clamps the reported usage", () => {
877 expect(remainingPercent(window)).toBe(60);
878 expect(remainingPercent({ ...window, usedPercent: 0 })).toBe(100);
879 expect(remainingPercent({ ...window, usedPercent: 100 })).toBe(0);
880 expect(remainingPercent({ ...window, usedPercent: 33.4 })).toBe(67);
881 });
882});
883
884describe("isUsageLimitsCommand", () => {
885 it("recognizes only the standalone local action", () => {
886 expect(isUsageLimitsCommand(" /USAGE-LIMITS\n")).toBe(true);
887 expect(isUsageLimitsCommand("/usage-limits explain")).toBe(false);
888 expect(isUsageLimitsCommand("Explain /usage-limits")).toBe(false);
889 expect(isUsageLimitsCommand("/usage")).toBe(false);
890 });
891});