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

UsageLimitsPooled.browser.test.tsx

311 lines11.2 KB

1import {
2 EnvironmentId,
3 ProviderDriverKind,
4 ProviderInstanceId,
5 UsageLimitSourceId,
6 type ServerProvider,
7} from "@t3tools/contracts";
8import type { LimitPresentations } from "@t3tools/shared/usageLimits";
9import { act } from "react";
10import { createRoot, type Root } from "react-dom/client";
11import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
12import { page, userEvent } from "vite-plus/test/browser";
13​
14// Real pointer clicks need the dialog's stacking styles to land above Base UI's modal overlay.
15import "~/index.css";
16​
17const consume = vi.hoisted(() => vi.fn());
18vi.mock("../../state/session", () => ({
19 useEnvironmentScope: () => true,
20 readEnvironmentScope: () => true,
21}));
22vi.mock("../../state/server", () => ({ serverEnvironment: { consumeResetCredit: null } }));
23vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => consume }));
24vi.mock("../../hooks/useSettings", () => ({ usePrimarySettings: () => "24h" }));
25vi.mock("../chat/ProviderInstanceIcon", () => ({ ProviderInstanceIcon: () => null }));
26vi.mock("../settings/RedactedSensitiveText", () => ({ RedactedSensitiveText: () => null }));
27​
28import { UsageLimitsPooled } from "./UsageLimitsPooled";
29​
30const presentations = (resetsAt: string | undefined, availableCount: number): LimitPresentations =>
31 new Map([
32 [
33 EnvironmentId.make("env-a"),
34 {
35 entry: { target: { label: "Test" } },
36 serverConfig: {
37 usageLimitSources: [],
38 providers: [
39 {
40 instanceId: ProviderInstanceId.make("alpha"),
41 driver: ProviderDriverKind.make("codex"),
42 displayName: "Alpha",
43 enabled: true,
44 installed: true,
45 version: null,
46 status: "ready",
47 auth: { status: "authenticated", email: "alpha@example.com" },
48 checkedAt: "2026-09-03T11:00:00Z",
49 models: [],
50 slashCommands: [],
51 skills: [],
52 usageLimits: {
53 checkedAt: "2026-09-03T11:00:00Z",
54 resetCredits: { availableCount },
55 windows: [
56 {
57 id: "five_hour",
58 kind: "session",
59 label: "Session",
60 usedPercent: resetsAt ? 40 : 0,
61 windowDurationMins: 300,
62 ...(resetsAt ? { resetsAt } : {}),
63 },
64 ],
65 },
66 } satisfies ServerProvider,
67 ],
68 },
69 },
70 ],
71 ]);
72​
73let root: Root;
74let container: HTMLDivElement;
75​
76beforeEach(async () => {
77 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
78 consume.mockReset();
79 container = document.createElement("div");
80 document.body.append(container);
81 root = createRoot(container);
82 await act(() =>
83 root.render(
84 <UsageLimitsPooled presentations={presentations("2026-09-03T14:00:00Z", 1)} now={0} />,
85 ),
86 );
87});
88​
89afterEach(async () => {
90 await act(() => root.unmount());
91 container.remove();
92 vi.unstubAllGlobals();
93});
94​
95async function click(label: string) {
96 const button = Array.from(document.querySelectorAll("button")).find(
97 (node) => node.textContent === label || node.getAttribute("aria-label")?.startsWith(label),
98 );
99 expect(button).toBeDefined();
100 await act(() => userEvent.click(button!));
102​
103/**
104 * Runs `change`, which takes the open popup's trigger out of the page, then watches the popup
105 * leave. A detached trigger has no rect, so a popup that keeps positioning against it slides
106 * to the viewport origin on its way out.
107 */
108async function expectDismissedInPlace(change: () => Promise<void> | void) {
109 const positioner = () => document.querySelector('[data-slot="popover-positioner"]');
110 const place = (node: Element) => {
111 const rect = node.getBoundingClientRect();
112 return [rect.left, rect.top];
113 };
114 const before = place(positioner()!);
115 await change();
116 const seen: number[][] = [];
117 for (let frame = 0; frame < 60 && positioner(); frame += 1) {
118 seen.push(place(positioner()!));
119 await new Promise(requestAnimationFrame);
120 }
121 expect(positioner()).toBeNull();
122 expect(seen).toEqual(seen.map(() => before));
124​
125it.each([
126 {
127 label: "success",
128 result: { _tag: "Success", value: { outcome: "reset" } },
129 text: "Reset applied. Your windows have cleared.",
130 },
131 {
132 label: "failure",
133 result: { _tag: "Failure", cause: { error: new Error("Codex rejected the credit.") } },
134 text: "Codex rejected the credit.",
135 },
136])("keeps pending feedback outside the closed popup until $label", async ({ result, text }) => {
137 let answer!: (result: unknown) => void;
138 consume.mockReturnValue(new Promise((resolve) => (answer = resolve)));
139 await click("Alpha:");
140 await click("Use reset");
141 expect(consume).not.toHaveBeenCalled();
142 await click("Cancel");
143 expect(consume).not.toHaveBeenCalled();
144 await click("Alpha:");
145 await click("Use reset");
146 await click("Use credit");
147 expect(consume).toHaveBeenCalledOnce();
148 // Both popups unmount once their exit animations finish.
149 await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();
150 await expect.poll(() => document.querySelector('[data-slot="popover-popup"]')).toBeNull();
151 const status = document.querySelector('[role="status"]');
152 expect(status?.textContent).toBe("Alpha Using reset credit…");
153 await click("Alpha:");
154 const using = Array.from(document.querySelectorAll("button")).find(
155 (node) => node.textContent === "Using…",
156 );
157 expect(using?.disabled).toBe(true);
158 await act(async () => answer(result));
159 expect(status?.textContent).toBe(`Alpha ${text}`);
160});
161​
162it("omits an empty reset plate but keeps countdowns and banked credits visible", async () => {
163 await page.viewport(1440, 900);
164 const now = Date.parse("2026-09-03T11:00:00Z");
165 const segment = page.getByRole("button", { name: /^Alpha:/ });
166 // The empty plate has no accessible text; select its painted background inside the real bar.
167 const plate = () =>
168 segment.element().querySelector<HTMLSpanElement>('[class~="bg-background/85"]');
169​
170 await act(() =>
171 root.render(<UsageLimitsPooled presentations={presentations(undefined, 0)} now={now} />),
172 );
173 await expect.element(segment.getByText("100%", { exact: true })).toBeVisible();
174 expect(plate()).toBeNull();
175​
176 await act(() =>
177 root.render(
178 <UsageLimitsPooled presentations={presentations("2026-09-03T14:00:00Z", 0)} now={now} />,
179 ),
180 );
181 await expect.element(plate()).toBeVisible();
182 expect(plate()?.textContent).toBe("↻ 3h 0m");
183​
184 await act(() =>
185 root.render(<UsageLimitsPooled presentations={presentations(undefined, 1)} now={now} />),
186 );
187 await expect.element(plate()).toBeVisible();
188 expect(plate()?.textContent).toBe("1");
189});
190​
191it("moves the one limit popover between windows on hover", async () => {
192 const [environmentId, presentation] = [...presentations("2026-09-03T14:00:00Z", 1)][0]!;
193 const serverConfig = presentation.serverConfig!;
194 const provider = serverConfig.providers[0]!;
195 const twoWindows: LimitPresentations = new Map([
196 [
197 environmentId,
198 {
199 ...presentation,
200 serverConfig: {
201 ...serverConfig,
202 providers: [
203 {
204 ...provider,
205 usageLimits: {
206 ...provider.usageLimits!,
207 windows: [
208 ...provider.usageLimits!.windows,
209 { id: "weekly", kind: "weekly", label: "Weekly", usedPercent: 32 },
210 ],
211 },
212 },
213 ],
214 },
215 },
216 ],
217 ]);
218 // Room above the bars so the popover opens there instead of flipping over the next card.
219 container.style.paddingTop = "20rem";
220 await act(() => root.render(<UsageLimitsPooled presentations={twoWindows} now={0} />));
221 const segment = (label: string) =>
222 Array.from(document.querySelectorAll("button")).find((node) =>
223 node.getAttribute("aria-label")?.startsWith(label),
224 )!;
225 // Popup contents, once the previous segment's details have animated away.
226 const popups = () =>
227 document.querySelector("[data-previous]")
228 ? null
229 : Array.from(
230 document.querySelectorAll('[data-slot="popover-popup"]'),
231 (node) => node.textContent,
232 );
233 const session = segment("Alpha: 60%");
234 const weekly = segment("Alpha: 68%");
235​
236 await act(() => userEvent.click(session));
237 await expect.poll(popups).toEqual([expect.stringContaining("Left60%")]);
238​
239 await act(() => userEvent.hover(weekly));
240 await expect.poll(popups).toEqual([expect.stringContaining("Left68%")]);
241​
242 // Weekly's popover now sits over the middle of the Session bar; come back in at its edge.
243 await act(() => userEvent.hover(session, { position: { x: 4, y: 4 } }));
244 await expect.poll(popups).toEqual([expect.stringContaining("Left60%")]);
245​
246 await expectDismissedInPlace(() =>
247 act(() => root.render(<UsageLimitsPooled presentations={new Map()} now={0} />)),
248 );
249 await act(() => userEvent.hover(container, { position: { x: 4, y: 4 } }));
250​
251 await act(() => root.render(<UsageLimitsPooled presentations={twoWindows} now={0} />));
252 await expect.poll(popups).toEqual([]);
253 await act(() => userEvent.click(segment("Alpha: 60%")));
254 await expect.poll(popups).toEqual([expect.stringContaining("Left60%")]);
255});
256​
257it("closes an open source-account popover when reset availability replaces its trigger", async () => {
258 const [environmentId, presentation] = [...presentations("2026-09-03T14:00:00Z", 1)][0]!;
259 const provider = presentation.serverConfig!.providers[0]!;
260 const source = (nextCreditId?: string): LimitPresentations =>
261 new Map([
262 [
263 environmentId,
264 {
265 ...presentation,
266 serverConfig: {
267 providers: [],
268 usageLimitSources: [
269 {
270 id: UsageLimitSourceId.make("hub"),
271 kind: "cliproxy",
272 label: "Hub",
273 checkedAt: "2026-09-03T11:00:00Z",
274 accounts: [
275 {
276 id: "Alpha",
277 driver: provider.driver,
278 usageLimits: {
279 ...provider.usageLimits!,
280 resetCredits: {
281 availableCount: 1,
282 ...(nextCreditId ? { nextCreditId } : {}),
283 },
284 },
285 },
286 ],
287 },
288 ],
289 },
290 },
291 ],
292 ]);
293 const popup = () => document.querySelector('[data-slot="popover-popup"]');
294 await act(() => root.render(<UsageLimitsPooled presentations={source("credit-1")} now={0} />));
295 await click("Alpha: 60%");
296 await expect.poll(() => popup()?.textContent).toContain("Use reset");
297​
298 await expectDismissedInPlace(() =>
299 act(() => root.render(<UsageLimitsPooled presentations={source()} now={0} />)),
300 );
301 await click("Alpha: 60%");
302 await expect.poll(() => popup()?.textContent).toContain("Left60%");
303​
304 await expectDismissedInPlace(() =>
305 act(() => root.render(<UsageLimitsPooled presentations={source("credit-2")} now={0} />)),
306 );
307 await click("Alpha: 60%");
308 await expect.poll(() => popup()?.textContent).toContain("Use reset");
309 await click("Use reset");
310 await expect.poll(() => document.querySelector('[role="alertdialog"]')).not.toBeNull();
311});