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

usageLimits.test.ts

1,017 lines34.1 KB

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