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 * as EnvironmentRegistry from "../connection/registry.ts";
34import * as EnvironmentSupervisor from "../connection/supervisor.ts";
35import * as Persistence from "../platform/persistence.ts";
36import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
37import type { RpcSession } from "../rpc/session.ts";
38import { createServerEnvironmentAtoms } from "./server.ts";
39
40const TARGET = new PrimaryConnectionTarget({
41 environmentId: EnvironmentId.make("usage-environment"),
42 label: "Usage environment",
43 httpBaseUrl: "https://environment.example.test",
44 wsBaseUrl: "wss://environment.example.test",
45});
46
47const INPUT: UsageSummaryInput = {
48 sinceDay: UsageDay.make("2026-09-01"),
49 untilDay: UsageDay.make("2026-09-04"),
50 timeZone: "UTC",
51};
52
53const CONFIG = {
54 settings: DEFAULT_SERVER_SETTINGS,
55 environment: { serverVersion: "0.0.1", capabilities: {} },
56} as ServerConfig;
57
58const PRICING = { status: "unavailable" as const, source: "test", fetchedAt: null, knownModels: 0 };
59
60const cursorSource = (refreshing: boolean): UsageSource => ({
61 fingerprint: {
62 hostId: "cursor.com",
63 provider: "cursor",
64 resolvedHomePath: "cursor-account:abc",
65 volumeId: "abc",
66 },
67 status: "ok",
68 scannedFiles: 1,
69 skippedFiles: 0,
70 malformedRecords: 0,
71 distinctSessions: 1,
72 message: null,
73 ...(refreshing ? { refreshing: true as const } : {}),
74});
75
76const sameServerSettings = Schema.toEquivalence(ServerSettings);
77
78const makeHarness = Effect.fn("ServerUsageTest.makeHarness")(function* (
79 beforeRead: (
80 request: number,
81 input: UsageSummaryInput,
82 ) => Effect.Effect<void, UsageReadError> = () => Effect.void,
83 sources: (input: UsageSummaryInput) => readonly UsageSource[] = () => [],
84) {
85 const events = yield* Queue.unbounded<ServerConfigStreamEvent>();
86 let settings = DEFAULT_SERVER_SETTINGS;
87 let requests = 0;
88 const inputs: UsageSummaryInput[] = [];
89 const client = {
90 [WS_METHODS.serverRefreshUsageRates]: () => Effect.succeed(PRICING),
91 [WS_METHODS.subscribeServerConfig]: () =>
92 Stream.concat(
93 Stream.make({ version: 1 as const, type: "snapshot" as const, config: CONFIG }),
94 Stream.fromQueue(events),
95 ),
96 [WS_METHODS.serverGetUsageSummary]: (input: UsageSummaryInput) =>
97 Effect.gen(function* () {
98 requests += 1;
99 inputs.push(input);
100 const price = settings.usagePriceOverrides["custom-model"]?.inputCostPerMillionTokens ?? 0;
101 yield* beforeRead(requests, input);
102 return {
103 contractVersion: USAGE_CONTRACT_VERSION,
104 readAt: "2026-09-04T12:00:00Z",
105 ...input,
106 buckets: [
107 {
108 day: input.sinceDay,
109 provider: "codex",
110 model: "custom-model",
111 totals: {
112 uncachedInputTokens: 1_000_000,
113 cachedInputTokens: 0,
114 cacheCreationTokens: 0,
115 outputTokens: 0,
116 reasoningTokens: 0,
117 },
118 costUsd: price,
119 cacheSavingsUsd: 0,
120 costSource: price === 0 ? "unpriced" : "modelPriced",
121 records: 1,
122 unpricedRecords: price === 0 ? 1 : 0,
123 sessions: 1,
124 },
125 ],
126 sources: sources(input),
127 pricing: PRICING,
128 scanDurationMs: 0,
129 } satisfies UsageSummary;
130 }),
131 } as unknown as WsRpcProtocolClient;
132 const session: RpcSession = {
133 client,
134 initialConfig: Effect.succeed(CONFIG),
135 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
136 ready: Effect.void,
137 probe: Effect.void,
138 closed: Effect.never,
139 };
140 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
141 target: TARGET,
142 state: yield* SubscriptionRef.make<SupervisorConnectionState>({
143 ...AVAILABLE_CONNECTION_STATE,
144 phase: "connected",
145 }),
146 session: yield* SubscriptionRef.make(Option.some(session)),
147 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
148 connect: Effect.void,
149 disconnect: Effect.void,
150 retryNow: Effect.void,
151 });
152 const environments = EnvironmentRegistry.EnvironmentRegistry.of({
153 run: (_environmentId, effect) =>
154 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
155 followStream: (_environmentId, stream) =>
156 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
157 } as EnvironmentRegistry.EnvironmentRegistry["Service"]);
158 const cache = Persistence.EnvironmentCacheStore.of({
159 loadShell: () => Effect.succeedNone,
160 saveShell: () => Effect.void,
161 loadThread: () => Effect.succeedNone,
162 saveThread: () => Effect.void,
163 removeThread: () => Effect.void,
164 loadServerConfig: () => Effect.succeedNone,
165 saveServerConfig: () => Effect.void,
166 loadVcsRefs: () => Effect.succeedNone,
167 saveVcsRefs: () => Effect.void,
168 removeVcsRefs: () => Effect.void,
169 clearVcsRefs: () => Effect.void,
170 clear: () => Effect.void,
171 });
172 const runtime = Atom.runtime(
173 Layer.merge(
174 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environments),
175 Layer.succeed(Persistence.EnvironmentCacheStore, cache),
176 ),
177 );
178 const initialConfigValueAtom = Atom.make(CONFIG);
179 const atoms = createServerEnvironmentAtoms(runtime, {
180 initialConfigValueAtom: () => initialConfigValueAtom,
181 });
182 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
183 Effect.sync(() => registry.dispose()),
184 );
185 const updateSettings = Effect.fn("ServerUsageTest.updateSettings")(function* (
186 next: ServerSettings,
187 ) {
188 settings = next;
189 yield* Queue.offer(events, {
190 version: 1,
191 type: "settingsUpdated",
192 payload: { settings },
193 });
194 // An equal settings document keeps the previous object, so match on content.
195 yield* AtomRegistry.toStream(registry, atoms.settingsValueAtom(TARGET.environmentId)).pipe(
196 Stream.filter((current) => current !== null && sameServerSettings(current, next)),
197 Stream.runHead,
198 );
199 });
200 return {
201 registry,
202 atoms,
203 requests: () => requests,
204 inputs: () => inputs,
205 updateSettings,
206 summary: (input = INPUT) => atoms.usageSummary({ environmentId: TARGET.environmentId, input }),
207 };
208});
209
210function settledSummary<E>(
211 registry: AtomRegistry.AtomRegistry,
212 atom: Atom.Atom<AsyncResult.AsyncResult<UsageSummary, E>>,
213) {
214 return AtomRegistry.toStream(registry, atom).pipe(
215 Stream.filterMap((result) =>
216 AsyncResult.isSuccess(result) && !result.waiting
217 ? Result.succeed(result.value)
218 : Result.failVoid,
219 ),
220 Stream.runHead,
221 Effect.map(Option.getOrThrow),
222 );
223}
224
225const makeRefreshingHarness = Effect.fn("ServerUsageTest.makeRefreshingHarness")(function* (
226 followUp: Effect.Effect<void, UsageReadError>,
227) {
228 const followUpStarted = yield* Deferred.make<void>();
229 const harness = yield* makeHarness(
230 (_request, input) =>
231 input.awaitRefresh === true
232 ? Deferred.succeed(followUpStarted, undefined).pipe(Effect.andThen(followUp))
233 : Effect.void,
234 (input) => [cursorSource(input.awaitRefresh !== true)],
235 );
236 return { ...harness, followUpStarted };
237});
238
239function waitForCost<E>(
240 registry: AtomRegistry.AtomRegistry,
241 atom: Atom.Atom<AsyncResult.AsyncResult<UsageSummary, E>>,
242 cost: number,
243) {
244 return AtomRegistry.toStream(registry, atom).pipe(
245 Stream.filter(
246 (result) =>
247 AsyncResult.isSuccess(result) &&
248 !result.waiting &&
249 result.value.buckets[0]?.costUsd === cost,
250 ),
251 Stream.runHead,
252 );
253}
254
255it.effect("restarts a pending usage read after a price change", () =>
256 Effect.scoped(
257 Effect.gen(function* () {
258 const started = yield* Deferred.make<void>();
259 const interrupted = yield* Deferred.make<void>();
260 const harness = yield* makeHarness((request) =>
261 request === 1
262 ? Deferred.succeed(started, undefined).pipe(
263 Effect.andThen(Effect.never),
264 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
265 )
266 : Effect.void,
267 );
268 const summary = harness.summary();
269 const unmount = harness.registry.mount(summary);
270 yield* Deferred.await(started);
271 yield* harness.updateSettings({
272 ...DEFAULT_SERVER_SETTINGS,
273 usagePriceOverrides: {
274 "custom-model": { inputCostPerMillionTokens: 5, outputCostPerMillionTokens: 10 },
275 },
276 });
277 yield* waitForCost(harness.registry, summary, 5);
278 yield* Deferred.await(interrupted);
279 expect(harness.requests()).toBe(2);
280 unmount();
281 }),
282 ),
283);
284
285it.effect("keeps the cached usage summary when the awaited refresh fails", () =>
286 Effect.scoped(
287 Effect.gen(function* () {
288 const harness = yield* makeRefreshingHarness(
289 Effect.fail(new UsageReadError({ reason: "scanFailed", detail: "Cursor is down" })),
290 );
291 const summary = harness.summary();
292 const unmount = harness.registry.mount(summary);
293 expect((yield* settledSummary(harness.registry, summary)).sources).toEqual([
294 cursorSource(true),
295 ]);
296 expect(AsyncResult.isSuccess(harness.registry.get(summary))).toBe(true);
297 expect(harness.requests()).toBe(2);
298 unmount();
299 }),
300 ),
301);