Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usage.test.ts

249 lines8.4 KB

1import {
2 EnvironmentId,
3 ProviderInstanceId,
4 ProviderSetupError,
5 UsageDay,
6 USAGE_CONTRACT_VERSION,
7 type UsageModelFilter,
8 type UsageSummary,
9 type UsageSummaryInput,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
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 environmentIdsKey,
19 refreshUsage,
20 refreshUsageLimits,
21 resetCreditFailureText,
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, Error>
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 ) =>
90 Effect.promise(() => get(environmentId).rates.promise).pipe(
91 Effect.flatMap((result) =>
92 AsyncResult.isSuccess(result)
93 ? Effect.succeed(result.value)
94 : Effect.failCause(result.cause),
95 ),
96 ),
97 },
98 },
99 presentations: {
100 presentationAtom: (environmentId: EnvironmentId) => get(environmentId).presentation,
101 },
102 } satisfies Parameters<typeof refreshUsage>[0];
103 return { registry, environments, requested, refresh: () => refreshUsage(options) };
105​
106describe("manual usage refresh", () => {
107 it.each(["success", "failure"])("waits for the rescan after a pricing %s", async (result) => {
108 const {
109 environments: [environment],
110 refresh,
111 } = harness();
112 const entry = environment!;
113 let finished = false;
114 const refreshing = refresh().then(() => {
115 finished = true;
116 });
117 expect(finished).toBe(false);
118 entry.rates.resolve(
119 result === "success"
120 ? AsyncResult.success(pricing)
121 : AsyncResult.fail(new Error("Pricing offline")),
122 );
123 await entry.scanStarted.promise;
124 expect(finished).toBe(false);
125 entry.scan.resolve(summary);
126 await refreshing;
127 expect(finished).toBe(true);
128 });
129​
130 it("rescans each environment with its own configured model filter", async () => {
131 const modelFilter = { include: [{ provider: "claude" as const, model: "orbit-1" }] };
132 const { environments, requested, refresh } = harness(["filtered", "plain"], {
133 filtered: modelFilter,
134 });
135 const refreshing = refresh();
136 for (const entry of environments) {
137 entry.rates.resolve(AsyncResult.success(pricing));
138 entry.scan.resolve(summary);
139 }
140 await refreshing;
141 expect(requested).toEqual([
142 { environmentId: "filtered", input: { ...input, modelFilter } },
143 { environmentId: "plain", input },
144 ]);
145 });
146​
147 it("settles when an environment disconnects during the rescan", async () => {
148 const {
149 registry,
150 environments: [environment],
151 refresh,
152 } = harness();
153 const entry = environment!;
154 const refreshing = refresh();
155 entry.rates.resolve(AsyncResult.success(pricing));
156 await entry.scanStarted.promise;
157 registry.set(entry.presentation, null);
158 await refreshing;
159 });
160​
161 it("waits for healthy environments without waiting for a recovering environment", async () => {
162 const { registry, environments, refresh } = harness(["healthy", "recovering"]);
163 const [healthy, recovering] = environments;
164 registry.set(recovering!.presentation, null);
165 let finished = false;
166 const refreshing = refresh().then(() => {
167 finished = true;
168 });
169 for (const entry of environments) entry.rates.resolve(AsyncResult.success(pricing));
170 await healthy!.scanStarted.promise;
171 expect(finished).toBe(false);
172 healthy!.scan.resolve(summary);
173 await refreshing;
174 expect(finished).toBe(true);
175 });
176​
177 it("replaces a scan that started before pricing was refreshed", async () => {
178 const {
179 registry,
180 environments: [environment],
181 refresh,
182 } = harness();
183 const entry = environment!;
184 let reads = 0;
185 const rescanned = Promise.withResolvers<void>();
186 const query = Atom.make(
187 Effect.promise(() => {
188 reads += 1;
189 if (reads > 1) {
190 rescanned.resolve();
191 return Promise.resolve(summary);
192 }
193 return new Promise<UsageSummary>(() => {});
194 }),
195 );
196 entry.query = query;
197 const unmount = registry.mount(query);
198 expect(reads).toBe(1);
199 const refreshing = refresh();
200 entry.rates.resolve(AsyncResult.success(pricing));
201 await rescanned.promise;
202 await refreshing;
203 expect(reads).toBe(2);
204 unmount();
205 });
206});
207​
208it("keeps an environment id containing a comma apart from two environments", () => {
209 expect(environmentIdsKey([EnvironmentId.make("a,b")])).not.toBe(
210 environmentIdsKey([EnvironmentId.make("b"), EnvironmentId.make("a")]),
211 );
212});
213​
214describe("limits refresh cooldown", () => {
215 it("shares an in-flight check and skips duplicate automatic refreshes", async () => {
216 const id = EnvironmentId.make("limits-in-flight");
217 const oldCheck = Promise.withResolvers<string>();
218 const first = refreshUsageLimits(id, () => oldCheck.promise, true);
219 const newCheck = vi.fn(async () => "new limits");
220 const manual = refreshUsageLimits(id, newCheck);
221 expect(await refreshUsageLimits(id, newCheck, true)).toBeUndefined();
222 expect(newCheck).not.toHaveBeenCalled();
223 oldCheck.resolve("old limits");
224 expect(await first).toBe("old limits");
225 expect(await manual).toBe("old limits");
226 expect(newCheck).not.toHaveBeenCalled();
227 });
228});
229​
230describe("reset credit failure text", () => {
231 it("shows the server's reason, falling back only when there is none", () => {
232 const refused = new ProviderSetupError({
233 instanceId: ProviderInstanceId.make("claude"),
234 operation: "consume-reset-credit",
235 detail: "This provider is disabled.",
236 });
237 expect(resetCreditFailureText(AsyncResult.failure(Cause.fail(refused)))).toBe(
238 "This provider is disabled.",
239 );
240 expect(resetCreditFailureText(AsyncResult.failure(Cause.die("Socket closed")))).toBe(
241 "Socket closed",
242 );
243 for (const cause of [Cause.fail({}), Cause.interrupt()]) {
244 expect(resetCreditFailureText(AsyncResult.failure(cause))).toBe(
245 "Could not use the reset credit.",
246 );
247 }
248 });
249});