@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 263 lines 8.49 KB
Raw
1 import {
2 EnvironmentId,
3 ProviderDriverKind,
4 ProviderInstanceId,
5 UsageLimitSourceId,
6 type ServerProvider,
7 } from "@t3tools/contracts";
8 import { describe, expect, it, vi } from "vite-plus/test";
9 import {
10 buildSubscriptionUsageSnapshot,
11 createWidgetRefresher,
12 WIDGET_REFRESH_INTERVAL,
13 } from "./subscriptionUsageSnapshot";
14
15 const checkedAt = "2026-09-05T12:00:00.000Z";
16 const now = Date.parse(checkedAt);
17 const 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;
24 const limits = { checkedAt, windows: [window] };
25 const deepLink = "t3code-dev://settings/usage?tab=limits";
26 function 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 }
43 function 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
52 describe("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("uses upstream deduplication for a native account also present in a proxy hub", () => {
118 const input = new Map([
119 [
120 EnvironmentId.make("env"),
121 {
122 entry: { target: { label: "Remote" } },
123 serverConfig: {
124 providers: [provider()],
125 usageLimitSources: [
126 {
127 id: UsageLimitSourceId.make("hub"),
128 kind: "cliproxy" as const,
129 label: "Hub",
130 checkedAt,
131 accounts: [
132 {
133 id: "account",
134 driver: ProviderDriverKind.make("codex"),
135 email: " PRIVATE@example.com ",
136 usageLimits: limits,
137 },
138 ],
139 },
140 ],
141 },
142 },
143 ],
144 ]);
145 expect(buildSubscriptionUsageSnapshot(input, deepLink).providers[0]?.detail).toBe(
146 "Subscription remaining",
147 );
148 input.get(EnvironmentId.make("env"))!.serverConfig.providers = [];
149 const snapshot = buildSubscriptionUsageSnapshot(input, deepLink);
150 expect(snapshot.providers[0]?.name).toBe("Codex");
151 expect(JSON.stringify(snapshot)).not.toContain("example.com");
152 });
153 it("bounds OS storage and puts the most constrained windows first", () => {
154 const windows = Array.from({ length: 20 }, (_, index) => ({
155 ...window,
156 id: `${index}`,
157 usedPercent: index * 5,
158 }));
159 const snapshot = buildSubscriptionUsageSnapshot(
160 presentations([provider({ usageLimits: { checkedAt, windows } })]),
161 deepLink,
162 );
163 expect(snapshot.providers[0]?.windows).toHaveLength(6);
164 expect(snapshot.providers[0]?.totalWindows).toBe(20);
165 expect(snapshot.providers[0]?.windows[0]?.remaining).toBe(5);
166 });
167 it("uses the freshest copy of an account across environments before pooling", () => {
168 const input = presentations();
169 input.set(EnvironmentId.make("other"), {
170 entry: { target: { label: "Other" } },
171 serverConfig: {
172 providers: [
173 provider({
174 usageLimits: {
175 checkedAt: new Date(now + 60_000).toISOString(),
176 windows: [{ ...window, usedPercent: 80 }],
177 },
178 }),
179 ],
180 },
181 });
182 const snapshot = buildSubscriptionUsageSnapshot(input, deepLink);
183 expect(snapshot.providers[0]?.detail).toBe("Subscription remaining");
184 expect(snapshot.providers[0]?.windows[0]?.remaining).toBe(20);
185 });
186 });
187
188 describe("subscription widget expiry", () => {
189 const maxAgeDeadline = now + 15 * 60_000;
190 function single(resetsAt: string) {
191 return buildSubscriptionUsageSnapshot(
192 presentations([provider({ usageLimits: { checkedAt, windows: [{ ...window, resetsAt }] } })]),
193 deepLink,
194 ).providers[0];
195 }
196
197 it.each(["2026-09-05T11:50:00.000Z", checkedAt])(
198 "keeps usage whose reset at %s already happened when observed",
199 (resetsAt) => {
200 expect(single(resetsAt)).toMatchObject({
201 detail: "Subscription remaining",
202 expiresAt: maxAgeDeadline,
203 windows: [{ remaining: 60, reset: expect.stringMatching(/^Reset /) }],
204 });
205 },
206 );
207
208 it.each([
209 { resetAccount: 1, expiresAt: maxAgeDeadline, label: /^Reset / },
210 { resetAccount: 0, expiresAt: now + 2 * 60_000, label: /^Next reset / },
211 ])(
212 "compares a pooled reset with its own account's observation (account $resetAccount)",
213 ({ resetAccount, expiresAt, label }) => {
214 // Account 0 was observed at 12:00, account 1 at 12:05; the pooled reset is at 12:02.
215 const snapshot = buildSubscriptionUsageSnapshot(
216 presentations(
217 [checkedAt, "2026-09-05T12:05:00.000Z"].map((accountCheckedAt, index) =>
218 provider({
219 instanceId: ProviderInstanceId.make(`codex-${index}`),
220 auth: { status: "authenticated", email: `account-${index}@example.com` },
221 usageLimits: {
222 checkedAt: accountCheckedAt,
223 windows: [
224 {
225 ...window,
226 resetsAt:
227 index === resetAccount
228 ? "2026-09-05T12:02:00.000Z"
229 : "2026-09-05T13:00:00.000Z",
230 },
231 ],
232 },
233 }),
234 ),
235 ),
236 deepLink,
237 );
238 expect(snapshot.providers[0]).toMatchObject({
239 detail: "2 accounts · pooled",
240 expiresAt,
241 windows: [{ remaining: 60, reset: expect.stringMatching(label) }],
242 });
243 },
244 );
245 });
246
247 describe("widget refresh probes", () => {
248 it("does not overlap a slow probe even after the refresh interval", async () => {
249 let finish!: () => void;
250 const probe = vi.fn(
251 () =>
252 new Promise<void>((resolve) => {
253 finish = resolve;
254 }),
255 );
256 const refresh = createWidgetRefresher(probe);
257 const first = refresh(["one", "one"], now);
258 await refresh(["one"], now + WIDGET_REFRESH_INTERVAL);
259 expect(probe).toHaveBeenCalledTimes(1);
260 finish();
261 await first;
262 });
263 });