Open History to see the last commit
1import {
2 DEFAULT_SERVER_SETTINGS,
3 EnvironmentId,
4 UsageDay,
5 UsageReadError,
6 USAGE_CONTRACT_VERSION,
7 WS_METHODS,
8 type ServerConfig,
9 type ServerConfigStreamEvent,
10 ServerSettings,
11 type UsageSource,
12 type UsageSummary,
13 type UsageSummaryInput,
14} from "@t3tools/contracts";
15import { expect, it } from "@effect/vitest";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Queue from "effect/Queue";
21import * as Result from "effect/Result";
22import * as Schema from "effect/Schema";
23import * as Stream from "effect/Stream";
24import * as SubscriptionRef from "effect/SubscriptionRef";
25import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
26
27import {
28 AVAILABLE_CONNECTION_STATE,
29 PrimaryConnectionTarget,
30 type PreparedConnection,
31 type SupervisorConnectionState,
32} from "../connection/model.ts";
33import type { EnvironmentPresentation } from "../connection/presentation.ts";
34import * as EnvironmentRegistry from "../connection/registry.ts";
35import * as EnvironmentSupervisor from "../connection/supervisor.ts";
36import * as Persistence from "../platform/persistence.ts";
37import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
38import type { RpcSession } from "../rpc/session.ts";
39import { createServerEnvironmentAtoms } from "./server.ts";
40import { refreshUsage } from "./usage.ts";
41
42const TARGET = new PrimaryConnectionTarget({
43 environmentId: EnvironmentId.make("usage-environment"),
44 label: "Usage environment",
45 httpBaseUrl: "https://environment.example.test",
46 wsBaseUrl: "wss://environment.example.test",
47});
48
49const INPUT: UsageSummaryInput = {
50 sinceDay: UsageDay.make("2026-09-01"),
51 untilDay: UsageDay.make("2026-09-04"),
52 timeZone: "UTC",
53};
54
55const CONFIG = {
56 settings: DEFAULT_SERVER_SETTINGS,
57 environment: { serverVersion: "0.0.1", capabilities: {} },
58} as ServerConfig;
59
60const PRICING = { status: "unavailable" as const, source: "test", fetchedAt: null, knownModels: 0 };
61
62const cursorSource = (refreshing: boolean): UsageSource => ({
63 fingerprint: {
64 hostId: "cursor.com",
65 provider: "cursor",
66 resolvedHomePath: "cursor-account:abc",
67 volumeId: "abc",
68 },
69 status: "ok",
70 scannedFiles: 1,
71 skippedFiles: 0,
72 malformedRecords: 0,
73 distinctSessions: 1,
74 message: null,
75 ...(refreshing ? { refreshing: true as const } : {}),
76});
77
78const sameServerSettings = Schema.toEquivalence(ServerSettings);
79
80const makeHarness = Effect.fn("ServerUsageTest.makeHarness")(function* (
81 beforeRead: (
82 request: number,
83 input: UsageSummaryInput,
84 ) => Effect.Effect<void, UsageReadError> = () => Effect.void,
85 sources: (input: UsageSummaryInput) => readonly UsageSource[] = () => [],
86) {
87 const events = yield* Queue.unbounded<ServerConfigStreamEvent>();
88 let settings = DEFAULT_SERVER_SETTINGS;
89 let requests = 0;
90 const inputs: UsageSummaryInput[] = [];
91 const client = {
92 [WS_METHODS.serverRefreshUsageRates]: () => Effect.succeed(PRICING),
93 [WS_METHODS.subscribeServerConfig]: () =>
94 Stream.concat(
95 Stream.make({ version: 1 as const, type: "snapshot" as const, config: CONFIG }),
96 Stream.fromQueue(events),
97 ),
98 [WS_METHODS.serverGetUsageSummary]: (input: UsageSummaryInput) =>
99 Effect.gen(function* () {
100 requests += 1;
101 inputs.push(input);
102 const price = settings.usagePriceOverrides["custom-model"]?.inputCostPerMillionTokens ?? 0;
103 yield* beforeRead(requests, input);
104 return {
105 contractVersion: USAGE_CONTRACT_VERSION,
106 readAt: "2026-09-04T12:00:00Z",
107 ...input,
108 buckets: [
109 {
110 day: input.sinceDay,
111 provider: "codex",
112 model: "custom-model",
113 totals: {
114 uncachedInputTokens: 1_000_000,
115 cachedInputTokens: 0,
116 cacheCreationTokens: 0,
117 outputTokens: 0,
118 reasoningTokens: 0,
119 },
120 costUsd: price,
121 cacheSavingsUsd: 0,
122 costSource: price === 0 ? "unpriced" : "modelPriced",
123 records: 1,
124 unpricedRecords: price === 0 ? 1 : 0,
125 sessions: 1,
126 },
127 ],
128 sources: sources(input),
129 pricing: PRICING,
130 scanDurationMs: 0,
131 } satisfies UsageSummary;
132 }),
133 } as unknown as WsRpcProtocolClient;
134 const session: RpcSession = {
135 client,
136 initialConfig: Effect.succeed(CONFIG),
137 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
138 ready: Effect.void,
139 probe: Effect.void,
140 closed: Effect.never,
141 };
142 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
143 target: TARGET,
144 state: yield* SubscriptionRef.make<SupervisorConnectionState>({
145 ...AVAILABLE_CONNECTION_STATE,
146 phase: "connected",
147 }),
148 session: yield* SubscriptionRef.make(Option.some(session)),
149 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
150 connect: Effect.void,
151 disconnect: Effect.void,
152 retryNow: Effect.void,
153 });
154 const environments = EnvironmentRegistry.EnvironmentRegistry.of({
155 run: (_environmentId, effect) =>
156 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
157 followStream: (_environmentId, stream) =>
158 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
159 } as EnvironmentRegistry.EnvironmentRegistry["Service"]);
160 const cache = Persistence.EnvironmentCacheStore.of({
161 loadShell: () => Effect.succeedNone,
162 saveShell: () => Effect.void,
163 loadThread: () => Effect.succeedNone,
164 saveThread: () => Effect.void,
165 removeThread: () => Effect.void,
166 loadServerConfig: () => Effect.succeedNone,
167 saveServerConfig: () => Effect.void,
168 loadVcsRefs: () => Effect.succeedNone,
169 saveVcsRefs: () => Effect.void,
170 removeVcsRefs: () => Effect.void,
171 clearVcsRefs: () => Effect.void,
172 clear: () => Effect.void,
173 });
174 const runtime = Atom.runtime(
175 Layer.merge(
176 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environments),
177 Layer.succeed(Persistence.EnvironmentCacheStore, cache),
178 ),
179 );
180 const initialConfigValueAtom = Atom.make(CONFIG);
181 const atoms = createServerEnvironmentAtoms(runtime, {
182 initialConfigValueAtom: () => initialConfigValueAtom,
183 });
184 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
185 Effect.sync(() => registry.dispose()),
186 );
187 const updateSettings = Effect.fn("ServerUsageTest.updateSettings")(function* (
188 next: ServerSettings,
189 ) {
190 settings = next;
191 yield* Queue.offer(events, {
192 version: 1,
193 type: "settingsUpdated",
194 payload: { settings },
195 });
196 // An equal settings document keeps the previous object, so match on content.
197 yield* AtomRegistry.toStream(registry, atoms.settingsValueAtom(TARGET.environmentId)).pipe(
198 Stream.filter((current) => current !== null && sameServerSettings(current, next)),
199 Stream.runHead,
200 );
201 });
202 return {
203 registry,
204 atoms,
205 requests: () => requests,
206 inputs: () => inputs,
207 updateSettings,
208 summary: (input = INPUT) => atoms.usageSummary({ environmentId: TARGET.environmentId, input }),
209 };
210});
211
212function settledSummary<E>(
213 registry: AtomRegistry.AtomRegistry,
214 atom: Atom.Atom<AsyncResult.AsyncResult<UsageSummary, E>>,
215) {
216 return AtomRegistry.toStream(registry, atom).pipe(
217 Stream.filterMap((result) =>
218 AsyncResult.isSuccess(result) && !result.waiting
219 ? Result.succeed(result.value)
220 : Result.failVoid,
221 ),
222 Stream.runHead,
223 Effect.map(Option.getOrThrow),
224 );
225}
226
227const makeRefreshingHarness = Effect.fn("ServerUsageTest.makeRefreshingHarness")(function* (
228 followUp: Effect.Effect<void, UsageReadError>,
229) {
230 const followUpStarted = yield* Deferred.make<void>();
231 const harness = yield* makeHarness(
232 (_request, input) =>
233 input.awaitRefresh === true
234 ? Deferred.succeed(followUpStarted, undefined).pipe(Effect.andThen(followUp))
235 : Effect.void,
236 (input) => [cursorSource(input.awaitRefresh !== true)],
237 );
238 return { ...harness, followUpStarted };
239});
240
241function waitForCost<E>(
242 registry: AtomRegistry.AtomRegistry,
243 atom: Atom.Atom<AsyncResult.AsyncResult<UsageSummary, E>>,
244 cost: number,
245) {
246 return AtomRegistry.toStream(registry, atom).pipe(
247 Stream.filter(
248 (result) =>
249 AsyncResult.isSuccess(result) &&
250 !result.waiting &&
251 result.value.buckets[0]?.costUsd === cost,
252 ),
253 Stream.runHead,
254 );
255}
256
257it.effect("refreshes cached usage windows only when override prices change", () =>
258 Effect.scoped(
259 Effect.gen(function* () {
260 const harness = yield* makeHarness();
261 const current = harness.summary();
262 const previous = harness.summary({ ...INPUT, sinceDay: UsageDay.make("2026-08-01") });
263 const unmountCurrent = harness.registry.mount(current);
264 const unmountPrevious = harness.registry.mount(previous);
265 yield* waitForCost(harness.registry, current, 0);
266 yield* waitForCost(harness.registry, previous, 0);
267 unmountPrevious();
268 expect(harness.requests()).toBe(2);
269
270 const prices = {
271 "custom-model": { inputCostPerMillionTokens: 3, outputCostPerMillionTokens: 9 },
272 "other-model": { inputCostPerMillionTokens: 1, outputCostPerMillionTokens: 2 },
273 };
274 yield* harness.updateSettings({ ...DEFAULT_SERVER_SETTINGS, usagePriceOverrides: prices });
275 yield* waitForCost(harness.registry, current, 3);
276 yield* waitForCost(harness.registry, previous, 3);
277 expect(harness.requests()).toBe(4);
278
279 yield* harness.updateSettings({
280 ...DEFAULT_SERVER_SETTINGS,
281 usagePriceOverrides: {
282 "other-model": { outputCostPerMillionTokens: 2, inputCostPerMillionTokens: 1 },
283 "custom-model": { outputCostPerMillionTokens: 9, inputCostPerMillionTokens: 3 },
284 },
285 });
286 yield* harness.updateSettings({
287 ...DEFAULT_SERVER_SETTINGS,
288 usagePriceOverrides: prices,
289 defaultTheme: "custom-theme",
290 });
291 yield* harness.updateSettings(DEFAULT_SERVER_SETTINGS);
292 yield* waitForCost(harness.registry, current, 0);
293 yield* waitForCost(harness.registry, previous, 0);
294 expect(harness.requests()).toBe(6);
295 unmountCurrent();
296 }),
297 ),
298);
299
300it.effect("restarts a pending usage read after a price change", () =>
301 Effect.scoped(
302 Effect.gen(function* () {
303 const started = yield* Deferred.make<void>();
304 const interrupted = yield* Deferred.make<void>();
305 const harness = yield* makeHarness((request) =>
306 request === 1
307 ? Deferred.succeed(started, undefined).pipe(
308 Effect.andThen(Effect.never),
309 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
310 )
311 : Effect.void,
312 );
313 const summary = harness.summary();
314 const unmount = harness.registry.mount(summary);
315 yield* Deferred.await(started);
316 yield* harness.updateSettings({
317 ...DEFAULT_SERVER_SETTINGS,
318 usagePriceOverrides: {
319 "custom-model": { inputCostPerMillionTokens: 5, outputCostPerMillionTokens: 10 },
320 },
321 });
322 yield* waitForCost(harness.registry, summary, 5);
323 yield* Deferred.await(interrupted);
324 expect(harness.requests()).toBe(2);
325 unmount();
326 }),
327 ),
328);
329
330it.effect("settles after one usage read when no source is refreshing", () =>
331 Effect.scoped(
332 Effect.gen(function* () {
333 const harness = yield* makeHarness();
334 const summary = harness.summary();
335 const unmount = harness.registry.mount(summary);
336 yield* settledSummary(harness.registry, summary);
337 expect(harness.inputs()).toEqual([INPUT]);
338 unmount();
339 }),
340 ),
341);
342
343it.effect("shows the cached usage summary until one awaited refresh replaces it", () =>
344 Effect.scoped(
345 Effect.gen(function* () {
346 const refreshed = yield* Deferred.make<void>();
347 const harness = yield* makeRefreshingHarness(Deferred.await(refreshed));
348 const summary = harness.summary();
349 const unmount = harness.registry.mount(summary);
350 yield* Deferred.await(harness.followUpStarted);
351
352 const provisional = harness.registry.get(summary);
353 expect(AsyncResult.isSuccess(provisional) && provisional.waiting).toBe(true);
354 expect(Option.getOrNull(AsyncResult.value(provisional))?.sources).toEqual([
355 cursorSource(true),
356 ]);
357 expect(harness.inputs()).toEqual([INPUT, { ...INPUT, awaitRefresh: true }]);
358
359 yield* Deferred.succeed(refreshed, undefined);
360 expect((yield* settledSummary(harness.registry, summary)).sources).toEqual([
361 cursorSource(false),
362 ]);
363 expect(harness.requests()).toBe(2);
364 unmount();
365 }),
366 ),
367);
368
369it.effect("keeps the cached usage summary when the awaited refresh fails", () =>
370 Effect.scoped(
371 Effect.gen(function* () {
372 const harness = yield* makeRefreshingHarness(
373 Effect.fail(new UsageReadError({ reason: "scanFailed", detail: "Cursor is down" })),
374 );
375 const summary = harness.summary();
376 const unmount = harness.registry.mount(summary);
377 expect((yield* settledSummary(harness.registry, summary)).sources).toEqual([
378 cursorSource(true),
379 ]);
380 expect(AsyncResult.isSuccess(harness.registry.get(summary))).toBe(true);
381 expect(harness.requests()).toBe(2);
382 unmount();
383 }),
384 ),
385);
386
387it.effect("finishes a manual usage refresh only after the awaited refresh", () =>
388 Effect.scoped(
389 Effect.gen(function* () {
390 const refreshed = yield* Deferred.make<void>();
391 const harness = yield* makeRefreshingHarness(Deferred.await(refreshed));
392 const presentation = Atom.make({
393 connection: { phase: "connected" },
394 } as EnvironmentPresentation | null);
395 let finished = false;
396 const refreshing = refreshUsage({
397 registry: harness.registry,
398 server: harness.atoms,
399 presentations: { presentationAtom: () => presentation },
400 environmentIds: [TARGET.environmentId],
401 input: INPUT,
402 }).then(() => {
403 finished = true;
404 });
405 yield* Deferred.await(harness.followUpStarted);
406 expect(finished).toBe(false);
407 yield* Deferred.succeed(refreshed, undefined);
408 yield* Effect.promise(() => refreshing);
409 expect(harness.requests()).toBe(2);
410 }),
411 ),
412);