Open History to see the last commit
1import {
2 EnvironmentId,
3 ProviderDriverKind,
4 ProviderInstanceId,
5 UsageLimitSourceId,
6 type ServerProvider,
7} from "@t3tools/contracts";
8import { describe, expect, it, vi } from "vite-plus/test";
9import {
10 buildSubscriptionUsageSnapshot,
11 createWidgetRefresher,
12 WIDGET_REFRESH_INTERVAL,
13} from "./subscriptionUsageSnapshot";
14
15const checkedAt = "2026-09-05T12:00:00.000Z";
16const now = Date.parse(checkedAt);
17const window = {
18 id: "session",
19 kind: "session",
20 label: "5 hours",
21 usedPercent: 40,
22 resetsAt: "2026-09-05T12:10:00.000Z",
23} as const;
24const limits = { checkedAt, windows: [window] };
25const deepLink = "t3code-dev://settings/usage?tab=limits";
26function provider(overrides: Partial<ServerProvider> = {}): ServerProvider {
27 return {
28 instanceId: ProviderInstanceId.make("codex"),
29 driver: ProviderDriverKind.make("codex"),
30 enabled: true,
31 installed: true,
32 version: null,
33 status: "ready",
34 auth: { status: "authenticated", email: "private@example.com" },
35 checkedAt,
36 models: [],
37 slashCommands: [],
38 skills: [],
39 usageLimits: limits,
40 ...overrides,
41 };
42}
43function presentations(providers: readonly ServerProvider[] = [provider()]) {
44 return new Map([
45 [
46 EnvironmentId.make("env"),
47 { entry: { target: { label: "Remote" } }, serverConfig: { providers } },
48 ],
49 ]);
50}
51
52describe("subscription widget snapshots", () => {
53 it("uses provider data and its observation time without exposing account emails", () => {
54 const snapshot = buildSubscriptionUsageSnapshot(
55 presentations([provider({ displayName: "private@example.com" })]),
56 deepLink,
57 );
58 expect(snapshot.checkedAt).toBe(now);
59 expect(snapshot.providers[0]).toMatchObject({
60 name: "Codex",
61 windows: [{ remaining: 60 }],
62 expiresAt: now + 10 * 60_000,
63 });
64 expect(snapshot.url).toBe(deepLink);
65 expect(JSON.stringify(snapshot)).not.toContain("private@example.com");
66 });
67 it("splits a pooled window by account without exposing emails", () => {
68 const claude = (id: string, overrides: Partial<ServerProvider>) =>
69 provider({
70 instanceId: ProviderInstanceId.make(id),
71 driver: ProviderDriverKind.make("claudeAgent"),
72 auth: { status: "authenticated", email: `${id}@example.com` },
73 ...overrides,
74 });
75 const snapshot = buildSubscriptionUsageSnapshot(
76 presentations([
77 claude("smol", {
78 displayName: "smol",
79 accentColor: "#4c6ef5",
80 usageLimits: {
81 checkedAt,
82 windows: [{ ...window, usedPercent: 29, windowDurationMins: 300 }],
83 },
84 }),
85 claude("relay", {
86 displayName: "relay@example.com",
87 usageLimits: {
88 checkedAt,
89 windows: [{ ...window, id: "seven_day", kind: "weekly", label: "Weekly" }],
90 },
91 }),
92 claude("rex", {
93 usageLimits: {
94 checkedAt,
95 windows: [{ ...window, resetsAt: "2026-09-05T11:50:00.000Z" }],
96 },
97 }),
98 ]),
99 deepLink,
100 );
101 const session = snapshot.providers[0]?.windows.find((w) => w.kind === "session");
102 expect(session?.accounts).toStrictEqual([
103 { name: "RE", remaining: 60, refill: 0 },
104 {
105 name: "smol",
106 color: "#4c6ef5",
107 remaining: 71,
108 refill: 29,
109 resetsAt: Date.parse(window.resetsAt),
110 reset: expect.any(String),
111 durationMs: 300 * 60_000,
112 },
113 { name: "RE2" },
114 ]);
115 expect(JSON.stringify(snapshot)).not.toContain("example.com");
116 });
117 it.each([
118 [
119 ["AB", "AB2", "AB"],
120 ["AB", "AB2", "AB3"],
121 ],
122 [
123 ["AB", "AB", "AB2"],
124 ["AB", "AB3", "AB2"],
125 ],
126 ])("keeps widget account names unique for %j", (names, expected) => {
127 const snapshot = buildSubscriptionUsageSnapshot(
128 presentations(
129 names.map((displayName, index) =>
130 provider({
131 instanceId: ProviderInstanceId.make(`account${index}`),
132 displayName,
133 auth: { status: "authenticated", email: `account${index}@example.com` },
134 usageLimits: {
135 checkedAt,
136 windows: [{ ...window, resetsAt: `2026-09-05T12:1${index}:00.000Z` }],
137 },
138 }),
139 ),
140 ),
141 deepLink,
142 );
143 expect(snapshot.providers[0]?.windows[0]?.accounts?.map((a) => a.name)).toStrictEqual(expected);
144 });
145 it("uses upstream deduplication for a native account also present in a proxy hub", () => {
146 const input = new Map([
147 [
148 EnvironmentId.make("env"),
149 {
150 entry: { target: { label: "Remote" } },
151 serverConfig: {
152 providers: [provider()],
153 usageLimitSources: [
154 {
155 id: UsageLimitSourceId.make("hub"),
156 kind: "cliproxy" as const,
157 label: "Hub",
158 checkedAt,
159 accounts: [
160 {
161 id: "account",
162 driver: ProviderDriverKind.make("codex"),
163 email: " PRIVATE@example.com ",
164 usageLimits: limits,
165 },
166 ],
167 },
168 ],
169 },
170 },
171 ],
172 ]);
173 expect(buildSubscriptionUsageSnapshot(input, deepLink).providers[0]?.detail).toBe(
174 "Subscription remaining",
175 );
176 input.get(EnvironmentId.make("env"))!.serverConfig.providers = [];
177 const snapshot = buildSubscriptionUsageSnapshot(input, deepLink);
178 expect(snapshot.providers[0]?.name).toBe("Codex");
179 expect(JSON.stringify(snapshot)).not.toContain("example.com");
180 });
181 it("bounds OS storage and puts the most constrained windows first", () => {
182 const windows = Array.from({ length: 20 }, (_, index) => ({
183 ...window,
184 id: `${index}`,
185 usedPercent: index * 5,
186 }));
187 const snapshot = buildSubscriptionUsageSnapshot(
188 presentations([provider({ usageLimits: { checkedAt, windows } })]),
189 deepLink,
190 );
191 expect(snapshot.providers[0]?.windows).toHaveLength(6);
192 expect(snapshot.providers[0]?.totalWindows).toBe(20);
193 expect(snapshot.providers[0]?.windows[0]?.remaining).toBe(5);
194 });
195 it("uses the freshest copy of an account across environments before pooling", () => {
196 const input = presentations();
197 input.set(EnvironmentId.make("other"), {
198 entry: { target: { label: "Other" } },
199 serverConfig: {
200 providers: [
201 provider({
202 usageLimits: {
203 checkedAt: new Date(now + 60_000).toISOString(),
204 windows: [{ ...window, usedPercent: 80 }],
205 },
206 }),
207 ],
208 },
209 });
210 const snapshot = buildSubscriptionUsageSnapshot(input, deepLink);
211 expect(snapshot.providers[0]?.detail).toBe("Subscription remaining");
212 expect(snapshot.providers[0]?.windows[0]?.remaining).toBe(20);
213 });
214});
215
216describe("subscription widget expiry", () => {
217 const maxAgeDeadline = now + 15 * 60_000;
218 function single(resetsAt: string) {
219 return buildSubscriptionUsageSnapshot(
220 presentations([provider({ usageLimits: { checkedAt, windows: [{ ...window, resetsAt }] } })]),
221 deepLink,
222 ).providers[0];
223 }
224
225 it.each(["2026-09-05T11:50:00.000Z", checkedAt])(
226 "keeps usage whose reset at %s already happened when observed",
227 (resetsAt) => {
228 expect(single(resetsAt)).toMatchObject({
229 detail: "Subscription remaining",
230 expiresAt: maxAgeDeadline,
231 windows: [{ remaining: 60, reset: expect.stringMatching(/^Reset /) }],
232 });
233 },
234 );
235
236 it.each([
237 { resetAccount: 1, expiresAt: maxAgeDeadline, label: /^Reset / },
238 { resetAccount: 0, expiresAt: now + 2 * 60_000, label: /^Next reset / },
239 ])(
240 "compares a pooled reset with its own account's observation (account $resetAccount)",
241 ({ resetAccount, expiresAt, label }) => {
242 // Account 0 was observed at 12:00, account 1 at 12:05; the pooled reset is at 12:02.
243 const snapshot = buildSubscriptionUsageSnapshot(
244 presentations(
245 [checkedAt, "2026-09-05T12:05:00.000Z"].map((accountCheckedAt, index) =>
246 provider({
247 instanceId: ProviderInstanceId.make(`codex-${index}`),
248 auth: { status: "authenticated", email: `account-${index}@example.com` },
249 usageLimits: {
250 checkedAt: accountCheckedAt,
251 windows: [
252 {
253 ...window,
254 resetsAt:
255 index === resetAccount
256 ? "2026-09-05T12:02:00.000Z"
257 : "2026-09-05T13:00:00.000Z",
258 },
259 ],
260 },
261 }),
262 ),
263 ),
264 deepLink,
265 );
266 expect(snapshot.providers[0]).toMatchObject({
267 detail: "2 accounts · pooled",
268 expiresAt,
269 windows: [{ remaining: 60, reset: expect.stringMatching(label) }],
270 });
271 },
272 );
273});
274
275describe("widget refresh probes", () => {
276 it("does not overlap a slow probe even after the refresh interval", async () => {
277 let finish!: () => void;
278 const probe = vi.fn(
279 () =>
280 new Promise<void>((resolve) => {
281 finish = resolve;
282 }),
283 );
284 const refresh = createWidgetRefresher(probe);
285 const first = refresh(["one", "one"], now);
286 await refresh(["one"], now + WIDGET_REFRESH_INTERVAL);
287 expect(probe).toHaveBeenCalledTimes(1);
288 finish();
289 await first;
290 });
291});