Open History to see the last commit
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 { refreshUsage, refreshUsageLimits, resetCreditFailureText } from "./usage.ts";
18
19const input = {
20 sinceDay: UsageDay.make("2026-09-05"),
21 untilDay: UsageDay.make("2026-09-05"),
22 timeZone: "UTC",
23};
24const pricing = { status: "fresh" as const, source: "test", fetchedAt: null, knownModels: 1 };
25const summary: UsageSummary = {
26 ...input,
27 contractVersion: USAGE_CONTRACT_VERSION,
28 readAt: "2026-09-05T12:00:00Z",
29 buckets: [],
30 sources: [],
31 pricing,
32 scanDurationMs: 1,
33};
34const registries: AtomRegistry.AtomRegistry[] = [];
35afterEach(() => {
36 for (const registry of registries.splice(0)) registry.dispose();
37});
38
39function harness(ids = ["a"], modelFilters: Record<string, UsageModelFilter> = {}) {
40 const registry = AtomRegistry.make();
41 registries.push(registry);
42 const environments = ids.map((id) => {
43 const environmentId = EnvironmentId.make(id);
44 const rates = Promise.withResolvers<
45 AsyncResult.Success<typeof pricing> | AsyncResult.Failure<never, Error>
46 >();
47 const scan = Promise.withResolvers<UsageSummary>();
48 const scanStarted = Promise.withResolvers<void>();
49 const presentation = Atom.make({
50 connection: { phase: "connected" },
51 } as EnvironmentPresentation | null);
52 const query = Atom.make(
53 Effect.promise(() => {
54 scanStarted.resolve();
55 return scan.promise;
56 }),
57 );
58 return { environmentId, rates, scan, scanStarted, presentation, query };
59 });
60 function get(environmentId: EnvironmentId) {
61 const environment = environments.find((entry) => entry.environmentId === environmentId);
62 if (!environment) throw new Error(`Unknown environment: ${environmentId}`);
63 return environment;
64 }
65 const requested: { environmentId: EnvironmentId; input: UsageSummaryInput }[] = [];
66 const options = {
67 registry,
68 environmentIds: environments.map((entry) => entry.environmentId),
69 input,
70 server: {
71 usageSummary: (target: { environmentId: EnvironmentId; input: UsageSummaryInput }) => {
72 requested.push(target);
73 return get(target.environmentId).query;
74 },
75 usageModelFilterAtom: (environmentId: EnvironmentId) =>
76 Atom.make<UsageModelFilter | undefined>(modelFilters[environmentId]),
77 refreshUsageRates: {
78 label: "test:rates",
79 requiredScopes: () => [],
80 permissionAtom: () => Atom.make(true),
81 run: (
82 _registry: AtomRegistry.AtomRegistry,
83 { environmentId }: { environmentId: EnvironmentId },
84 ) =>
85 Effect.promise(() => get(environmentId).rates.promise).pipe(
86 Effect.flatMap((result) =>
87 AsyncResult.isSuccess(result)
88 ? Effect.succeed(result.value)
89 : Effect.failCause(result.cause),
90 ),
91 ),
92 },
93 },
94 presentations: {
95 presentationAtom: (environmentId: EnvironmentId) => get(environmentId).presentation,
96 },
97 } satisfies Parameters<typeof refreshUsage>[0];
98 return { registry, environments, requested, refresh: () => refreshUsage(options) };
99}
100
101describe("manual usage refresh", () => {
102 it.each(["success", "failure"])("waits for the rescan after a pricing %s", async (result) => {
103 const {
104 environments: [environment],
105 refresh,
106 } = harness();
107 const entry = environment!;
108 let finished = false;
109 const refreshing = refresh().then(() => {
110 finished = true;
111 });
112 expect(finished).toBe(false);
113 entry.rates.resolve(
114 result === "success"
115 ? AsyncResult.success(pricing)
116 : AsyncResult.fail(new Error("Pricing offline")),
117 );
118 await entry.scanStarted.promise;
119 expect(finished).toBe(false);
120 entry.scan.resolve(summary);
121 await refreshing;
122 expect(finished).toBe(true);
123 });
124
125 it("rescans each environment with its own configured model filter", async () => {
126 const modelFilter = { include: [{ provider: "claude" as const, model: "orbit-1" }] };
127 const { environments, requested, refresh } = harness(["filtered", "plain"], {
128 filtered: modelFilter,
129 });
130 const refreshing = refresh();
131 for (const entry of environments) {
132 entry.rates.resolve(AsyncResult.success(pricing));
133 entry.scan.resolve(summary);
134 }
135 await refreshing;
136 expect(requested).toEqual([
137 { environmentId: "filtered", input: { ...input, modelFilter } },
138 { environmentId: "plain", input },
139 ]);
140 });
141
142 it("settles when an environment disconnects during the rescan", async () => {
143 const {
144 registry,
145 environments: [environment],
146 refresh,
147 } = harness();
148 const entry = environment!;
149 const refreshing = refresh();
150 entry.rates.resolve(AsyncResult.success(pricing));
151 await entry.scanStarted.promise;
152 registry.set(entry.presentation, null);
153 await refreshing;
154 });
155
156 it("waits for healthy environments without waiting for a recovering environment", async () => {
157 const { registry, environments, refresh } = harness(["healthy", "recovering"]);
158 const [healthy, recovering] = environments;
159 registry.set(recovering!.presentation, null);
160 let finished = false;
161 const refreshing = refresh().then(() => {
162 finished = true;
163 });
164 for (const entry of environments) entry.rates.resolve(AsyncResult.success(pricing));
165 await healthy!.scanStarted.promise;
166 expect(finished).toBe(false);
167 healthy!.scan.resolve(summary);
168 await refreshing;
169 expect(finished).toBe(true);
170 });
171
172 it("replaces a scan that started before pricing was refreshed", async () => {
173 const {
174 registry,
175 environments: [environment],
176 refresh,
177 } = harness();
178 const entry = environment!;
179 let reads = 0;
180 const rescanned = Promise.withResolvers<void>();
181 const query = Atom.make(
182 Effect.promise(() => {
183 reads += 1;
184 if (reads > 1) {
185 rescanned.resolve();
186 return Promise.resolve(summary);
187 }
188 return new Promise<UsageSummary>(() => {});
189 }),
190 );
191 entry.query = query;
192 const unmount = registry.mount(query);
193 expect(reads).toBe(1);
194 const refreshing = refresh();
195 entry.rates.resolve(AsyncResult.success(pricing));
196 await rescanned.promise;
197 await refreshing;
198 expect(reads).toBe(2);
199 unmount();
200 });
201});
202
203describe("limits refresh cooldown", () => {
204 it("shares an in-flight check and skips duplicate automatic refreshes", async () => {
205 const id = EnvironmentId.make("limits-in-flight");
206 const oldCheck = Promise.withResolvers<string>();
207 const first = refreshUsageLimits(id, () => oldCheck.promise, true);
208 const newCheck = vi.fn(async () => "new limits");
209 const manual = refreshUsageLimits(id, newCheck);
210 expect(await refreshUsageLimits(id, newCheck, true)).toBeUndefined();
211 expect(newCheck).not.toHaveBeenCalled();
212 oldCheck.resolve("old limits");
213 expect(await first).toBe("old limits");
214 expect(await manual).toBe("old limits");
215 expect(newCheck).not.toHaveBeenCalled();
216 });
217});
218
219describe("reset credit failure text", () => {
220 it("shows the server's reason, falling back only when there is none", () => {
221 const refused = new ProviderSetupError({
222 instanceId: ProviderInstanceId.make("claude"),
223 operation: "consume-reset-credit",
224 detail: "This provider is disabled.",
225 });
226 expect(resetCreditFailureText(AsyncResult.failure(Cause.fail(refused)))).toBe(
227 "This provider is disabled.",
228 );
229 expect(resetCreditFailureText(AsyncResult.failure(Cause.die("Socket closed")))).toBe(
230 "Socket closed",
231 );
232 for (const cause of [Cause.fail({}), Cause.interrupt()]) {
233 expect(resetCreditFailureText(AsyncResult.failure(cause))).toBe(
234 "Could not use the reset credit.",
235 );
236 }
237 });
238});