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

subscriptionUsageSnapshot.test.ts

257 lines9.0 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 {
10 buildSubscriptionUsageSnapshot,
11 createWidgetRefresher,
12 WIDGET_REFRESH_INTERVAL,
13 subscriptionUsageTimeline,
14} from "./subscriptionUsageSnapshot";
15​
16const checkedAt = "2026-09-05T12:00:00.000Z";
17const now = Date.parse(checkedAt);
18const window = {
19 id: "session",
20 kind: "session",
21 label: "5 hours",
22 usedPercent: 40,
23 resetsAt: "2026-09-05T12:10:00.000Z",
24} as const;
25const limits = { checkedAt, windows: [window] };
26const deepLink = "t3code-dev://settings/usage?tab=limits";
27function provider(overrides: Partial<ServerProvider> = {}): ServerProvider {
28 return {
29 instanceId: ProviderInstanceId.make("codex"),
30 driver: ProviderDriverKind.make("codex"),
31 enabled: true,
32 installed: true,
33 version: null,
34 status: "ready",
35 auth: { status: "authenticated", email: "private@example.com" },
36 checkedAt,
37 models: [],
38 slashCommands: [],
39 skills: [],
40 usageLimits: limits,
41 ...overrides,
42 };
44function presentations(providers: readonly ServerProvider[] = [provider()]) {
45 return new Map([
46 [
47 EnvironmentId.make("env"),
48 { entry: { target: { label: "Remote" } }, serverConfig: { providers } },
49 ],
50 ]);
52​
53describe("subscription widget snapshots", () => {
54 it("uses provider data and its observation time without exposing account emails", () => {
55 const snapshot = buildSubscriptionUsageSnapshot(
56 presentations([provider({ displayName: "private@example.com" })]),
57 deepLink,
58 );
59 expect(snapshot.checkedAt).toBe(now);
60 expect(snapshot.providers[0]).toMatchObject({
61 name: "Codex",
62 windows: [{ remaining: 60 }],
63 expiresAt: now + 10 * 60_000,
64 });
65 expect(snapshot.url).toBe(deepLink);
66 expect(JSON.stringify(snapshot)).not.toContain("private@example.com");
67 });
68 it("clears data after removing environments and hides disabled providers", () => {
69 expect(
70 buildSubscriptionUsageSnapshot(new Map(), deepLink).providers.every(
71 (p) => p.windows.length === 0,
72 ),
73 ).toBe(true);
74 expect(
75 buildSubscriptionUsageSnapshot(
76 presentations([provider({ enabled: false })]),
77 deepLink,
78 ).providers.every((p) => p.windows.length === 0),
79 ).toBe(true);
80 });
81 it("uses upstream deduplication for a native account also present in a proxy hub", () => {
82 const input = new Map([
83 [
84 EnvironmentId.make("env"),
85 {
86 entry: { target: { label: "Remote" } },
87 serverConfig: {
88 providers: [provider()],
89 usageLimitSources: [
90 {
91 id: UsageLimitSourceId.make("hub"),
92 kind: "cliproxy" as const,
93 label: "Hub",
94 checkedAt,
95 accounts: [
96 {
97 id: "account",
98 driver: ProviderDriverKind.make("codex"),
99 email: " PRIVATE@example.com ",
100 usageLimits: limits,
101 },
102 ],
103 },
104 ],
105 },
106 },
107 ],
108 ]);
109 expect(buildSubscriptionUsageSnapshot(input, deepLink).providers[0]?.detail).toBe(
110 "Subscription remaining",
111 );
112 input.get(EnvironmentId.make("env"))!.serverConfig.providers = [];
113 const snapshot = buildSubscriptionUsageSnapshot(input, deepLink);
114 expect(snapshot.providers[0]?.name).toBe("Codex");
115 expect(JSON.stringify(snapshot)).not.toContain("example.com");
116 });
117 it("keeps unavailable quotas distinct from zero usage and omits provider error messages", () => {
118 const snapshot = buildSubscriptionUsageSnapshot(
119 presentations([
120 provider({
121 usageLimits: {
122 ...limits,
123 unavailable: { reason: "probeFailed", message: "token secret" },
124 },
125 }),
126 ]),
127 deepLink,
128 );
129 expect(snapshot.providers[0]?.windows).toEqual([]);
130 expect(JSON.stringify(snapshot)).not.toContain("token secret");
131 expect(
132 buildSubscriptionUsageSnapshot(
133 presentations([
134 provider({ usageLimits: { checkedAt, windows: [{ ...window, usedPercent: 0 }] } }),
135 ]),
136 deepLink,
137 ).providers[0]?.windows[0]?.remaining,
138 ).toBe(100);
139 });
140 it("bounds OS storage and puts the most constrained windows first", () => {
141 const windows = Array.from({ length: 20 }, (_, index) => ({
142 ...window,
143 id: `${index}`,
144 usedPercent: index * 5,
145 }));
146 const snapshot = buildSubscriptionUsageSnapshot(
147 presentations([provider({ usageLimits: { checkedAt, windows } })]),
148 deepLink,
149 );
150 expect(snapshot.providers[0]?.windows).toHaveLength(6);
151 expect(snapshot.providers[0]?.totalWindows).toBe(20);
152 expect(snapshot.providers[0]?.windows[0]?.remaining).toBe(5);
153 });
154 it("marks unknown or distant reset times stale after fifteen minutes", () => {
155 const snapshot = buildSubscriptionUsageSnapshot(
156 presentations([
157 provider({ usageLimits: { checkedAt, windows: [{ ...window, resetsAt: undefined }] } }),
158 ]),
159 deepLink,
160 );
161 expect(snapshot.providers[0]?.expiresAt).toBe(now + 15 * 60_000);
162 expect(snapshot.providers[0]?.windows[0]?.reset).toBe("Reset time unavailable");
163 });
164 it("schedules a reset boundary without inventing a zero quota", () => {
165 const snapshot = buildSubscriptionUsageSnapshot(presentations(), deepLink);
166 const timeline = subscriptionUsageTimeline(snapshot, now);
167 expect(timeline.map((entry) => entry.date.getTime())).toEqual([now, now + 10 * 60_000]);
168 expect(timeline[1]?.props.providers[0]?.windows).toEqual([]);
169 expect(subscriptionUsageTimeline(snapshot, now + 60 * 60_000)).toHaveLength(1);
170 });
171 it("expires providers independently without inventing a refill", () => {
172 const snapshot = buildSubscriptionUsageSnapshot(
173 presentations([
174 provider(),
175 provider({
176 instanceId: ProviderInstanceId.make("claude"),
177 driver: ProviderDriverKind.make("claudeAgent"),
178 usageLimits: { checkedAt, windows: [{ ...window, resetsAt: undefined }] },
179 }),
180 ]),
181 deepLink,
182 );
183 const timeline = subscriptionUsageTimeline(snapshot, now);
184 expect(timeline.map((entry) => entry.date.getTime())).toEqual([
185 now,
186 now + 10 * 60_000,
187 now + 15 * 60_000,
188 ]);
189 expect(timeline[1]?.props.providers[0]?.windows).toEqual([]);
190 expect(timeline[1]?.props.providers[1]?.windows[0]?.remaining).toBe(60);
191 expect(timeline[2]?.props.providers.every((provider) => provider.windows.length === 0)).toBe(
192 true,
193 );
194 });
195 it("marks a malformed check time immediately stale without storing null", () => {
196 const snapshot = buildSubscriptionUsageSnapshot(
197 presentations([provider({ usageLimits: { ...limits, checkedAt: "invalid" } })]),
198 deepLink,
199 );
200 expect(snapshot.checkedAt).toBe(0);
201 expect(snapshot.providers[0]).toMatchObject({ expiresAt: 0, windows: [] });
202 expect(subscriptionUsageTimeline(snapshot, now)).toHaveLength(1);
203 expect(JSON.stringify(snapshot)).not.toContain("null");
204 });
205 it("uses the freshest copy of an account across environments before pooling", () => {
206 const input = presentations();
207 input.set(EnvironmentId.make("other"), {
208 entry: { target: { label: "Other" } },
209 serverConfig: {
210 providers: [
211 provider({
212 usageLimits: {
213 checkedAt: new Date(now + 60_000).toISOString(),
214 windows: [{ ...window, usedPercent: 80 }],
215 },
216 }),
217 ],
218 },
219 });
220 const snapshot = buildSubscriptionUsageSnapshot(input, deepLink);
221 expect(snapshot.providers[0]?.detail).toBe("Subscription remaining");
222 expect(snapshot.providers[0]?.windows[0]?.remaining).toBe(20);
223 });
224});
225​
226describe("widget refresh probes", () => {
227 it("throttles each connected environment independently and retries failures", async () => {
228 const probe = vi
229 .fn<(id: string) => Promise<void>>()
230 .mockRejectedValueOnce(new Error("offline"))
231 .mockResolvedValue(undefined);
232 const refresh = createWidgetRefresher(probe);
233 await refresh([], now);
234 expect(probe).not.toHaveBeenCalled();
235 await refresh(["first"], now);
236 await refresh(["first", "second"], now + 1);
237 expect(probe.mock.calls).toEqual([["first"], ["second"]]);
238 await refresh(["first"], now + WIDGET_REFRESH_INTERVAL);
239 expect(probe.mock.calls).toEqual([["first"], ["second"], ["first"]]);
240 });
241​
242 it("does not overlap a slow probe even after the refresh interval", async () => {
243 let finish!: () => void;
244 const probe = vi.fn(
245 () =>
246 new Promise<void>((resolve) => {
247 finish = resolve;
248 }),
249 );
250 const refresh = createWidgetRefresher(probe);
251 const first = refresh(["one", "one"], now);
252 await refresh(["one"], now + WIDGET_REFRESH_INTERVAL);
253 expect(probe).toHaveBeenCalledTimes(1);
254 finish();
255 await first;
256 });
257});