Open History to see the last commit
1import {
2 EnvironmentId,
3 ProviderDriverKind,
4 ProviderInstanceId,
5 UsageDay,
6 USAGE_CONTRACT_VERSION,
7 type ServerProvider,
8 type UsageSummary,
9} from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
12import { afterEach, describe, expect, it, vi } from "vite-plus/test";
13
14import type { EnvironmentPresentation } from "../connection/presentation.ts";
15import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
16import {
17 cursorKeychainAccessEnvironments,
18 needsCursorKeychainAccess,
19 refreshUsage,
20 refreshUsageLimits,
21} from "./usage.ts";
22
23const input = {
24 sinceDay: UsageDay.make("2026-09-05"),
25 untilDay: UsageDay.make("2026-09-05"),
26 timeZone: "UTC",
27};
28const pricing = { status: "fresh" as const, source: "test", fetchedAt: null, knownModels: 1 };
29const summary: UsageSummary = {
30 ...input,
31 contractVersion: USAGE_CONTRACT_VERSION,
32 readAt: "2026-09-05T12:00:00Z",
33 buckets: [],
34 sources: [],
35 pricing,
36 scanDurationMs: 1,
37};
38const registries: AtomRegistry.AtomRegistry[] = [];
39afterEach(() => {
40 for (const registry of registries.splice(0)) registry.dispose();
41});
42
43function harness(ids = ["a"]) {
44 const registry = AtomRegistry.make();
45 registries.push(registry);
46 const environments = ids.map((id) => {
47 const environmentId = EnvironmentId.make(id);
48 const rates = Promise.withResolvers<
49 AsyncResult.Success<typeof pricing> | AsyncResult.Failure<never, unknown>
50 >();
51 const scan = Promise.withResolvers<UsageSummary>();
52 const scanStarted = Promise.withResolvers<void>();
53 const presentation = Atom.make({
54 connection: { phase: "connected" },
55 } as EnvironmentPresentation | null);
56 const query = Atom.make(
57 Effect.promise(() => {
58 scanStarted.resolve();
59 return scan.promise;
60 }),
61 );
62 return { environmentId, rates, scan, scanStarted, presentation, query };
63 });
64 function get(environmentId: EnvironmentId) {
65 const environment = environments.find((entry) => entry.environmentId === environmentId);
66 if (!environment) throw new Error(`Unknown environment: ${environmentId}`);
67 return environment;
68 }
69 const options = {
70 registry,
71 environmentIds: environments.map((entry) => entry.environmentId),
72 input,
73 server: {
74 usageSummary: ({ environmentId }: { environmentId: EnvironmentId }) =>
75 get(environmentId).query,
76 refreshUsageRates: {
77 label: "test:rates",
78 run: (
79 _registry: AtomRegistry.AtomRegistry,
80 { environmentId }: { environmentId: EnvironmentId },
81 ) => get(environmentId).rates.promise,
82 },
83 },
84 presentations: {
85 presentationAtom: (environmentId: EnvironmentId) => get(environmentId).presentation,
86 },
87 } satisfies Parameters<typeof refreshUsage>[0];
88 return { registry, environments, refresh: () => refreshUsage(options) };
89}
90
91describe("manual usage refresh", () => {
92 it.each(["success", "failure"])("waits for the rescan after a pricing %s", async (result) => {
93 const {
94 environments: [environment],
95 refresh,
96 } = harness();
97 const entry = environment!;
98 let finished = false;
99 const refreshing = refresh().then(() => {
100 finished = true;
101 });
102 expect(finished).toBe(false);
103 entry.rates.resolve(
104 result === "success"
105 ? AsyncResult.success(pricing)
106 : AsyncResult.fail(new Error("Pricing offline")),
107 );
108 await entry.scanStarted.promise;
109 expect(finished).toBe(false);
110 entry.scan.resolve(summary);
111 await refreshing;
112 expect(finished).toBe(true);
113 });
114
115 it("settles when an environment disconnects during the rescan", async () => {
116 const {
117 registry,
118 environments: [environment],
119 refresh,
120 } = harness();
121 const entry = environment!;
122 const refreshing = refresh();
123 entry.rates.resolve(AsyncResult.success(pricing));
124 await entry.scanStarted.promise;
125 registry.set(entry.presentation, null);
126 await refreshing;
127 });
128
129 it("waits for healthy environments without waiting for a recovering environment", async () => {
130 const { registry, environments, refresh } = harness(["healthy", "recovering"]);
131 const [healthy, recovering] = environments;
132 registry.set(recovering!.presentation, null);
133 let finished = false;
134 const refreshing = refresh().then(() => {
135 finished = true;
136 });
137 for (const entry of environments) entry.rates.resolve(AsyncResult.success(pricing));
138 await healthy!.scanStarted.promise;
139 expect(finished).toBe(false);
140 healthy!.scan.resolve(summary);
141 await refreshing;
142 expect(finished).toBe(true);
143 });
144
145 it("settles when connected state has no usable RPC session", async () => {
146 const {
147 environments: [environment],
148 refresh,
149 } = harness();
150 const entry = environment!;
151 const refreshing = refresh();
152 entry.rates.resolve(
153 AsyncResult.fail(
154 new EnvironmentRpcUnavailableError({
155 environmentId: entry.environmentId,
156 message: "No session",
157 }),
158 ),
159 );
160 await refreshing;
161 });
162
163 it("replaces a scan that started before pricing was refreshed", async () => {
164 const {
165 registry,
166 environments: [environment],
167 refresh,
168 } = harness();
169 const entry = environment!;
170 let reads = 0;
171 const rescanned = Promise.withResolvers<void>();
172 const query = Atom.make(
173 Effect.promise(() => {
174 reads += 1;
175 if (reads > 1) {
176 rescanned.resolve();
177 return Promise.resolve(summary);
178 }
179 return new Promise<UsageSummary>(() => {});
180 }),
181 );
182 entry.query = query;
183 const unmount = registry.mount(query);
184 expect(reads).toBe(1);
185 const refreshing = refresh();
186 entry.rates.resolve(AsyncResult.success(pricing));
187 await rescanned.promise;
188 await refreshing;
189 expect(reads).toBe(2);
190 unmount();
191 });
192});
193
194describe("limits refresh cooldown", () => {
195 it("runs a fresh check after an in-flight check when settings change", async () => {
196 const id = EnvironmentId.make("limits-after-enable");
197 const oldCheck = Promise.withResolvers<string>();
198 const first = refreshUsageLimits(id, () => oldCheck.promise, true);
199 const newCheck = vi.fn(async () => "new limits");
200 const afterEnable = refreshUsageLimits(id, newCheck, false, true);
201 expect(newCheck).not.toHaveBeenCalled();
202 oldCheck.resolve("old limits");
203 expect(await first).toBe("old limits");
204 expect(await afterEnable).toBe("new limits");
205 expect(newCheck).toHaveBeenCalledTimes(1);
206 });
207
208 it("joins manual calls and gates automatic refreshes after success or failure", async () => {
209 const clock = vi.spyOn(Date, "now").mockReturnValue(1_000);
210 try {
211 for (const fails of [false, true]) {
212 const id = EnvironmentId.make(`limits-${fails}`);
213 const pending = Promise.withResolvers<string>();
214 const refresh = vi.fn(() => pending.promise);
215 const first = refreshUsageLimits(id, refresh, true);
216 await refreshUsageLimits(id, refresh, true);
217 const manual = refreshUsageLimits(id, refresh);
218 const settled = vi.fn();
219 void manual.then(settled, settled);
220 expect(settled).not.toHaveBeenCalled();
221 expect(refresh).toHaveBeenCalledTimes(1);
222 if (fails) {
223 const firstFailure = expect(first).rejects.toThrow("unavailable");
224 const manualFailure = expect(manual).rejects.toThrow("unavailable");
225 pending.reject(new Error("unavailable"));
226 await Promise.all([firstFailure, manualFailure]);
227 } else {
228 pending.resolve("quota");
229 expect(await first).toBe("quota");
230 expect(await manual).toBe("quota");
231 }
232 expect(settled).toHaveBeenCalledTimes(1);
233 const next = vi.fn(async () => undefined);
234 clock.mockReturnValue(300_999);
235 await refreshUsageLimits(id, next, true);
236 expect(next).not.toHaveBeenCalled();
237 clock.mockReturnValue(301_000);
238 await refreshUsageLimits(id, next, true);
239 expect(next).toHaveBeenCalledTimes(1);
240 await refreshUsageLimits(id, next);
241 expect(next).toHaveBeenCalledTimes(2);
242 clock.mockReturnValue(1_000);
243 }
244 } finally {
245 clock.mockRestore();
246 }
247 });
248});
249
250describe("needsCursorKeychainAccess", () => {
251 const cursorPrompt: UsageSummary = {
252 ...summary,
253 sources: [
254 {
255 fingerprint: {
256 hostId: "host",
257 provider: "cursor",
258 resolvedHomePath: "/Users/me/.cursor/auth.json",
259 volumeId: "volume",
260 },
261 status: "ok",
262 scannedFiles: 0,
263 skippedFiles: 0,
264 malformedRecords: 0,
265 distinctSessions: 0,
266 message: "Cursor account usage is off on this environment.",
267 action: "enableCursorKeychain",
268 },
269 ],
270 };
271 const cursor = (status: ServerProvider["status"]): ServerProvider => ({
272 instanceId: ProviderInstanceId.make("cursor"),
273 driver: ProviderDriverKind.make("cursor"),
274 enabled: status !== "disabled",
275 installed: status === "ready",
276 version: null,
277 status,
278 auth: { status: "unknown" },
279 checkedAt: "2026-09-05T12:00:00.000Z",
280 models: [],
281 slashCommands: [],
282 skills: [],
283 });
284
285 it("offers access only when Cursor is ready on that environment", () => {
286 expect(needsCursorKeychainAccess(cursorPrompt, [cursor("ready")])).toBe(true);
287 expect(needsCursorKeychainAccess(cursorPrompt, [cursor("error")])).toBe(false);
288 expect(needsCursorKeychainAccess(cursorPrompt, [cursor("disabled")])).toBe(false);
289 expect(needsCursorKeychainAccess(cursorPrompt, [])).toBe(false);
290 expect(needsCursorKeychainAccess(cursorPrompt, null)).toBe(false);
291 expect(needsCursorKeychainAccess(summary, [cursor("ready")])).toBe(false);
292 });
293
294 it("stops offering access once any environment reads the Cursor account", () => {
295 const off = { summary: cursorPrompt, needsCursorKeychainAccess: true };
296 const account: UsageSummary = {
297 ...summary,
298 sources: [
299 {
300 fingerprint: {
301 hostId: "cursor.com",
302 provider: "cursor",
303 resolvedHomePath: "cursor-account:abc",
304 volumeId: "abc",
305 },
306 status: "ok",
307 scannedFiles: 1,
308 skippedFiles: 0,
309 malformedRecords: 0,
310 distinctSessions: 1,
311 message: null,
312 },
313 ],
314 };
315 expect(cursorKeychainAccessEnvironments([off, off])).toEqual([off, off]);
316 expect(
317 cursorKeychainAccessEnvironments([
318 off,
319 { summary: account, needsCursorKeychainAccess: false },
320 ]),
321 ).toEqual([]);
322 });
323});