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