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

usage.test.tsx

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