Open History to see the last commit
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 collectProviderUsageLimits,
13 sameUsageLimitCommandCoverage,
14 withUsageLimitsCommands,
15 collectLimitAccounts,
16 collectExternalUsageLinks,
17 collectLimitNotices,
18 collectLimitPools,
19 elapsedShare,
20 paceOf,
21 paceRemainingPercent,
22 usesChatGptSharing,
23} from "./usageLimits.ts";
24
25const now = Date.parse("2026-09-03T12:00:00.000Z");
26
27const window = {
28 id: "five_hour",
29 kind: "session",
30 label: "Session",
31 usedPercent: 40,
32 windowDurationMins: 300,
33 resetsAt: "2026-09-03T14:00:00.000Z",
34} as const;
35
36function provider(overrides: Partial<ServerProvider>): ServerProvider {
37 return {
38 instanceId: ProviderInstanceId.make("codex"),
39 driver: ProviderDriverKind.make("codex"),
40 enabled: true,
41 installed: true,
42 version: null,
43 status: "ready",
44 auth: { status: "authenticated" },
45 checkedAt: "2026-09-03T11:00:00.000Z",
46 models: [],
47 slashCommands: [],
48 skills: [],
49 ...overrides,
50 };
51}
52
53describe("pace", () => {
54 it("places the clock three fifths through a five-hour window with two hours left", () => {
55 expect(elapsedShare(window, now)).toBeCloseTo(0.6);
56 expect(paceRemainingPercent(window, now)).toBe(40);
57 expect(paceOf(window, now)).toBe("under");
58 expect(paceOf({ ...window, usedPercent: 62 }, now)).toBe("on");
59 expect(paceOf({ ...window, usedPercent: 80 }, now)).toBe("ahead");
60 });
61});
62
63describe("pools", () => {
64 const checkedAt = "2026-09-03T11:00:00.000Z";
65 const weekly = {
66 id: "seven_day",
67 kind: "weekly",
68 label: "Weekly",
69 windowDurationMins: 7 * 24 * 60,
70 resetsAt: "2026-09-06T12:00:00.000Z",
71 } as const;
72 const claude = ProviderDriverKind.make("claudeAgent");
73 const source = {
74 id: UsageLimitSourceId.make("hub"),
75 kind: "cliproxy" as const,
76 label: "hub",
77 checkedAt,
78 };
79 const laptop = { entry: { target: { label: "Laptop" } } };
80
81 it("merges one account reported natively on two environments and by a hub into one entry", () => {
82 const native = provider({
83 driver: claude,
84 instanceId: ProviderInstanceId.make("claude"),
85 auth: { status: "authenticated", email: "Same@example.com" },
86 usageLimits: { checkedAt, windows: [{ ...window, usedPercent: 40 }] },
87 });
88 const input = new Map([
89 [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { providers: [native] } }],
90 [
91 EnvironmentId.make("env-b"),
92 {
93 entry: { target: { label: "Desktop" } },
94 serverConfig: {
95 providers: [
96 {
97 ...native,
98 usageLimits: {
99 checkedAt: "2026-09-03T11:30:00.000Z",
100 windows: [{ ...window, usedPercent: 55 }],
101 },
102 },
103 ],
104 usageLimitSources: [
105 {
106 ...source,
107 accounts: [
108 {
109 id: "claude-same@example.com.json",
110 driver: claude,
111 email: "same@example.com",
112 plan: "Claude Subscription",
113 usageLimits: { checkedAt, windows: [{ ...window, usedPercent: 10 }] },
114 },
115 ],
116 },
117 ],
118 },
119 },
120 ],
121 ]);
122 const accounts = collectLimitAccounts(input);
123 expect(accounts).toHaveLength(1);
124 expect(accounts[0]).toMatchObject({
125 key: "env-a:claude",
126 sourceLabel: null,
127 redeem: { environmentId: "env-b", input: { instanceId: "claude" } },
128 environments: [
129 { environmentId: "env-a", label: "Laptop" },
130 { environmentId: "env-b", label: "Desktop" },
131 ],
132 });
133 expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(55);
134 });
135
136 it("merges OpenCode Go limits from machines with the same API key", () => {
137 const go = provider({
138 driver: ProviderDriverKind.make("opencode"),
139 instanceId: ProviderInstanceId.make("opencode"),
140 auth: { status: "authenticated" },
141 usageLimits: {
142 checkedAt,
143 credentialFingerprint: "shared-go-key",
144 windows: [{ ...window, id: "go_rolling", usedPercent: 3 }],
145 },
146 });
147 const input = new Map([
148 [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { providers: [go] } }],
149 [
150 EnvironmentId.make("env-b"),
151 {
152 entry: { target: { label: "Desktop" } },
153 serverConfig: {
154 providers: [
155 {
156 ...go,
157 usageLimits: {
158 ...go.usageLimits!,
159 checkedAt: "2026-09-03T11:30:00.000Z",
160 windows: [{ ...window, id: "go_rolling", usedPercent: 4 }],
161 },
162 },
163 ],
164 },
165 },
166 ],
167 ]);
168 const accounts = collectLimitAccounts(input);
169 expect(accounts).toHaveLength(1);
170 expect(accounts[0]?.environments).toEqual([
171 { environmentId: "env-a", label: "Laptop" },
172 { environmentId: "env-b", label: "Desktop" },
173 ]);
174 expect(collectLimitPools(accounts, now)[0]?.windows[0]?.members).toHaveLength(1);
175 expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(4);
176
177 const differentKey = {
178 ...go,
179 usageLimits: { ...go.usageLimits!, credentialFingerprint: "other-go-key" },
180 };
181 input.set(EnvironmentId.make("env-b"), {
182 entry: { target: { label: "Desktop" } },
183 serverConfig: { providers: [differentKey] },
184 });
185 expect(collectLimitAccounts(input)).toHaveLength(2);
186
187 input.set(EnvironmentId.make("env-a"), {
188 ...laptop,
189 serverConfig: {
190 providers: [{ ...go, auth: { status: "authenticated", email: "same@example.com" } }],
191 },
192 });
193 input.set(EnvironmentId.make("env-b"), {
194 entry: { target: { label: "Desktop" } },
195 serverConfig: {
196 providers: [
197 { ...differentKey, auth: { status: "authenticated", email: "SAME@example.com" } },
198 ],
199 },
200 });
201 expect(collectLimitAccounts(input)).toHaveLength(1);
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 expect(account?.redeem).toEqual({
290 environmentId: "env-a",
291 input: { sourceId: "hub", accountId: "claude-same@example.com.json", creditId: "hub-credit" },
292 });
293 expect(account?.limits.resetCredits?.availableCount).toBe(3);
294 });
295
296 it("redeems on the environment whose snapshot supplied the credits on show", () => {
297 const stale = provider({
298 auth: { status: "authenticated", email: "same@example.com" },
299 usageLimits: {
300 checkedAt,
301 windows: [window],
302 resetCredits: { availableCount: 0 },
303 },
304 });
305 const fresh = {
306 ...stale,
307 usageLimits: {
308 checkedAt: "2026-09-03T11:30:00.000Z",
309 windows: [window],
310 resetCredits: { availableCount: 2 },
311 },
312 };
313 const input = new Map([
314 [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { providers: [stale] } }],
315 [
316 EnvironmentId.make("env-b"),
317 { entry: { target: { label: "Desktop" } }, serverConfig: { providers: [fresh] } },
318 ],
319 ]);
320 const [account] = collectLimitAccounts(input);
321 expect(account?.limits.resetCredits?.availableCount).toBe(2);
322 expect(account?.redeem).toEqual({ environmentId: "env-b", input: { instanceId: "codex" } });
323 });
324
325 it("keeps distinct hub accounts redeemable through their own source", () => {
326 const hubAccounts = ["first", "second"].map((id) => ({
327 id,
328 driver: ProviderDriverKind.make("codex"),
329 email: `${id}@example.com`,
330 usageLimits: {
331 checkedAt,
332 windows: [window],
333 resetCredits: { availableCount: 2, nextCreditId: `${id}-credit` },
334 },
335 }));
336 const input = new Map([
337 [
338 EnvironmentId.make("env-a"),
339 {
340 ...laptop,
341 serverConfig: {
342 providers: [],
343 usageLimitSources: [{ ...source, accounts: hubAccounts }],
344 },
345 },
346 ],
347 ]);
348 expect(collectLimitAccounts(input).map((account) => account.redeem)).toEqual(
349 hubAccounts.map((account) => ({
350 environmentId: "env-a",
351 input: { sourceId: "hub", accountId: account.id, creditId: `${account.id}-credit` },
352 })),
353 );
354 });
355
356 it("does not give old credits the timestamp of a newer window-only read", () => {
357 const snapshots = [
358 { checkedAt, windows: [window], resetCredits: { availableCount: 2 } },
359 { checkedAt: "2026-09-03T12:00:00.000Z", windows: [window] },
360 {
361 checkedAt: "2026-09-03T11:30:00.000Z",
362 windows: [window],
363 resetCredits: { availableCount: 1 },
364 },
365 ];
366 const input = new Map(
367 snapshots.map((usageLimits, i) => [
368 EnvironmentId.make(`env-${i}`),
369 {
370 ...laptop,
371 serverConfig: {
372 providers: [
373 provider({
374 auth: { status: "authenticated", email: "same@example.com" },
375 usageLimits,
376 }),
377 ],
378 },
379 },
380 ]),
381 );
382 const [account] = collectLimitAccounts(input);
383 expect(account?.limits.checkedAt).toBe("2026-09-03T12:00:00.000Z");
384 expect(account?.limits.resetCredits?.availableCount).toBe(1);
385 expect(account?.redeem?.environmentId).toBe("env-2");
386 });
387
388 it("keeps one email in two workspaces apart while merging each workspace's duplicates", () => {
389 const login = (instanceId: string, workspaceId: string, usedPercent: number) =>
390 provider({
391 instanceId: ProviderInstanceId.make(instanceId),
392 auth: { status: "authenticated", email: "same@example.com", workspaceId },
393 usageLimits: { checkedAt, windows: [{ ...weekly, usedPercent }] },
394 });
395 const hubAccount = (id: string, workspaceId?: string) => ({
396 id,
397 driver: ProviderDriverKind.make("codex"),
398 email: "same@example.com",
399 ...(workspaceId ? { workspaceId } : {}),
400 usageLimits: { checkedAt, windows: [{ ...weekly, usedPercent: 50 }] },
401 });
402 const input = new Map([
403 [
404 EnvironmentId.make("env-a"),
405 {
406 ...laptop,
407 serverConfig: {
408 providers: [login("business", "ws-business", 8), login("personal", "ws-plus", 26)],
409 usageLimitSources: [
410 { ...source, accounts: [hubAccount("plus.json", "ws-plus"), hubAccount("x.json")] },
411 ],
412 },
413 },
414 ],
415 [
416 EnvironmentId.make("env-b"),
417 {
418 entry: { target: { label: "Desktop" } },
419 serverConfig: { providers: [login("personal", "ws-plus", 26)] },
420 },
421 ],
422 ]);
423 const accounts = collectLimitAccounts(input);
424 expect(accounts.map((account) => account.key)).toEqual([
425 "env-a:business",
426 "env-a:personal",
427 "hub:x.json",
428 ]);
429 expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(8);
430 const withoutEmail = (id: string, workspaceId: string) => {
431 const { email: _email, ...account } = hubAccount(id, workspaceId);
432 return account;
433 };
434 const sameFile = new Map([
435 [
436 EnvironmentId.make("env-a"),
437 {
438 ...laptop,
439 serverConfig: {
440 providers: [],
441 usageLimitSources: [{ ...source, accounts: [withoutEmail("a.json", "ws-1")] }],
442 },
443 },
444 ],
445 [
446 EnvironmentId.make("env-b"),
447 {
448 ...laptop,
449 serverConfig: {
450 providers: [],
451 usageLimitSources: [{ ...source, accounts: [withoutEmail("a.json", "ws-2")] }],
452 },
453 },
454 ],
455 ]);
456 expect(collectLimitAccounts(sameFile).map((account) => account.key)).toEqual([
457 "hub:a.json:ws-1",
458 "hub:a.json:ws-2",
459 ]);
460 expect(accounts[1]?.environments.map((environment) => environment.label)).toEqual([
461 "Laptop",
462 "Desktop",
463 ]);
464 });
465
466 it("joins a report without a workspace to the only workspace signed in with its email", () => {
467 const native = provider({
468 driver: claude,
469 auth: { status: "authenticated", email: "same@example.com", workspaceId: "org-a" },
470 usageLimits: { checkedAt, windows: [window] },
471 });
472 const hubAccount = {
473 id: "claude.json",
474 driver: claude,
475 email: "same@example.com",
476 usageLimits: { checkedAt, windows: [window] },
477 };
478 const withOther = (other: ServerProvider) =>
479 new Map([
480 [
481 EnvironmentId.make("env-a"),
482 {
483 ...laptop,
484 serverConfig: {
485 providers: [native, other],
486 usageLimitSources: [{ ...source, accounts: [hubAccount] }],
487 },
488 },
489 ],
490 ]);
491 const unrelated = provider({ instanceId: ProviderInstanceId.make("codex-2") });
492 expect(collectLimitAccounts(withOther(unrelated)).map((account) => account.key)).toEqual([
493 "env-a:codex",
494 ]);
495 const unreadable = provider({
496 ...native,
497 instanceId: ProviderInstanceId.make("team"),
498 auth: { ...native.auth, workspaceId: "org-b" },
499 usageLimits: { checkedAt, windows: [], unavailable: { reason: "probeFailed" } },
500 });
501 expect(collectLimitAccounts(withOther(unreadable)).map((account) => account.key)).toEqual([
502 "env-a:codex",
503 "hub:claude.json",
504 ]);
505 });
506
507 it("keys a hub account without an email by hub, so two environments on one hub share it", () => {
508 const seat = {
509 id: "claude-team-seat.json",
510 driver: claude,
511 usageLimits: { checkedAt, windows: [window] },
512 };
513 const hub = { ...source, accounts: [seat] };
514 const input = new Map([
515 [
516 EnvironmentId.make("env-a"),
517 { ...laptop, serverConfig: { providers: [], usageLimitSources: [hub] } },
518 ],
519 [
520 EnvironmentId.make("env-b"),
521 {
522 entry: { target: { label: "Desktop" } },
523 serverConfig: { providers: [], usageLimitSources: [hub] },
524 },
525 ],
526 ]);
527 const accounts = collectLimitAccounts(input);
528 expect(accounts.map((account) => account.key)).toEqual(["hub:claude-team-seat.json"]);
529 expect(accounts[0]?.displayName).toBe("claude-team-seat");
530 });
531
532 it("pools Codex windows by kind, whichever slot reported them", () => {
533 const codexAccount = (id: string, slots: readonly string[]) => ({
534 id,
535 driver: ProviderDriverKind.make("codex"),
536 usageLimits: {
537 checkedAt,
538 windows: slots.map((slot) => ({ ...weekly, id: slot, usedPercent: 50 })),
539 },
540 });
541 const pooled = (accounts: ReturnType<typeof codexAccount>[]) =>
542 collectLimitPools(
543 collectLimitAccounts(
544 new Map([
545 [
546 EnvironmentId.make("env-a"),
547 {
548 ...laptop,
549 serverConfig: { providers: [], usageLimitSources: [{ ...source, accounts }] },
550 },
551 ],
552 ]),
553 ),
554 now,
555 )[0]?.windows ?? [];
556 for (const order of [
557 [codexAccount("business", ["primary"]), codexAccount("plus", ["secondary"])],
558 [codexAccount("plus", ["secondary"]), codexAccount("business", ["primary"])],
559 ]) {
560 const windows = pooled(order);
561 expect(windows.map((window) => window.id)).toEqual(["weekly"]);
562 expect(windows[0]?.members).toHaveLength(2);
563 }
564 expect(
565 pooled([codexAccount("a", ["secondary"]), codexAccount("b", ["primary", "secondary"])]).map(
566 (window) => window.id,
567 ),
568 ).toEqual(["weekly", "weekly:secondary"]);
569 });
570
571 it("pools windows by id across accounts and orders resets by when they land", () => {
572 const input = new Map([
573 [
574 EnvironmentId.make("env-a"),
575 {
576 ...laptop,
577 serverConfig: {
578 providers: [],
579 usageLimitSources: [
580 {
581 ...source,
582 accounts: [
583 {
584 id: "a",
585 driver: claude,
586 usageLimits: {
587 checkedAt,
588 windows: [
589 { ...window, usedPercent: 80, resetsAt: "2026-09-03T13:00:00.000Z" },
590 { ...weekly, usedPercent: 20 },
591 ],
592 },
593 },
594 {
595 id: "b",
596 driver: claude,
597 usageLimits: {
598 checkedAt,
599 windows: [{ ...window, usedPercent: 40 }],
600 },
601 },
602 {
603 id: "c",
604 driver: ProviderDriverKind.make("codex"),
605 usageLimits: { checkedAt, windows: [{ ...weekly, usedPercent: 50 }] },
606 },
607 {
608 id: "unsupported",
609 driver: claude,
610 usageLimits: {
611 checkedAt,
612 windows: [],
613 unavailable: { reason: "unsupported" as const },
614 },
615 },
616 ],
617 },
618 ],
619 },
620 },
621 ],
622 ]);
623 const pools = collectLimitPools(collectLimitAccounts(input), now);
624 expect(pools.map((pool) => [pool.driver, pool.accounts.length])).toEqual([
625 ["claudeAgent", 2],
626 ["codex", 1],
627 ]);
628 const [session, week] = pools[0]!.windows;
629 const untimed = collectLimitPools(
630 collectLimitAccounts(input).map((account) =>
631 account.key === "hub:b"
632 ? {
633 ...account,
634 limits: {
635 ...account.limits,
636 windows: account.limits.windows.map((w) => ({ ...w, resetsAt: undefined })),
637 },
638 }
639 : account,
640 ),
641 now,
642 );
643 expect(untimed[0]?.windows[0]?.pace).toBe("on");
644 expect(session).toMatchObject({
645 id: "five_hour",
646 remainingPercent: 40,
647 usedPercent: 60,
648 pace: "under",
649 });
650 expect(
651 session?.resets.map((reset) => [reset.member.account.key, reset.restoresPercent]),
652 ).toEqual([
653 ["hub:a", 40],
654 ["hub:b", 20],
655 ]);
656 expect(week).toMatchObject({ id: "seven_day", remainingPercent: 80, members: [{}] });
657 // Codex reports `primary` for both its five-hour and (on Go) monthly window.
658 const mixed = collectLimitPools(
659 [
660 ...collectLimitAccounts(input),
661 {
662 key: "go",
663 driver: claude,
664 displayName: "Go",
665 email: undefined,
666 plan: undefined,
667 accentColor: undefined,
668 environments: [],
669 sourceLabel: null,
670 redeem: null,
671 limits: {
672 checkedAt,
673 windows: [
674 {
675 id: "five_hour",
676 kind: "monthly",
677 label: "Monthly",
678 usedPercent: 82,
679 windowDurationMins: 30 * 24 * 60,
680 resetsAt: "2026-09-14T12:00:00.000Z",
681 },
682 ],
683 },
684 },
685 ],
686 now,
687 );
688 expect(mixed[0]?.windows.map((window) => [window.kind, window.members.length])).toEqual([
689 ["session", 2],
690 ["weekly", 1],
691 ["monthly", 1],
692 ]);
693 expect(session?.members.map((member) => member.account.key)).toEqual(["hub:a", "hub:b"]);
694 expect(pools[0]?.accounts.map((account) => account.key)).toEqual(["hub:a", "hub:b"]);
695 });
696});
697
698describe("pooled account columns", () => {
699 const weekly = {
700 ...window,
701 id: "seven_day",
702 kind: "weekly",
703 label: "Weekly",
704 windowDurationMins: 7 * 24 * 60,
705 } as const;
706 const account = (key: string, windows: LimitAccount["limits"]["windows"]): LimitAccount => ({
707 key,
708 driver: ProviderDriverKind.make("claudeAgent"),
709 displayName: key,
710 email: undefined,
711 plan: undefined,
712 accentColor: undefined,
713 environments: [],
714 sourceLabel: "Hub",
715 redeem: null,
716 limits: { checkedAt: "2026-09-03T11:00:00.000Z", windows },
717 });
718 const keys = (pool: ReturnType<typeof collectLimitPools>[number]) =>
719 pool.windows.map((row) =>
720 row.columns.map((member) => (member.window ? member.account.key : null)),
721 );
722
723 // regression: #20349 sessions stay visible while the weekly quota is exhausted
724 it.each([
725 ["claudeAgent", "13:00", 40, "14:00", 100],
726 ["codex", "14:00", 100, "14:00", 100],
727 ["claudeAgent", "15:00", 100, "15:00", 100],
728 ["codex", "15:00", 40, "14:00", 60],
729 ] as const)(
730 "%s session resetting at %s with %i percent spent becomes usable at %s with %i percent restored",
731 (driver, sessionReset, usedPercent, usableAt, restoresPercent) => {
732 const at = (time: string) => `2026-09-03T${time}:00.000Z`;
733 const a = {
734 ...account("a", [
735 {
736 ...window,
737 id: driver === "codex" ? "primary" : window.id,
738 usedPercent,
739 resetsAt: at(sessionReset),
740 },
741 {
742 ...weekly,
743 id: driver === "codex" ? "secondary" : weekly.id,
744 usedPercent: 100,
745 resetsAt: at("14:00"),
746 },
747 ]),
748 driver: ProviderDriverKind.make(driver),
749 };
750 const [session] = collectLimitPools([a], now)[0]!.windows;
751 expect.soft(session?.remainingPercent).toBe(0);
752 expect(session?.resets[0]).toMatchObject({
753 at: Date.parse(at(usableAt)),
754 restoresPercent,
755 });
756 },
757 );
758
759 it("excludes weekly-blocked sessions from the pool without changing snapshots or model allowances", () => {
760 const blocked = account("blocked", [
761 window,
762 { ...weekly, usedPercent: 100 },
763 { ...weekly, id: "seven_day_fable", usedPercent: 20 },
764 ]);
765 const accounts = [
766 blocked,
767 account("available", [
768 { ...window, usedPercent: 20 },
769 { ...weekly, usedPercent: 99 },
770 { ...weekly, id: "seven_day_fable", usedPercent: 40 },
771 ]),
772 { ...blocked, key: "cursor", driver: ProviderDriverKind.make("cursor") },
773 ];
774 const snapshot = structuredClone(accounts);
775 const [claude, cursor] = collectLimitPools(accounts, now);
776 expect.soft(claude?.windows.map((row) => row.remainingPercent)).toEqual([40, 1, 70]);
777 expect.soft(cursor?.windows.map((row) => row.remainingPercent)).toEqual([60, 0, 80]);
778 expect(accounts).toEqual(snapshot);
779 });
780
781 it("keeps session columns across rows with opposite reset and usage orders", () => {
782 const accounts = [
783 account("a", [
784 { ...weekly, usedPercent: 80, resetsAt: "2026-09-05T12:00:00.000Z" },
785 { ...window, usedPercent: 10, resetsAt: "2026-09-03T15:00:00.000Z" },
786 ]),
787 account("b", [
788 { ...weekly, usedPercent: 20, resetsAt: "2026-09-06T12:00:00.000Z" },
789 { ...window, usedPercent: 90, resetsAt: "2026-09-03T13:00:00.000Z" },
790 ]),
791 ];
792 const [pool] = collectLimitPools(accounts, now);
793 expect(pool!.accounts.map((account) => account.key)).toEqual(["b", "a"]);
794 expect(keys(pool!)).toEqual([
795 ["b", "a"],
796 ["b", "a"],
797 ]);
798 expect(pool!.windows[1]!.resets.map((reset) => reset.member.account.key)).toEqual(["a", "b"]);
799 expect(pool!.windows[1]!.remainingPercent).toBe(50);
800 expect(keys(collectLimitPools(accounts.toReversed(), now)[0]!)).toEqual(keys(pool!));
801 });
802
803 it.each([undefined, "invalid", "2026-09-03T11:30:00.000Z"])(
804 "keeps blocked sessions empty without predicting a refill from a missing or stale clock (%s)",
805 (resetsAt) => {
806 const [pool] = collectLimitPools(
807 [
808 account("session-clock", [
809 { ...window, resetsAt },
810 { ...weekly, usedPercent: 100 },
811 ]),
812 account("weekly-clock", [window, { ...weekly, usedPercent: 100, resetsAt }]),
813 ],
814 now,
815 );
816 expect(pool!.windows[0]).toMatchObject({ remainingPercent: 0, pace: null, resets: [] });
817 expect(pool!.windows[0]!.columns.map((column) => column.window?.resetsAt)).toEqual([
818 undefined,
819 undefined,
820 ]);
821 },
822 );
823
824 it("orders by usable session refill and clears suppression after a fresh weekly reading", () => {
825 const blocked = account("blocked", [
826 { ...window, resetsAt: "2026-09-03T13:00:00.000Z" },
827 { ...weekly, usedPercent: 100, resetsAt: "2026-09-03T15:00:00.000Z" },
828 ]);
829 const available = account("available", [window]);
830 const [before] = collectLimitPools([blocked, available], now);
831 expect(before!.accounts.map((account) => account.key)).toEqual(["available", "blocked"]);
832 expect(before!.windows[0]!.remainingPercent).toBe(30);
833 const refreshed = {
834 ...blocked,
835 limits: {
836 checkedAt: "2026-09-03T12:00:00.000Z",
837 windows: [blocked.limits.windows[0]!, { ...weekly, usedPercent: 10 }],
838 },
839 };
840 const [after] = collectLimitPools([refreshed, available], now);
841 expect(after!.accounts.map((account) => account.key)).toEqual(["blocked", "available"]);
842 expect(after!.windows[0]!.remainingPercent).toBe(60);
843 expect(after!.windows[0]!.resets[0]).toMatchObject({
844 at: Date.parse("2026-09-03T13:00:00.000Z"),
845 restoresPercent: 20,
846 });
847 });
848
849 it("preserves gaps without counting missing windows toward pooled quota", () => {
850 const [pool] = collectLimitPools(
851 [
852 account("a", [window]),
853 account("b", [
854 { ...window, resetsAt: "2026-09-03T15:00:00.000Z" },
855 { ...weekly, usedPercent: 80 },
856 ]),
857 account("c", [weekly]),
858 ],
859 now,
860 );
861 expect(keys(pool!)).toEqual([
862 ["a", "b", null],
863 [null, "b", "c"],
864 ]);
865 expect(pool!.windows[1]!.members.map((member) => member.account.key)).toEqual(["b", "c"]);
866 expect(pool!.windows[1]!.remainingPercent).toBe(40);
867 expect(pool!.windows[1]!.resets.map((reset) => reset.restoresPercent)).toEqual([40, 20]);
868 });
869
870 it("falls back to weekly resets when no account reports a session", () => {
871 const [pool] = collectLimitPools(
872 [
873 account("a", [{ ...weekly, resetsAt: "2026-09-06T12:00:00.000Z" }]),
874 account("b", [{ ...weekly, resetsAt: "2026-09-05T12:00:00.000Z" }]),
875 ],
876 now,
877 );
878 expect(keys(pool!)).toEqual([["b", "a"]]);
879 });
880});
881
882describe("/usage-limits", () => {
883 const limits = { checkedAt: "2026-09-03T11:00:00.000Z", windows: [window] };
884 const selected = provider({
885 usageLimits: limits,
886 auth: { status: "authenticated", email: "same@example.com" },
887 });
888 const sources = [
889 {
890 id: UsageLimitSourceId.make("hub"),
891 kind: "cliproxy" as const,
892 label: "Accounts",
893 checkedAt: limits.checkedAt,
894 accounts: [
895 {
896 id: "duplicate",
897 driver: selected.driver,
898 email: "SAME@example.com",
899 usageLimits: limits,
900 },
901 { id: "oss", driver: selected.driver, plan: "Codex OSS", usageLimits: limits },
902 { id: "other-provider", driver: ProviderDriverKind.make("claude"), usageLimits: limits },
903 ],
904 },
905 ];
906
907 it("uses hub credit balances and redemption targets in the composer, including native duplicates", () => {
908 const hubs = sources.map((source) => ({
909 ...source,
910 accounts: source.accounts.map((account) => ({
911 ...account,
912 usageLimits: {
913 ...account.usageLimits,
914 resetCredits: { availableCount: 2, nextCreditId: `${account.id}-credit` },
915 },
916 })),
917 }));
918 const report = collectProviderUsageLimits(selected.instanceId, [selected], hubs, now);
919 expect(report?.accounts[0]?.limits.resetCredits?.availableCount).toBe(2);
920 expect(report?.accounts[0]?.resetCreditInput).toEqual({
921 sourceId: "hub",
922 accountId: "duplicate",
923 creditId: "duplicate-credit",
924 });
925 expect(report?.accounts.find((account) => account.id === "hub:oss")?.resetCreditInput).toEqual({
926 sourceId: "hub",
927 accountId: "oss",
928 creditId: "oss-credit",
929 });
930 });
931
932 it("gives a hub credit to no native row when its email is signed in to two workspaces", () => {
933 const workspaces = ["ws-a", "ws-b"].map((workspaceId) =>
934 provider({
935 instanceId: ProviderInstanceId.make(workspaceId),
936 usageLimits: limits,
937 auth: { status: "authenticated", email: "same@example.com", workspaceId },
938 }),
939 );
940 const hub = [
941 {
942 ...sources[0]!,
943 accounts: [
944 {
945 id: "duplicate",
946 driver: selected.driver,
947 email: "same@example.com",
948 usageLimits: { ...limits, resetCredits: { availableCount: 2, nextCreditId: "c" } },
949 },
950 ],
951 },
952 ];
953 const report = collectProviderUsageLimits(workspaces[0]!.instanceId, workspaces, hub, now);
954 expect(report?.accounts.map((account) => account.resetCreditInput)).toEqual([
955 { instanceId: "ws-a" },
956 { instanceId: "ws-b" },
957 { sourceId: "hub", accountId: "duplicate", creditId: "c" },
958 ]);
959 });
960
961 it("redeems a native duplicate through the hub even when the native snapshot is fresher", () => {
962 const fresher = provider({
963 usageLimits: {
964 checkedAt: "2026-09-03T11:30:00.000Z",
965 windows: [window],
966 resetCredits: { availableCount: 3, nextCreditId: "native-credit" },
967 },
968 auth: { status: "authenticated", email: "same@example.com" },
969 });
970 const stale = [
971 {
972 id: UsageLimitSourceId.make("hub"),
973 kind: "cliproxy" as const,
974 label: "Accounts",
975 checkedAt: limits.checkedAt,
976 accounts: [
977 {
978 id: "duplicate",
979 driver: fresher.driver,
980 email: "SAME@example.com",
981 usageLimits: {
982 ...limits,
983 resetCredits: { availableCount: 2, nextCreditId: "hub-credit" },
984 },
985 },
986 ],
987 },
988 ];
989 const report = collectProviderUsageLimits(fresher.instanceId, [fresher], stale, now);
990 expect(report?.accounts[0]?.resetCreditInput).toEqual({
991 sourceId: "hub",
992 accountId: "duplicate",
993 creditId: "hub-credit",
994 });
995 expect(report?.accounts[0]?.limits.resetCredits?.availableCount).toBe(3);
996 });
997
998 it("keeps unidentified custom instances separate, filtering by driver", () => {
999 const report = collectProviderUsageLimits(
1000 selected.instanceId,
1001 [
1002 selected,
1003 provider({
1004 instanceId: ProviderInstanceId.make("codex-work"),
1005 displayName: "Work",
1006 usageLimits: { ...limits, resetCredits: { availableCount: 2 } },
1007 }),
1008 provider({
1009 driver: ProviderDriverKind.make("claude"),
1010 instanceId: ProviderInstanceId.make("claude"),
1011 usageLimits: limits,
1012 }),
1013 ],
1014 sources,
1015 now,
1016 );
1017 expect(report?.createdAt).toBe("2026-09-03T12:00:00.000Z");
1018 expect(report?.accounts.map((account) => account.id)).toEqual([
1019 "codex",
1020 "codex-work",
1021 "hub:oss",
1022 ]);
1023 expect(report?.accounts[0]).toMatchObject({
1024 instanceId: selected.instanceId,
1025 email: selected.auth.email,
1026 });
1027 expect(report?.accounts[1]).toMatchObject({
1028 displayName: "Work",
1029 limits: { resetCredits: { availableCount: 2 } },
1030 });
1031 expect(report?.accounts[2]).toMatchObject({
1032 label: "Accounts · oss",
1033 sourceLabel: "CLI Proxy",
1034 plan: "Codex OSS",
1035 });
1036 expect(report?.notices).toEqual([]);
1037 });
1038
1039 it("keeps the freshest usable native duplicate and the freshest native credits in either order", () => {
1040 const failed = provider({
1041 auth: selected.auth,
1042 usageLimits: {
1043 ...limits,
1044 checkedAt: "2026-09-03T11:40:00.000Z",
1045 unavailable: { reason: "probeFailed" },
1046 },
1047 });
1048 const credited = provider({
1049 instanceId: ProviderInstanceId.make("codex-credit"),
1050 auth: selected.auth,
1051 usageLimits: {
1052 checkedAt: "2026-09-03T11:20:00.000Z",
1053 windows: [{ ...window, usedPercent: 50 }],
1054 resetCredits: { availableCount: 2 },
1055 },
1056 });
1057 const staleCredit = provider({
1058 ...credited,
1059 instanceId: ProviderInstanceId.make("codex-stale-credit"),
1060 usageLimits: { ...limits, resetCredits: { availableCount: 3 } },
1061 });
1062 const freshest = provider({
1063 instanceId: ProviderInstanceId.make("codex-fresh"),
1064 auth: selected.auth,
1065 usageLimits: {
1066 checkedAt: "2026-09-03T11:30:00.000Z",
1067 windows: [{ ...window, usedPercent: 55 }],
1068 },
1069 });
1070 const duplicates = [failed, staleCredit, credited, freshest];
1071 for (const providers of [duplicates, duplicates.toReversed()]) {
1072 const report = collectProviderUsageLimits(failed.instanceId, providers, sources, now);
1073 expect(report?.accounts.map((account) => account.id)).toEqual(["codex-fresh", "hub:oss"]);
1074 expect(report?.accounts[0]).toMatchObject({
1075 limits: {
1076 checkedAt: "2026-09-03T11:30:00.000Z",
1077 windows: [{ usedPercent: 55 }],
1078 resetCredits: { availableCount: 2 },
1079 },
1080 resetCreditInput: { instanceId: "codex-credit" },
1081 });
1082 expect(report?.accounts[0]?.limits.unavailable).toBeUndefined();
1083 }
1084 });
1085
1086 it("merges native workspace duplicates only while the workspace evidence is unambiguous", () => {
1087 const known = provider({
1088 ...selected,
1089 instanceId: ProviderInstanceId.make("workspace-a"),
1090 auth: { ...selected.auth, workspaceId: "ws-a" },
1091 });
1092 const fresh = provider({
1093 ...known,
1094 instanceId: ProviderInstanceId.make("workspace-a-fresh"),
1095 usageLimits: { ...limits, checkedAt: "2026-09-03T11:30:00.000Z" },
1096 });
1097 const natives = [known, fresh, selected];
1098 expect(
1099 collectProviderUsageLimits(selected.instanceId, natives, [], now)?.accounts.map(
1100 (account) => account.id,
1101 ),
1102 ).toEqual(["workspace-a-fresh"]);
1103
1104 const unreadable = provider({
1105 instanceId: ProviderInstanceId.make("workspace-b"),
1106 auth: { ...selected.auth, workspaceId: "ws-b" },
1107 });
1108 expect(
1109 collectProviderUsageLimits(
1110 selected.instanceId,
1111 [...natives, unreadable],
1112 [],
1113 now,
1114 )?.accounts.map((account) => account.id),
1115 ).toEqual(["workspace-a-fresh", "codex"]);
1116 expect(
1117 collectProviderUsageLimits(
1118 selected.instanceId,
1119 [...natives, { ...unreadable, usageLimits: limits }],
1120 [],
1121 now,
1122 )?.accounts.map((account) => account.id),
1123 ).toEqual(["workspace-a-fresh", "codex", "workspace-b"]);
1124 });
1125
1126 it("supports a source-only provider and keeps duplicates when the native probe failed", () => {
1127 expect(
1128 collectProviderUsageLimits(selected.instanceId, [provider({})], sources, now)?.accounts.map(
1129 (account) => account.id,
1130 ),
1131 ).toEqual(["hub:duplicate", "hub:oss"]);
1132 const failed = provider({ usageLimits: { ...limits, unavailable: { reason: "probeFailed" } } });
1133 expect(
1134 collectProviderUsageLimits(selected.instanceId, [failed], sources, now)?.accounts.map(
1135 (account) => account.id,
1136 ),
1137 ).toEqual(["codex", "hub:duplicate", "hub:oss"]);
1138 expect(collectProviderUsageLimits(selected.instanceId, [provider({})], [], now)).toBeNull();
1139 expect(
1140 collectProviderUsageLimits(
1141 selected.instanceId,
1142 [provider({ enabled: false, usageLimits: limits })],
1143 [],
1144 now,
1145 ),
1146 ).toBeNull();
1147 });
1148
1149 it("surfaces source errors only for sources that carry the selected driver", () => {
1150 const failing = { ...sources[0]!, error: "token expired" };
1151 expect(
1152 collectProviderUsageLimits(selected.instanceId, [selected], [failing], now)?.notices,
1153 ).toEqual(["Accounts: token expired"]);
1154 const claudeOnly = { ...failing, accounts: failing.accounts.slice(2) };
1155 expect(
1156 collectProviderUsageLimits(selected.instanceId, [selected], [claudeOnly], now)?.notices,
1157 ).toEqual([]);
1158 const unreadable = { ...failing, accounts: [] };
1159 expect(
1160 collectProviderUsageLimits(selected.instanceId, [selected], [unreadable], now)?.notices,
1161 ).toEqual(["Accounts: token expired"]);
1162 const sourceOnly = collectProviderUsageLimits(
1163 selected.instanceId,
1164 [provider({})],
1165 [unreadable],
1166 now,
1167 );
1168 expect(sourceOnly?.accounts).toEqual([]);
1169 expect(sourceOnly?.notices).toEqual(["Accounts: token expired"]);
1170 });
1171
1172 it("advertises global and workspace commands only for providers present in Limits", () => {
1173 const withWorkspace = provider({
1174 workspaceSnapshots: [
1175 { cwd: "/tmp/project", checkedAt: limits.checkedAt, slashCommands: [], skills: [] },
1176 ],
1177 });
1178 const [supported] = withUsageLimitsCommands([withWorkspace], sources);
1179 expect(supported?.slashCommands.map((command) => command.name)).toEqual(["usage-limits"]);
1180 expect(
1181 supported?.workspaceSnapshots?.[0]?.slashCommands.map((command) => command.name),
1182 ).toEqual(["usage-limits"]);
1183 expect(withUsageLimitsCommands([withWorkspace], [])[0]?.slashCommands).toEqual([]);
1184 const ownCommand = provider({
1185 slashCommands: [{ name: "usage-limits", description: "Provider's own" }],
1186 });
1187 expect(withUsageLimitsCommands([ownCommand], [])[0]?.slashCommands).toEqual([
1188 { name: "usage-limits", description: "Provider's own" },
1189 ]);
1190 const unreadable = { ...sources[0]!, accounts: [], error: "token expired" };
1191 expect(
1192 withUsageLimitsCommands([withWorkspace], [unreadable])[0]?.slashCommands.map(
1193 (command) => command.name,
1194 ),
1195 ).toEqual(["usage-limits"]);
1196 expect(
1197 withUsageLimitsCommands([selected], [])[0]?.slashCommands.map((command) => command.name),
1198 ).toEqual(["usage-limits"]);
1199 });
1200});
1201
1202describe("sameUsageLimitCommandCoverage", () => {
1203 const codexAccount = {
1204 id: "a",
1205 driver: ProviderDriverKind.make("codex"),
1206 usageLimits: { checkedAt: "2026-09-03T11:00:00.000Z", windows: [] },
1207 };
1208 const base = {
1209 id: UsageLimitSourceId.make("hub"),
1210 kind: "cliproxy" as const,
1211 label: "Accounts",
1212 checkedAt: "2026-09-03T11:00:00.000Z",
1213 };
1214 it("ignores quota movement but not the drivers offered the command", () => {
1215 const withCodex = [{ ...base, accounts: [codexAccount] }];
1216 const withCodexLater = [
1217 {
1218 ...base,
1219 accounts: [
1220 {
1221 ...codexAccount,
1222 usageLimits: { ...codexAccount.usageLimits, checkedAt: "2026-09-03T12:00:00.000Z" },
1223 },
1224 ],
1225 },
1226 ];
1227 expect(sameUsageLimitCommandCoverage(withCodex, withCodexLater)).toBe(true);
1228 expect(sameUsageLimitCommandCoverage(withCodex, [{ ...base, accounts: [] }])).toBe(false);
1229 });
1230 it("treats a failed read as a change in coverage, in both directions", () => {
1231 const empty = [{ ...base, accounts: [] }];
1232 const failed = [{ ...base, accounts: [], error: "token expired" }];
1233 expect(sameUsageLimitCommandCoverage(empty, failed)).toBe(false);
1234 expect(sameUsageLimitCommandCoverage(failed, empty)).toBe(false);
1235 expect(
1236 sameUsageLimitCommandCoverage(failed, [{ ...base, accounts: [], error: "still down" }]),
1237 ).toBe(true);
1238 });
1239});
1240
1241describe("external usage settings", () => {
1242 it("deduplicates destinations across accounts and environments without inventing quota pools", () => {
1243 const managed = provider({
1244 usageLimits: {
1245 checkedAt: "2026-09-03T11:00:00.000Z",
1246 windows: [],
1247 unavailable: { reason: "unsupported", message: "Track usage in ChatGPT." },
1248 externalUsage: { label: "ChatGPT usage", url: "https://chatgpt.com/#settings/Usage" },
1249 },
1250 });
1251 const presentations = new Map([
1252 [
1253 EnvironmentId.make("a"),
1254 {
1255 entry: { target: { label: "A" } },
1256 serverConfig: {
1257 providers: [managed, { ...managed, instanceId: ProviderInstanceId.make("personal") }],
1258 },
1259 },
1260 ],
1261 [
1262 EnvironmentId.make("b"),
1263 { entry: { target: { label: "B" } }, serverConfig: { providers: [managed] } },
1264 ],
1265 ]);
1266 expect(collectExternalUsageLinks(presentations)).toEqual([
1267 {
1268 ...managed.usageLimits!.externalUsage,
1269 message: "Track usage in ChatGPT.",
1270 accounts: [`${managed.instanceId} on A`, "personal on A", `${managed.instanceId} on B`],
1271 },
1272 ]);
1273 expect(collectLimitAccounts(presentations)).toEqual([]);
1274 expect(collectLimitNotices(presentations)).toEqual([]);
1275 });
1276});
1277
1278describe("ChatGPT sharing presentation", () => {
1279 it("requires verified sharing metadata rather than the Codex driver or login type", () => {
1280 const codex = provider({ auth: { status: "authenticated", type: "chatgpt" } });
1281 expect(usesChatGptSharing(codex)).toBe(false);
1282 expect(
1283 usesChatGptSharing({ ...codex, auth: { ...codex.auth, subscriptionSharing: true } }),
1284 ).toBe(true);
1285 expect(
1286 usesChatGptSharing({
1287 ...codex,
1288 auth: { status: "unauthenticated", subscriptionSharing: true },
1289 }),
1290 ).toBe(false);
1291 });
1292});