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