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

usage.test.tsx

168 lines5.5 KB

1import { EnvironmentId, UsageDay, USAGE_CONTRACT_VERSION } from "@t3tools/contracts";
2import { act, useLayoutEffect } from "react";
3import { create, type ReactTestRenderer } from "react-test-renderer";
4import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5​
6import { useUsage, type EnvironmentUsageStatus, type UsageView } from "./usage";
7​
8const testState = vi.hoisted(() => ({ environments: [] as EnvironmentUsageStatus[] }));
9vi.mock("@effect/atom-react", async (importOriginal) => ({
10 ...(await importOriginal<typeof import("@effect/atom-react")>()),
11 useAtomValue: () => testState.environments,
12}));
13​
14const input = {
15 sinceDay: UsageDay.make("2026-09-04"),
16 untilDay: UsageDay.make("2026-09-04"),
17 timeZone: "UTC",
18};
19​
20function environment(id: string, cost: number | null, hostId = id): EnvironmentUsageStatus {
21 return {
22 environmentId: EnvironmentId.make(id),
23 label: id,
24 isPending: cost === null,
25 canReadDiagnostics: true,
26 error: null,
27 needsCursorKeychainAccess: false,
28 summary:
29 cost === null
30 ? null
31 : {
32 ...input,
33 contractVersion: USAGE_CONTRACT_VERSION,
34 readAt: "2026-09-04T12:00:00Z",
35 buckets: [
36 {
37 day: input.sinceDay,
38 provider: "codex",
39 model: id,
40 totals: {
41 uncachedInputTokens: 100,
42 cachedInputTokens: 0,
43 cacheCreationTokens: 0,
44 outputTokens: 50,
45 reasoningTokens: 0,
46 },
47 costUsd: cost,
48 cacheSavingsUsd: 0,
49 costSource: "modelPriced",
50 records: 1,
51 unpricedRecords: 0,
52 sessions: 1,
53 },
54 ],
55 sources: [
56 {
57 fingerprint: {
58 hostId,
59 provider: "codex",
60 resolvedHomePath: "/sessions",
61 volumeId: hostId,
62 },
63 status: "ok",
64 scannedFiles: 1,
65 skippedFiles: 0,
66 malformedRecords: 0,
67 distinctSessions: 1,
68 message: null,
69 },
70 ],
71 pricing: { status: "fresh", source: "test", fetchedAt: null, knownModels: 1 },
72 scanDurationMs: 1,
73 },
74 };
76​
77let renderer: ReactTestRenderer | undefined;
78let latest: UsageView;
79​
80function Probe({ selected }: { selected: ReadonlySet<EnvironmentId> | null }) {
81 const usage = useUsage(input, selected);
82 useLayoutEffect(() => {
83 latest = usage;
84 }, [usage]);
85 return null;
87​
88async function select(...ids: string[]) {
89 await act(() => {
90 renderer?.update(<Probe selected={new Set(ids.map((id) => EnvironmentId.make(id)))} />);
91 });
93​
94beforeEach(async () => {
95 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
96 testState.environments = [environment("a", 10), environment("b", 20), environment("slow", null)];
97 await act(() => {
98 renderer = create(<Probe selected={null} />);
99 });
100});
101​
102afterEach(async () => {
103 await act(() => renderer?.unmount());
104 vi.unstubAllGlobals();
105});
106​
107describe("usage environment selection", () => {
108 it("starts with all environments and adds results as they arrive", async () => {
109 expect(latest.merged.costUsd).toBe(30);
110 expect(latest.isPending).toBe(false);
111 expect(latest.isPartial).toBe(true);
112​
113 testState.environments = [...testState.environments.slice(0, 2), environment("slow", 40)];
114 await act(() => renderer?.update(<Probe selected={null} />));
115 expect(latest.merged.costUsd).toBe(70);
116 expect(latest.isPartial).toBe(false);
117 });
118​
119 it("excludes unselected usage and pending environments, then restores all", async () => {
120 await select("b");
121 expect(latest.merged.costUsd).toBe(20);
122 expect(latest.merged.models.map((model) => model.model)).toEqual(["b"]);
123 expect(latest.isPending).toBe(false);
124 expect(latest.isPartial).toBe(false);
125 expect(latest.environments).toHaveLength(3);
126​
127 await act(() => renderer?.update(<Probe selected={null} />));
128 expect(latest.merged.costUsd).toBe(30);
129 expect(latest.isPartial).toBe(true);
130 });
131​
132 it("distinguishes a pending selection from an empty or failed selection", async () => {
133 await select("slow");
134 expect(latest.isPending).toBe(true);
135 expect(latest.merged.costUsd).toBe(0);
136​
137 await select();
138 expect(latest.selectedEnvironments).toHaveLength(0);
139 expect(latest.isPending).toBe(false);
140 expect(latest.isPartial).toBe(false);
141​
142 testState.environments = [{ ...environment("slow", null), isPending: false, error: "Offline" }];
143 await select("slow");
144 expect(latest.isPending).toBe(false);
145 expect(latest.isPartial).toBe(false);
146 });
147​
148 it("deduplicates within the selection so an excluded owner cannot hide usage", async () => {
149 testState.environments = [environment("a", 10, "shared"), environment("b", 20, "shared")];
150 await act(() => renderer?.update(<Probe selected={null} />));
151 expect(latest.merged.costUsd).toBe(10);
152​
153 await select("b");
154 expect(latest.merged.costUsd).toBe(20);
155 expect(latest.merged.duplicateSources).toEqual([]);
156 });
157​
158 it("keeps selected cached results visible during a refresh", async () => {
159 testState.environments = [
160 { ...environment("a", 10), isPending: true },
161 environment("slow", null),
162 ];
163 await select("a");
164 expect(latest.merged.costUsd).toBe(10);
165 expect(latest.isPending).toBe(false);
166 expect(latest.isPartial).toBe(false);
167 });
168});