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

subscriptionUsageSnapshot.test.ts

362 lines13.1 KB

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 { getMobileThemeRuntimeVariables } from "../lib/mobileThemeVariables";
10import { createWidgetTheme } from "./widgetTheme";
11import {
12 type SubscriptionUsageSnapshot,
13 buildSubscriptionUsageSnapshot,
14 createWidgetRefresher,
15 WIDGET_REFRESH_INTERVAL,
16 subscriptionUsageTimeline,
17} from "./subscriptionUsageSnapshot";
18​
19function contrastRatio(first: string, second: string) {
20 const luminance = (color: string) => {
21 if (!/^#[0-9a-f]{6}(?:ff)?$/i.test(color)) throw new Error(`Expected opaque hex: ${color}`);
22 const linear = [1, 3, 5].map((offset) => {
23 const channel = Number.parseInt(color.slice(offset, offset + 2), 16) / 255;
24 return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
25 });
26 return 0.2126 * linear[0]! + 0.7152 * linear[1]! + 0.0722 * linear[2]!;
27 };
28 const a = luminance(first);
29 const b = luminance(second);
30 return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
32​
33const checkedAt = "2026-09-05T12:00:00.000Z";
34const now = Date.parse(checkedAt);
35const window = {
36 id: "session",
37 kind: "session",
38 label: "5 hours",
39 usedPercent: 40,
40 resetsAt: "2026-09-05T12:10:00.000Z",
41} as const;
42const limits = { checkedAt, windows: [window] };
43const deepLink = "t3code-dev://settings/usage?tab=limits";
44function provider(overrides: Partial<ServerProvider> = {}): ServerProvider {
45 return {
46 instanceId: ProviderInstanceId.make("codex"),
47 driver: ProviderDriverKind.make("codex"),
48 enabled: true,
49 installed: true,
50 version: null,
51 status: "ready",
52 auth: { status: "authenticated", email: "private@example.com" },
53 checkedAt,
54 models: [],
55 slashCommands: [],
56 skills: [],
57 usageLimits: limits,
58 ...overrides,
59 };
61function presentations(providers: readonly ServerProvider[] = [provider()]) {
62 return new Map([
63 [
64 EnvironmentId.make("env"),
65 { entry: { target: { label: "Remote" } }, serverConfig: { providers } },
66 ],
67 ]);
69​
70describe("subscription widget snapshots", () => {
71 it("uses provider data and its observation time without exposing account emails", () => {
72 const snapshot = buildSubscriptionUsageSnapshot(
73 presentations([provider({ displayName: "private@example.com" })]),
74 deepLink,
75 );
76 expect(snapshot.checkedAt).toBe(now);
77 expect(snapshot.providers[0]).toMatchObject({
78 name: "Codex",
79 windows: [{ remaining: 60 }],
80 expiresAt: now + 10 * 60_000,
81 });
82 expect(snapshot.url).toBe(deepLink);
83 expect(JSON.stringify(snapshot)).not.toContain("private@example.com");
84 });
85 it("clears data after removing environments", () => {
86 expect(buildSubscriptionUsageSnapshot(new Map(), deepLink).providers).toEqual([]);
87 });
88 it.each<{ name: string; overrides: Partial<ServerProvider> }>([
89 { name: "disabled", overrides: { enabled: false } },
90 {
91 name: "missing",
92 overrides: { installed: false, status: "error", usageLimits: undefined },
93 },
94 {
95 name: "API-key",
96 overrides: {
97 usageLimits: { checkedAt, windows: [], unavailable: { reason: "unsupported" } },
98 },
99 },
100 ])("hides $name providers", ({ overrides }) => {
101 expect(
102 buildSubscriptionUsageSnapshot(presentations([provider(overrides)]), deepLink).providers,
103 ).toEqual([]);
104 });
105 it.each([
106 { name: "Codex", driver: "codex" },
107 { name: "Claude", driver: "claudeAgent" },
108 ])("only shows $name when $name and OpenCode are configured", ({ name, driver }) => {
109 const snapshot = buildSubscriptionUsageSnapshot(
110 presentations([
111 provider({
112 instanceId: ProviderInstanceId.make(driver),
113 driver: ProviderDriverKind.make(driver),
114 }),
115 provider({
116 instanceId: ProviderInstanceId.make("opencode"),
117 driver: ProviderDriverKind.make("opencode"),
118 usageLimits: undefined,
119 }),
120 ]),
121 deepLink,
122 );
123 expect(snapshot.providers).toHaveLength(1);
124 expect(snapshot.providers[0]).toMatchObject({
125 name,
126 totalWindows: 1,
127 windows: [{ remaining: 60 }],
128 });
129 expect(subscriptionUsageTimeline(snapshot, now + 15 * 60_000)[0]?.props.providers).toEqual([
130 expect.objectContaining({ name, totalWindows: 0, windows: [] }),
131 ]);
132 });
133 it("keeps an enabled provider visible before its first usage read", () => {
134 const snapshot = buildSubscriptionUsageSnapshot(
135 presentations([provider({ usageLimits: undefined })]),
136 deepLink,
137 );
138 expect(snapshot.checkedAt).toBe(0);
139 expect(snapshot.providers).toEqual([
140 { name: "Codex", detail: "No limits available", windows: [], expiresAt: 0, totalWindows: 0 },
141 ]);
142 });
143 it("uses upstream deduplication for a native account also present in a proxy hub", () => {
144 const input = new Map([
145 [
146 EnvironmentId.make("env"),
147 {
148 entry: { target: { label: "Remote" } },
149 serverConfig: {
150 providers: [provider()],
151 usageLimitSources: [
152 {
153 id: UsageLimitSourceId.make("hub"),
154 kind: "cliproxy" as const,
155 label: "Hub",
156 checkedAt,
157 accounts: [
158 {
159 id: "account",
160 driver: ProviderDriverKind.make("codex"),
161 email: " PRIVATE@example.com ",
162 usageLimits: limits,
163 },
164 ],
165 },
166 ],
167 },
168 },
169 ],
170 ]);
171 expect(buildSubscriptionUsageSnapshot(input, deepLink).providers[0]?.detail).toBe(
172 "Subscription remaining",
173 );
174 input.get(EnvironmentId.make("env"))!.serverConfig.providers = [];
175 const snapshot = buildSubscriptionUsageSnapshot(input, deepLink);
176 expect(snapshot.providers[0]?.name).toBe("Codex");
177 expect(JSON.stringify(snapshot)).not.toContain("example.com");
178 });
179 it("keeps unavailable quotas distinct from zero usage and omits provider error messages", () => {
180 const snapshot = buildSubscriptionUsageSnapshot(
181 presentations([
182 provider({
183 usageLimits: {
184 ...limits,
185 unavailable: { reason: "probeFailed", message: "token secret" },
186 },
187 }),
188 ]),
189 deepLink,
190 );
191 expect(snapshot.providers[0]?.windows).toEqual([]);
192 expect(JSON.stringify(snapshot)).not.toContain("token secret");
193 expect(
194 buildSubscriptionUsageSnapshot(
195 presentations([
196 provider({ usageLimits: { checkedAt, windows: [{ ...window, usedPercent: 0 }] } }),
197 ]),
198 deepLink,
199 ).providers[0]?.windows[0]?.remaining,
200 ).toBe(100);
201 });
202 it("bounds OS storage and puts the most constrained windows first", () => {
203 const windows = Array.from({ length: 20 }, (_, index) => ({
204 ...window,
205 id: `${index}`,
206 usedPercent: index * 5,
207 }));
208 const snapshot = buildSubscriptionUsageSnapshot(
209 presentations([provider({ usageLimits: { checkedAt, windows } })]),
210 deepLink,
211 );
212 expect(snapshot.providers[0]?.windows).toHaveLength(6);
213 expect(snapshot.providers[0]?.totalWindows).toBe(20);
214 expect(snapshot.providers[0]?.windows[0]?.remaining).toBe(5);
215 });
216 it("includes every limit for the scrollable Android widget", () => {
217 const windows = Array.from({ length: 20 }, (_, index) => ({
218 ...window,
219 id: `${index}`,
220 usedPercent: index * 5,
221 }));
222 const snapshot = buildSubscriptionUsageSnapshot(
223 presentations([provider({ usageLimits: { checkedAt, windows } })]),
224 deepLink,
225 Infinity,
226 );
227 expect(snapshot.providers[0]?.windows.map((window) => window.remaining)).toEqual(
228 Array.from({ length: 20 }, (_, index) => 5 + index * 5),
229 );
230 });
231 it("marks unknown or distant reset times stale after fifteen minutes", () => {
232 const snapshot = buildSubscriptionUsageSnapshot(
233 presentations([
234 provider({ usageLimits: { checkedAt, windows: [{ ...window, resetsAt: undefined }] } }),
235 ]),
236 deepLink,
237 );
238 expect(snapshot.providers[0]?.expiresAt).toBe(now + 15 * 60_000);
239 expect(snapshot.providers[0]?.windows[0]?.reset).toBe("Reset time unavailable");
240 });
241 it("preserves the saved appearance through a reset without inventing a zero quota", () => {
242 const light = getMobileThemeRuntimeVariables("t3-chat", "light", "ios");
243 const dark = getMobileThemeRuntimeVariables("t3-code", "dark", "ios");
244 const snapshot: SubscriptionUsageSnapshot = JSON.parse(
245 JSON.stringify({
246 ...buildSubscriptionUsageSnapshot(presentations(), deepLink),
247 theme: createWidgetTheme("dark", { light, dark }),
248 }),
249 );
250 const timeline = subscriptionUsageTimeline(snapshot, now);
251 expect(timeline.map((entry) => entry.date.getTime())).toEqual([now, now + 10 * 60_000]);
252 expect(timeline[1]?.props.providers[0]?.windows).toEqual([]);
253 expect(subscriptionUsageTimeline(snapshot, now + 60 * 60_000)).toHaveLength(1);
254 for (const entry of timeline) {
255 expect(JSON.parse(JSON.stringify(entry.props)).theme).toEqual({
256 mode: "dark",
257 light: expect.objectContaining({
258 background: light["--color-card"],
259 foreground: light["--color-foreground"],
260 }),
261 dark: expect.objectContaining({
262 background: dark["--color-card"],
263 foreground: dark["--color-foreground"],
264 }),
265 });
266 }
267 });
268 it("keeps the default Android unfilled track distinguishable from the card", () => {
269 const theme = createWidgetTheme("system", {
270 light: getMobileThemeRuntimeVariables("t3-code", "light", "android"),
271 dark: getMobileThemeRuntimeVariables("t3-code", "dark", "android"),
272 });
273 expect(contrastRatio(theme.dark.track, theme.dark.background)).toBeGreaterThanOrEqual(1.3);
274 expect(contrastRatio(theme.light.track, theme.light.background)).toBeGreaterThanOrEqual(1.3);
275 });
276 it("expires providers independently without inventing a refill", () => {
277 const snapshot = buildSubscriptionUsageSnapshot(
278 presentations([
279 provider(),
280 provider({
281 instanceId: ProviderInstanceId.make("claude"),
282 driver: ProviderDriverKind.make("claudeAgent"),
283 usageLimits: { checkedAt, windows: [{ ...window, resetsAt: undefined }] },
284 }),
285 ]),
286 deepLink,
287 );
288 const timeline = subscriptionUsageTimeline(snapshot, now);
289 expect(timeline.map((entry) => entry.date.getTime())).toEqual([
290 now,
291 now + 10 * 60_000,
292 now + 15 * 60_000,
293 ]);
294 expect(timeline[1]?.props.providers[0]?.windows).toEqual([]);
295 expect(timeline[1]?.props.providers[1]?.windows[0]?.remaining).toBe(60);
296 expect(timeline[2]?.props.providers.every((provider) => provider.windows.length === 0)).toBe(
297 true,
298 );
299 });
300 it("marks a malformed check time immediately stale without storing null", () => {
301 const snapshot = buildSubscriptionUsageSnapshot(
302 presentations([provider({ usageLimits: { ...limits, checkedAt: "invalid" } })]),
303 deepLink,
304 );
305 expect(snapshot.checkedAt).toBe(0);
306 expect(snapshot.providers[0]).toMatchObject({ expiresAt: 0, windows: [] });
307 expect(subscriptionUsageTimeline(snapshot, now)).toHaveLength(1);
308 expect(JSON.stringify(snapshot)).not.toContain("null");
309 });
310 it("uses the freshest copy of an account across environments before pooling", () => {
311 const input = presentations();
312 input.set(EnvironmentId.make("other"), {
313 entry: { target: { label: "Other" } },
314 serverConfig: {
315 providers: [
316 provider({
317 usageLimits: {
318 checkedAt: new Date(now + 60_000).toISOString(),
319 windows: [{ ...window, usedPercent: 80 }],
320 },
321 }),
322 ],
323 },
324 });
325 const snapshot = buildSubscriptionUsageSnapshot(input, deepLink);
326 expect(snapshot.providers[0]?.detail).toBe("Subscription remaining");
327 expect(snapshot.providers[0]?.windows[0]?.remaining).toBe(20);
328 });
329});
330​
331describe("widget refresh probes", () => {
332 it("throttles each connected environment independently and retries failures", async () => {
333 const probe = vi
334 .fn<(id: string) => Promise<void>>()
335 .mockRejectedValueOnce(new Error("offline"))
336 .mockResolvedValue(undefined);
337 const refresh = createWidgetRefresher(probe);
338 await refresh([], now);
339 expect(probe).not.toHaveBeenCalled();
340 await refresh(["first"], now);
341 await refresh(["first", "second"], now + 1);
342 expect(probe.mock.calls).toEqual([["first"], ["second"]]);
343 await refresh(["first"], now + WIDGET_REFRESH_INTERVAL);
344 expect(probe.mock.calls).toEqual([["first"], ["second"], ["first"]]);
345 });
346​
347 it("does not overlap a slow probe even after the refresh interval", async () => {
348 let finish!: () => void;
349 const probe = vi.fn(
350 () =>
351 new Promise<void>((resolve) => {
352 finish = resolve;
353 }),
354 );
355 const refresh = createWidgetRefresher(probe);
356 const first = refresh(["one", "one"], now);
357 await refresh(["one"], now + WIDGET_REFRESH_INTERVAL);
358 expect(probe).toHaveBeenCalledTimes(1);
359 finish();
360 await first;
361 });
362});