@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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