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

usage.test.tsx

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