Open History to see the last commit
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!));
101}
102
103it.each([
104 {
105 label: "success",
106 result: { _tag: "Success", value: { outcome: "reset" } },
107 text: "Reset applied. Your windows have cleared.",
108 },
109 {
110 label: "failure",
111 result: { _tag: "Failure", cause: { error: new Error("Codex rejected the credit.") } },
112 text: "Codex rejected the credit.",
113 },
114])("keeps pending feedback outside the closed popup until $label", async ({ result, text }) => {
115 let answer!: (result: unknown) => void;
116 consume.mockReturnValue(new Promise((resolve) => (answer = resolve)));
117 await click("Alpha:");
118 await click("Use reset");
119 expect(consume).not.toHaveBeenCalled();
120 await click("Cancel");
121 expect(consume).not.toHaveBeenCalled();
122 await click("Alpha:");
123 await click("Use reset");
124 await click("Use credit");
125 expect(consume).toHaveBeenCalledOnce();
126 // Both popups unmount once their exit animations finish.
127 await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();
128 await expect.poll(() => document.querySelector('[data-slot="popover-popup"]')).toBeNull();
129 const status = document.querySelector('[role="status"]');
130 expect(status?.textContent).toBe("Alpha Using reset credit…");
131 await click("Alpha:");
132 const using = Array.from(document.querySelectorAll("button")).find(
133 (node) => node.textContent === "Using…",
134 );
135 expect(using?.disabled).toBe(true);
136 await act(async () => answer(result));
137 expect(status?.textContent).toBe(`Alpha ${text}`);
138});
139
140it("omits an empty reset plate but keeps countdowns and banked credits visible", async () => {
141 await page.viewport(1440, 900);
142 const now = Date.parse("2026-09-03T11:00:00Z");
143 const segment = page.getByRole("button", { name: /^Alpha:/ });
144 // The empty plate has no accessible text; select its painted background inside the real bar.
145 const plate = () =>
146 segment.element().querySelector<HTMLSpanElement>('[class~="bg-background/85"]');
147
148 await act(() =>
149 root.render(<UsageLimitsPooled presentations={presentations(undefined, 0)} now={now} />),
150 );
151 await expect.element(segment.getByText("100%", { exact: true })).toBeVisible();
152 expect(plate()).toBeNull();
153
154 await act(() =>
155 root.render(
156 <UsageLimitsPooled presentations={presentations("2026-09-03T14:00:00Z", 0)} now={now} />,
157 ),
158 );
159 await expect.element(plate()).toBeVisible();
160 expect(plate()?.textContent).toBe("↻ 3h 0m");
161
162 await act(() =>
163 root.render(<UsageLimitsPooled presentations={presentations(undefined, 1)} now={now} />),
164 );
165 await expect.element(plate()).toBeVisible();
166 expect(plate()?.textContent).toBe("1");
167});
168
169it("moves the one limit popover between windows on hover", async () => {
170 const [environmentId, presentation] = [...presentations("2026-09-03T14:00:00Z", 1)][0]!;
171 const serverConfig = presentation.serverConfig!;
172 const provider = serverConfig.providers[0]!;
173 const twoWindows: LimitPresentations = new Map([
174 [
175 environmentId,
176 {
177 ...presentation,
178 serverConfig: {
179 ...serverConfig,
180 providers: [
181 {
182 ...provider,
183 usageLimits: {
184 ...provider.usageLimits!,
185 windows: [
186 ...provider.usageLimits!.windows,
187 { id: "weekly", kind: "weekly", label: "Weekly", usedPercent: 32 },
188 ],
189 },
190 },
191 ],
192 },
193 },
194 ],
195 ]);
196 // Room above the bars so the popover opens there instead of flipping over the next card.
197 container.style.paddingTop = "20rem";
198 await act(() => root.render(<UsageLimitsPooled presentations={twoWindows} now={0} />));
199 const segment = (label: string) =>
200 Array.from(document.querySelectorAll("button")).find((node) =>
201 node.getAttribute("aria-label")?.startsWith(label),
202 )!;
203 // Popup contents, once the previous segment's details have animated away.
204 const popups = () =>
205 document.querySelector("[data-previous]")
206 ? null
207 : Array.from(
208 document.querySelectorAll('[data-slot="popover-popup"]'),
209 (node) => node.textContent,
210 );
211 const session = segment("Alpha: 60%");
212 const weekly = segment("Alpha: 68%");
213
214 await act(() => userEvent.click(session));
215 await expect.poll(popups).toEqual([expect.stringContaining("Left60%")]);
216
217 await act(() => userEvent.hover(weekly));
218 await expect.poll(popups).toEqual([expect.stringContaining("Left68%")]);
219
220 // Weekly's popover now sits over the middle of the Session bar; come back in at its edge.
221 await act(() => userEvent.hover(session, { position: { x: 4, y: 4 } }));
222 await expect.poll(popups).toEqual([expect.stringContaining("Left60%")]);
223
224 await act(() => root.render(<UsageLimitsPooled presentations={new Map()} now={0} />));
225 await expect.poll(popups).toEqual([]);
226 await act(() => userEvent.hover(container, { position: { x: 4, y: 4 } }));
227
228 await act(() => root.render(<UsageLimitsPooled presentations={twoWindows} now={0} />));
229 await expect.poll(popups).toEqual([]);
230 await act(() => userEvent.click(segment("Alpha: 60%")));
231 await expect.poll(popups).toEqual([expect.stringContaining("Left60%")]);
232});
233
234it("closes an open source-account popover when reset availability replaces its trigger", async () => {
235 const [environmentId, presentation] = [...presentations("2026-09-03T14:00:00Z", 1)][0]!;
236 const provider = presentation.serverConfig!.providers[0]!;
237 const source = (nextCreditId?: string): LimitPresentations =>
238 new Map([
239 [
240 environmentId,
241 {
242 ...presentation,
243 serverConfig: {
244 providers: [],
245 usageLimitSources: [
246 {
247 id: UsageLimitSourceId.make("hub"),
248 kind: "cliproxy",
249 label: "Hub",
250 checkedAt: "2026-09-03T11:00:00Z",
251 accounts: [
252 {
253 id: "Alpha",
254 driver: provider.driver,
255 usageLimits: {
256 ...provider.usageLimits!,
257 resetCredits: {
258 availableCount: 1,
259 ...(nextCreditId ? { nextCreditId } : {}),
260 },
261 },
262 },
263 ],
264 },
265 ],
266 },
267 },
268 ],
269 ]);
270 const popup = () => document.querySelector('[data-slot="popover-popup"]');
271 await act(() => root.render(<UsageLimitsPooled presentations={source("credit-1")} now={0} />));
272 await click("Alpha: 60%");
273 await expect.poll(() => popup()?.textContent).toContain("Use reset");
274
275 await act(() => root.render(<UsageLimitsPooled presentations={source()} now={0} />));
276 await expect.poll(popup).toBeNull();
277 await click("Alpha: 60%");
278 await expect.poll(() => popup()?.textContent).toContain("Left60%");
279
280 await act(() => root.render(<UsageLimitsPooled presentations={source("credit-2")} now={0} />));
281 await expect.poll(popup).toBeNull();
282 await click("Alpha: 60%");
283 await expect.poll(() => popup()?.textContent).toContain("Use reset");
284 await click("Use reset");
285 await expect.poll(() => document.querySelector('[role="alertdialog"]')).not.toBeNull();
286});