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

UsageModelDialog.browser.test.tsx

205 lines6.1 KB

1import { RegistryContext } from "@effect/atom-react";
2import {
3 AuthDiagnosticsReadScope,
4 USAGE_CONTRACT_VERSION,
5 UsageSummary,
6 type UsageSummaryInput,
7} from "@t3tools/contracts";
8import { Schema } from "effect";
9import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
10import { describe, expect, it, vi } from "vite-plus/test";
11import { page } from "vite-plus/test/browser";
12​
13import { render } from "../../../test/render";
14import { useUsage } from "../../state/usage";
15import { UsageModelDialog } from "./UsageModelDialog";
16​
17const summaries = vi.hoisted(() => new Map<string, unknown>());
18​
19vi.mock("../../state/presentation", async () => ({
20 environmentPresentations: {
21 presentationsAtom: (await import("effect/reactivity")).Atom.make(
22 new Map([
23 ["local", { connection: { phase: "connected" }, entry: { target: { label: "Local" } } }],
24 ]),
25 ),
26 },
27}));
28vi.mock("../../state/session", async (importOriginal) => ({
29 ...(await importOriginal<typeof import("../../state/session")>()),
30 environmentSession: {
31 sessionStateAtom: () =>
32 Atom.make(AsyncResult.success({ authenticated: true, scopes: [AuthDiagnosticsReadScope] })),
33 },
34}));
35vi.mock("../../state/server", () => ({
36 serverEnvironment: {
37 usageSummary: ({ input }: { readonly input: UsageSummaryInput }) =>
38 summaries.get(input.sinceDay),
39 usageModelFilterAtom: () => Atom.make(undefined),
40 configValueAtom: () => Atom.make(null),
41 },
42}));
43​
44const window = (sinceDay: string) =>
45 ({ sinceDay, untilDay: "2026-11-30", timeZone: "UTC" }) as UsageSummaryInput;
46​
47const decodeSummary = Schema.decodeSync(UsageSummary);
48const summary = (sinceDay: string, costUsd: number) =>
49 decodeSummary({
50 contractVersion: USAGE_CONTRACT_VERSION,
51 readAt: "2026-11-30T00:00:00.000Z",
52 timeZone: "UTC",
53 sinceDay,
54 untilDay: "2026-11-30",
55 buckets: [
56 {
57 day: "2026-11-25",
58 provider: "claude",
59 model: "claude-fable-5",
60 totals: {
61 uncachedInputTokens: 1000,
62 cachedInputTokens: 0,
63 cacheCreationTokens: 0,
64 outputTokens: 0,
65 reasoningTokens: 0,
66 },
67 costUsd,
68 cacheSavingsUsd: 0,
69 costSource: "modelPriced",
70 records: 1,
71 unpricedRecords: 0,
72 sessions: 1,
73 },
74 ],
75 sources: [
76 {
77 fingerprint: {
78 hostId: "host",
79 provider: "claude",
80 resolvedHomePath: "/home",
81 volumeId: "",
82 },
83 status: "ok",
84 scannedFiles: 1,
85 skippedFiles: 0,
86 malformedRecords: 0,
87 distinctSessions: 1,
88 message: null,
89 },
90 ],
91 pricing: { status: "fresh", source: "test", fetchedAt: null, knownModels: 1 },
92 scanDurationMs: 0,
93 });
94​
95function summaryAtom() {
96 return Atom.make<AsyncResult.AsyncResult<UsageSummary, Error>>(AsyncResult.initial(true)).pipe(
97 Atom.keepAlive,
98 );
100​
101function setup() {
102 summaries.clear();
103 const month = summaryAtom();
104 const week = summaryAtom();
105 summaries.set("2026-11-01", month);
106 summaries.set("2026-11-24", week);
107 return { registry: AtomRegistry.make(), month, week };
109​
110function ModelDialogOnUsage({ input }: { readonly input: UsageSummaryInput }) {
111 const { shown } = useUsage(input);
112 const model = shown?.merged.models[0];
113 if (shown === null || model === undefined) return null;
114 return (
115 <UsageModelDialog
116 model={model}
117 environments={shown.environments}
118 metric="cost"
119 chartWindow={{
120 days: ["2026-11-25"],
121 hours: [],
122 resolution: "day",
123 timeZone: "UTC",
124 referenceTime: undefined,
125 hour12: false,
126 }}
127 onSetPrice={() => {}}
128 onClose={() => {}}
129 />
130 );
132​
133describe("UsageModelDialog", () => {
134 it("exposes each stat as its own label and value to screen readers", async () => {
135 await using _screen = await render(
136 <UsageModelDialog
137 model={{
138 model: "claude-sonnet-4-5",
139 provider: "claude",
140 costUsd: 2,
141 totalTokens: 1_000_000,
142 tokens: {
143 uncachedInputTokens: 100_000,
144 cachedInputTokens: 900_000,
145 cacheCreationTokens: 0,
146 outputTokens: 0,
147 reasoningTokens: 0,
148 },
149 records: 1,
150 unpricedRecords: 0,
151 unpricedTokens: 0,
152 costShare: 1,
153 tokenShare: 1,
154 }}
155 environments={[]}
156 metric="cost"
157 chartWindow={{
158 days: [],
159 hours: [],
160 resolution: "day",
161 timeZone: "UTC",
162 referenceTime: undefined,
163 hour12: false,
164 }}
165 onSetPrice={() => {}}
166 onClose={() => {}}
167 />,
168 );
169​
170 const dialog = page.getByRole("dialog");
171 for (const [label, value] of [
172 ["Cost", "$2.00"],
173 ["Tokens", "1M"],
174 ["Per 1M tokens", "$2.00"],
175 ["Cache hit", "90.0%"],
176 ] as const) {
177 await expect
178 .element(dialog.getByRole("term").getByText(label, { exact: true }))
179 .toBeVisible();
180 await expect
181 .element(dialog.getByRole("definition").getByText(value, { exact: true }).first())
182 .toBeVisible();
183 }
184 });
185​
186 it("keeps the trend on the retained window until the next window answers", async () => {
187 const { registry, month, week } = setup();
188 registry.set(month, AsyncResult.success(summary("2026-11-01", 10)));
189 const ui = (input: UsageSummaryInput) => (
190 <RegistryContext.Provider value={registry}>
191 <ModelDialogOnUsage input={input} />
192 </RegistryContext.Provider>
193 );
194 // The dialog reads usage state only; no route is involved.
195 await using screen = await render(ui(window("2026-11-01")), { router: false });
196 const dialog = page.getByRole("dialog");
197 await expect.element(dialog.getByRole("cell", { name: "$10.00" })).toBeVisible();
198​
199 await screen.rerender(ui(window("2026-11-24")));
200 await expect.element(dialog.getByRole("cell", { name: "$10.00" })).toBeVisible();
201​
202 registry.set(week, AsyncResult.success(summary("2026-11-24", 3)));
203 await expect.element(dialog.getByRole("cell", { name: "$3.00" })).toBeVisible();
204 });
205});