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