@devries-cameron20 / t3code Mirror · read-only / commits / 81dea7821d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 22:00 UTC

test(web): disposable render helper and lint rule for browser tests (#22187)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 20, 2026 at 10:21 UTC 81dea7821dca30b417182db6fa0cb99a0195bfd8
149 files changed +7080 -7300
AGENTS.md
+12
@@ -100,6 +100,18 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real
100 - **Do not run repo-wide checks.** No `vp check`, no `vp run -r test`, no `vp run -r typecheck` unless I ask. CI owns the full suite.
101 - Backend behavior changes ship with focused tests for that behavior.
102 - The server is event-sourced, and side effects run after the command commits. In tests, drain the effect worker (`OrchestrationEffectWorkerV2.drain`) or await the specific persisted event or `Deferred` that marks the milestone. Never wait on sleeps or polling. A test that needs a timeout to pass is wrong.
103 +- Web component tests are `*.browser.test.tsx` and render through `apps/web/test/render.tsx`. Acquire everything a test changes with `using`/`await using` so disposal undoes it even when the test fails; no `beforeEach`/`afterEach`, no module-level screens. Shared mock state that `vi.mock` factories read gets reset by a `setup()` call at the top of the test. `t3code/require-disposable-render` flags the old patterns.
104 +
105 + ```tsx
106 + it("saves on Enter", async () => {
107 + const onSave = vi.fn();
108 + using _now = vi.spyOn(Date, "now").mockReturnValue(0);
109 + await using screen = await render(<TitleEditor onSave={onSave} />, { router: "/threads/1" });
110 + await userEvent.type(screen.getByRole("textbox"), "Title{Enter}");
111 + expect(onSave).toHaveBeenCalledWith("Title");
112 + });
113 + ```
114 +
115 - Upon request, user-visible frontend changes should get one integrated pass in a real client: `test-t3-app` for web, `test-t3-mobile` for mobile. The primary agent does this once after integrating. Subagents do not launch their own dev servers. Ask permission before doing computer use or spinning up browsers.
116
117 For authorized mobile verification, a missing or outdated native client is a build step, not a blocker. Run `node scripts/mobile-native-client.ts ensure <ios|android> <device-id>` on the simulator host before starting Metro. It checks the local Expo fingerprint and builds/installs when needed. See `test-t3-mobile` for the full workflow.
apps/web/src/browser/ElectronBrowserHost.browser.test.tsx
+34 -34
@@ -7,9 +7,9 @@ import {
7 type DesktopPreviewBridge,
8 type PreviewSessionSnapshot,
9 } from "@t3tools/contracts";
10 -import { act } from "react";
11 -import { createRoot, type Root } from "react-dom/client";
12 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
10 +import { describe, expect, it, vi } from "vite-plus/test";
11 +
12 +import { act, fakeTimers, render } from "../../test/render";
13
14 const mocks = vi.hoisted(() => ({
15 getClientSettings: vi.fn<() => Promise<ClientSettings | null>>(),
@@ -73,10 +73,7 @@ const snapshot = (tabId: string, updatedAt: string): PreviewSessionSnapshot => (
73 updatedAt,
74 });
75
76 -let root: Root | undefined;
77 -let container: HTMLDivElement;
78 -
79 -beforeEach(() => {
76 +function setup(): Disposable {
77 __resetClientSettingsPersistenceForTests();
78 mocks.getClientSettings.mockReset().mockResolvedValue(DEFAULT_CLIENT_SETTINGS);
79 mocks.setClientSettings.mockReset().mockResolvedValue(undefined);
@@ -88,26 +85,37 @@ beforeEach(() => {
85 webPreferences: "contextIsolation=yes",
86 preloadUrl: null,
87 });
91 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
92 - container = document.createElement("div");
93 - document.body.append(container);
94 -});
95 -
96 -afterEach(async () => {
97 - vi.useFakeTimers();
98 - await act(async () => root?.unmount());
99 - root = undefined;
100 - container.remove();
101 - await vi.advanceTimersByTimeAsync(0);
102 - vi.useRealTimers();
103 - resetPreviewStateForTests();
104 - __resetClientSettingsPersistenceForTests();
105 - vi.restoreAllMocks();
106 - vi.unstubAllGlobals();
107 -});
88 + return {
89 + [Symbol.dispose]() {
90 + resetPreviewStateForTests();
91 + __resetClientSettingsPersistenceForTests();
92 + },
93 + };
94 +}
95 +
96 +async function renderHost() {
97 + await using stack = new AsyncDisposableStack();
98 + const screen = stack.use(
99 + await render(
100 + <AppAtomRegistryProvider>
101 + <ElectronBrowserHost />
102 + </AppAtomRegistryProvider>,
103 + ),
104 + );
105 + // Unmounting releases each tab on a close timer; run it now so it never fires in a later test.
106 + stack.defer(async () => {
107 + using _timers = fakeTimers();
108 + await screen.unmount();
109 + await vi.advanceTimersByTimeAsync(0);
110 + });
111 + await act(() => ensureClientSettingsHydrated());
112 + const environment = stack.move();
113 + return { container: screen.container, [Symbol.asyncDispose]: () => environment.disposeAsync() };
114 +}
115
116 describe("ElectronBrowserHost", () => {
117 it("never moves a tab's webview when the server reorders tabs by last update", async () => {
118 + using _state = setup();
119 reconcilePreviewServerSessions(threadRef, {
120 sessions: [
121 snapshot("tab_7", "2026-01-01T00:00:01.000Z"),
@@ -116,17 +124,9 @@ describe("ElectronBrowserHost", () => {
124 serverEpoch: "server-a",
125 revision: 1,
126 });
119 - root = createRoot(container);
120 - await act(async () => {
121 - root!.render(
122 - <AppAtomRegistryProvider>
123 - <ElectronBrowserHost />
124 - </AppAtomRegistryProvider>,
125 - );
126 - await ensureClientSettingsHydrated();
127 - });
127 + await using screen = await renderHost();
128
129 - const host = container.querySelector("[data-electron-browser-host]")!;
129 + const host = screen.container.querySelector("[data-electron-browser-host]")!;
130 const webviews = () => [...host.querySelectorAll("webview")];
131 const before = webviews();
132 expect(before.map((node) => node.getAttribute("data-preview-server-tab")).toSorted()).toEqual([
apps/web/src/browser/HostedBrowserWebview.browser.test.tsx
+80 -68
@@ -7,13 +7,14 @@ import {
7 type DesktopPreviewBridge,
8 type PreviewViewportSetting,
9 } from "@t3tools/contracts";
10 -import { act } from "react";
10 +import type { ReactNode } from "react";
11
12 import "~/index.css";
13 -import { createRoot, type Root } from "react-dom/client";
14 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13 +import { describe, expect, it, vi } from "vite-plus/test";
14 import type { previewBridge } from "~/components/preview/previewBridge";
15
16 +import { act, fakeTimers, render, stubGlobal } from "../../test/render";
17 +
18 const mocks = vi.hoisted(() => ({
19 getClientSettings: vi.fn<() => Promise<ClientSettings | null>>(),
20 setClientSettings: vi.fn<(settings: ClientSettings) => Promise<void>>(),
@@ -58,9 +59,6 @@ import { useBrowserSurfaceStore } from "./browserSurfaceStore";
59 import * as desktopTabLifetime from "./desktopTabLifetime";
60 import { HostedBrowserWebview } from "./HostedBrowserWebview";
61
61 -let root: Root | undefined;
62 -let container: HTMLDivElement;
63 -
62 function deferred<A>() {
63 let resolve!: (value: A) => void;
64 let reject!: (error: unknown) => void;
@@ -71,9 +69,16 @@ function deferred<A>() {
69 return { promise, resolve, reject };
70 }
71
74 -beforeEach(() => {
72 +function resetStores() {
73 __resetClientSettingsPersistenceForTests();
74 useBrowserSurfaceStore.setState({ activityByTabId: {}, byTabId: {} });
75 +}
76 +
77 +function setup() {
78 + using stack = new DisposableStack();
79 + resetStores();
80 + stack.defer(resetStores);
81 + vi.mocked(desktopTabLifetime.acquireDesktopTab).mockClear();
82 mocks.getClientSettings.mockReset();
83 mocks.setClientSettings.mockReset().mockResolvedValue(undefined);
84 mocks.createTab.mockReset().mockResolvedValue(undefined);
@@ -84,27 +89,27 @@ beforeEach(() => {
89 webPreferences: "contextIsolation=yes",
90 preloadUrl: null,
91 });
87 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
88 - vi.spyOn(console, "error").mockImplementation(() => undefined);
89 - container = document.createElement("div");
90 - document.body.append(container);
91 -});
92 + stack.use(vi.spyOn(console, "error").mockImplementation(() => undefined));
93 + return stack.move();
94 +}
95
93 -afterEach(async () => {
94 - vi.useFakeTimers();
95 - await act(async () => root?.unmount());
96 - root = undefined;
97 - container.remove();
98 - await vi.advanceTimersByTimeAsync(0);
99 - vi.useRealTimers();
100 - __resetClientSettingsPersistenceForTests();
101 - useBrowserSurfaceStore.setState({ activityByTabId: {}, byTabId: {} });
102 - vi.restoreAllMocks();
103 - vi.unstubAllGlobals();
104 -});
96 +// The webview releases its desktop tab on a timer after unmount; run it before the test ends
97 +// so it cannot land in the next one.
98 +async function renderHost(ui: ReactNode) {
99 + await using stack = new AsyncDisposableStack();
100 + const screen = stack.use(await render(ui));
101 + stack.defer(async () => {
102 + using _timers = fakeTimers();
103 + await screen.unmount();
104 + await vi.advanceTimersByTimeAsync(0);
105 + });
106 + const environment = stack.move();
107 + return Object.assign(screen, { [Symbol.asyncDispose]: () => environment.disposeAsync() });
108 +}
109
110 describe("HostedBrowserWebview settings hydration", () => {
111 it("starts a retained background tab only after a settings read succeeds on retry", async () => {
112 + using _setup = setup();
113 const firstRead = deferred<ClientSettings | null>();
114 const retryRead = deferred<ClientSettings | null>();
115 const tabCreation = deferred<void>();
@@ -116,7 +121,7 @@ describe("HostedBrowserWebview settings hydration", () => {
121 // Chromium treats <webview> as an unknown element; give it the one Electron method the
122 // host calls once the guest attaches.
123 const createElement = document.createElement.bind(document);
119 - const createGuest = vi.spyOn(document, "createElement").mockImplementation(((
124 + using createGuest = vi.spyOn(document, "createElement").mockImplementation(((
125 tagName: string,
126 options?: ElementCreationOptions,
127 ) => {
@@ -126,7 +131,7 @@ describe("HostedBrowserWebview settings hydration", () => {
131 : element;
132 }) as typeof document.createElement);
133 const guests = () => createGuest.mock.calls.filter(([tagName]) => tagName === "webview");
129 - const guest = () => container.querySelector("webview");
134 + const guest = () => screen.container.querySelector("webview");
135 const threadRef = {
136 environmentId: EnvironmentId.make("host-settings-retry"),
137 threadId: ThreadId.make("thread-settings-retry"),
@@ -134,20 +139,17 @@ describe("HostedBrowserWebview settings hydration", () => {
139 const runtimeTabId = "retained-background-tab";
140 useBrowserSurfaceStore.getState().acquireActivity(runtimeTabId);
141
137 - root = createRoot(container);
138 - await act(async () =>
139 - root!.render(
140 - <HostedBrowserWebview
141 - threadRef={threadRef}
142 - tabId="server-tab"
143 - runtimeTabId={runtimeTabId}
144 - initialUrl="https://example.com"
145 - viewport={FILL_PREVIEW_VIEWPORT}
146 - pictureInPicture={false}
147 - profileId="work"
148 - zoomFactor={1.25}
149 - />,
150 - ),
142 + await using screen = await renderHost(
143 + <HostedBrowserWebview
144 + threadRef={threadRef}
145 + tabId="server-tab"
146 + runtimeTabId={runtimeTabId}
147 + initialUrl="https://example.com"
148 + viewport={FILL_PREVIEW_VIEWPORT}
149 + pictureInPicture={false}
150 + profileId="work"
151 + zoomFactor={1.25}
152 + />,
153 );
154
155 expect(mocks.getClientSettings).toHaveBeenCalledOnce();
@@ -211,41 +213,48 @@ describe("HostedBrowserWebview viewport layout", () => {
213 const owner = Symbol("panel");
214 const panel = { x: 0, y: 0, width: 2000, height: 1600 };
215
216 + const webview = (viewport: PreviewViewportSetting) => (
217 + <HostedBrowserWebview
218 + threadRef={{
219 + environmentId: EnvironmentId.make("zoom-layout"),
220 + threadId: ThreadId.make("zoom-layout"),
221 + }}
222 + tabId="zoom-layout"
223 + runtimeTabId={runtimeTabId}
224 + initialUrl="about:blank"
225 + viewport={viewport}
226 + pictureInPicture={false}
227 + profileId={undefined}
228 + zoomFactor={1.5}
229 + />
230 + );
231 +
232 async function renderViewport(viewport: PreviewViewportSetting) {
233 mocks.getClientSettings.mockResolvedValue({
234 ...DEFAULT_CLIENT_SETTINGS,
235 browserDefaultZoomFactor: 1.5,
236 });
219 - root ??= createRoot(container);
220 - await act(async () => {
221 - await ensureClientSettingsHydrated();
222 - root!.render(
223 - <HostedBrowserWebview
224 - threadRef={{
225 - environmentId: EnvironmentId.make("zoom-layout"),
226 - threadId: ThreadId.make("zoom-layout"),
227 - }}
228 - tabId="zoom-layout"
229 - runtimeTabId={runtimeTabId}
230 - initialUrl="about:blank"
231 - viewport={viewport}
232 - pictureInPicture={false}
233 - profileId={undefined}
234 - zoomFactor={1.5}
235 - />,
236 - );
237 - });
238 - const guest = container.querySelector("webview");
237 + await act(() => ensureClientSettingsHydrated());
238 + await using stack = new AsyncDisposableStack();
239 + const screen = stack.use(await renderHost(webview(viewport)));
240 + const guest = screen.container.querySelector("webview");
241 expect(guest).not.toBeNull();
240 - return guest!;
242 + const environment = stack.move();
243 + return Object.assign(screen, {
244 + guest: guest!,
245 + setViewport: (next: PreviewViewportSetting) => screen.rerender(webview(next)),
246 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
247 + });
248 }
249
250 it("keeps fixed viewports sized in guest pixels across host zoom and fitted surfaces", async () => {
251 + using _setup = setup();
252 let windowZoom = 1.25;
245 - vi.stubGlobal("desktopBridge", { getWindowZoomFactor: () => windowZoom });
253 + using _bridge = stubGlobal("desktopBridge", { getWindowZoomFactor: () => windowZoom });
254 useBrowserSurfaceStore.getState().claim(runtimeTabId, owner, false);
255 useBrowserSurfaceStore.getState().present(runtimeTabId, owner, panel, true, 0, 30);
248 - const guest = await renderViewport({ _tag: "freeform", width: 800, height: 600 });
256 + await using screen = await renderViewport({ _tag: "freeform", width: 800, height: 600 });
257 + const { guest } = screen;
258 expect(guest.getBoundingClientRect()).toMatchObject({ width: 960, height: 720 });
259
260 windowZoom = 0.75;
@@ -258,7 +267,7 @@ describe("HostedBrowserWebview viewport layout", () => {
267
268 windowZoom = 1.25;
269 await act(() => window.dispatchEvent(new Event("resize")));
261 - await renderViewport({ _tag: "preset", presetId: "iphone-se", width: 375, height: 667 });
270 + await screen.setViewport({ _tag: "preset", presetId: "iphone-se", width: 375, height: 667 });
271 expect(guest.getBoundingClientRect().width).toBe(450);
272 expect(guest.getBoundingClientRect().height).toBeCloseTo(800.4, 1);
273
@@ -278,7 +287,7 @@ describe("HostedBrowserWebview viewport layout", () => {
287 useBrowserSurfaceStore.getState().claim(runtimeTabId, owner, false);
288 useBrowserSurfaceStore.getState().present(runtimeTabId, owner, panel, true, 0, 30);
289 });
281 - await renderViewport(FILL_PREVIEW_VIEWPORT);
290 + await screen.setViewport(FILL_PREVIEW_VIEWPORT);
291 expect(guest.getBoundingClientRect()).toMatchObject({ width: 2000, height: 1600 });
292 expect(mocks.createTab).toHaveBeenCalledExactlyOnceWith(runtimeTabId, {
293 zoomFactor: 1.5,
@@ -287,11 +296,14 @@ describe("HostedBrowserWebview viewport layout", () => {
296 });
297
298 it("preserves preview scaling with an older bridge or no desktop bridge", async () => {
290 - vi.stubGlobal("desktopBridge", {});
291 - const guest = await renderViewport({ _tag: "freeform", width: 800, height: 600 });
299 + using _setup = setup();
300 + using _bridge = stubGlobal("desktopBridge", {});
301 + await using screen = await renderViewport({ _tag: "freeform", width: 800, height: 600 });
302 + const { guest } = screen;
303 expect(guest.getBoundingClientRect()).toMatchObject({ width: 1200, height: 900 });
304
294 - vi.stubGlobal("desktopBridge", undefined);
305 + // `_bridge` puts the original back after the unmount, so the unmount still sees no bridge.
306 + Reflect.set(globalThis, "desktopBridge", undefined);
307 await act(() => window.dispatchEvent(new Event("resize")));
308 expect(guest.getBoundingClientRect()).toMatchObject({ width: 1200, height: 900 });
309 });
apps/web/src/cloud/useCloudLinkController.browser.test.tsx
+68 -56
@@ -6,9 +6,10 @@ import {
6 } from "@t3tools/contracts";
7 import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay";
8 import { AsyncResult } from "effect/reactivity";
9 -import { act, useLayoutEffect } from "react";
10 -import { createRoot, type Root } from "react-dom/client";
11 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
9 +import { useLayoutEffect } from "react";
10 +import { describe, expect, it, vi } from "vite-plus/test";
11 +
12 +import { act, render } from "../../test/render";
13
14 const testState = vi.hoisted(() => ({
15 scopes: new Set<string>(),
@@ -105,29 +106,38 @@ const linkedState: EnvironmentCloudLinkStateResult = {
106 publishAgentActivity: false,
107 };
108
108 -let root: Root | null = null;
109 -let controller: ReturnType<typeof useCloudLinkController> | null = null;
109 +type Controller = ReturnType<typeof useCloudLinkController>;
110
111 -function ControllerProbe() {
111 +function ControllerProbe({ onRender }: { onRender: (controller: Controller) => void }) {
112 const value = useCloudLinkController();
113 useLayoutEffect(() => {
114 - controller = value;
114 + onRender(value);
115 });
116 return null;
117 }
118
119 async function mountController() {
120 - root = createRoot(document.createElement("div"));
121 - await act(async () => root!.render(<ControllerProbe />));
122 -}
123 -
124 -async function reconcile(desired: CloudLinkDesiredState) {
125 - let succeeded = false;
126 - await act(async () => {
127 - if (controller === null) throw new Error("Controller is not mounted.");
128 - succeeded = await controller.reconcileCloudState(desired);
120 + let controller: Controller | null = null;
121 + const screen = await render(
122 + <ControllerProbe
123 + onRender={(value) => {
124 + controller = value;
125 + }}
126 + />,
127 + );
128 + return Object.assign(screen, {
129 + get controller() {
130 + return controller;
131 + },
132 + async reconcile(desired: CloudLinkDesiredState) {
133 + let succeeded = false;
134 + await act(async () => {
135 + if (controller === null) throw new Error("Controller is not mounted.");
136 + succeeded = await controller.reconcileCloudState(desired);
137 + });
138 + return succeeded;
139 + },
140 });
130 - return succeeded;
141 }
142
143 function expectNoMutations() {
@@ -136,9 +146,7 @@ function expectNoMutations() {
146 expect(testState.preferences).not.toHaveBeenCalled();
147 }
148
139 -beforeEach(() => {
140 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
141 - vi.spyOn(console, "error").mockImplementation(() => undefined);
149 +function setup() {
150 testState.scopes = new Set([AuthRelayReadScope, AuthRelayWriteScope]);
151 testState.snapshot = linkedState;
152 testState.renderedSnapshot = linkedState;
@@ -154,34 +162,29 @@ beforeEach(() => {
162 }
163 testState.refreshLink.mockReset();
164 testState.toast.mockReset();
157 -});
158 -
159 -afterEach(async () => {
160 - await act(async () => root?.unmount());
161 - root = null;
162 - controller = null;
163 - vi.restoreAllMocks();
164 - vi.unstubAllGlobals();
165 -});
165 + return vi.spyOn(console, "error").mockImplementation(() => undefined);
166 +}
167
168 describe("useCloudLinkController", () => {
169 it.each([AuthRelayReadScope, AuthRelayWriteScope])(
170 "does not mutate without %s, even with a cached link snapshot",
171 async (scope) => {
171 - await mountController();
172 + using _setup = setup();
173 + await using screen = await mountController();
174 testState.scopes.delete(scope);
175
174 - expect(await reconcile({ managedTunnel: true, publish: true })).toBe(false);
176 + expect(await screen.reconcile({ managedTunnel: true, publish: true })).toBe(false);
177 expect(testState.getToken).not.toHaveBeenCalled();
178 expectNoMutations();
179 },
180 );
181
182 it("does not interpret unavailable link state as an unlinked environment", async () => {
183 + using _setup = setup();
184 testState.snapshot = null;
182 - await mountController();
185 + await using screen = await mountController();
186
184 - expect(await reconcile({ managedTunnel: false, publish: true })).toBe(false);
187 + expect(await screen.reconcile({ managedTunnel: false, publish: true })).toBe(false);
188 expect(testState.getToken).not.toHaveBeenCalled();
189 expectNoMutations();
190 });
@@ -189,38 +192,41 @@ describe("useCloudLinkController", () => {
192 it.each([AuthRelayReadScope, AuthRelayWriteScope])(
193 "rechecks %s after requesting the cloud token",
194 async (scope) => {
192 - await mountController();
195 + using _setup = setup();
196 + await using screen = await mountController();
197 testState.getToken.mockImplementationOnce(async () => {
198 testState.scopes.delete(scope);
199 return "clerk-token";
200 });
201
198 - expect(await reconcile({ managedTunnel: false, publish: false })).toBe(false);
202 + expect(await screen.reconcile({ managedTunnel: false, publish: false })).toBe(false);
203 expectNoMutations();
204 },
205 );
206
207 it("stops if the link-state read fails while requesting the cloud token", async () => {
204 - await mountController();
208 + using _setup = setup();
209 + await using screen = await mountController();
210 testState.getToken.mockImplementationOnce(async () => {
211 testState.snapshot = null;
212 return "clerk-token";
213 });
214
210 - expect(await reconcile({ managedTunnel: true, publish: true })).toBe(false);
215 + expect(await screen.reconcile({ managedTunnel: true, publish: true })).toBe(false);
216 expectNoMutations();
217 });
218
219 it("uses the latest linked mode to change publishing without replacing the tunnel", async () => {
220 + using _setup = setup();
221 testState.snapshot = { ...linkedState, linked: false, managedTunnelActive: false };
222 testState.renderedSnapshot = testState.snapshot;
217 - await mountController();
223 + await using screen = await mountController();
224 testState.getToken.mockImplementationOnce(async () => {
225 testState.snapshot = linkedState;
226 return "clerk-token";
227 });
228
223 - expect(await reconcile({ managedTunnel: true, publish: true })).toBe(true);
229 + expect(await screen.reconcile({ managedTunnel: true, publish: true })).toBe(true);
230 expect(testState.link).not.toHaveBeenCalled();
231 expect(testState.unlink).not.toHaveBeenCalled();
232 expect(testState.preferences).toHaveBeenCalledExactlyOnceWith({
@@ -230,12 +236,13 @@ describe("useCloudLinkController", () => {
236 });
237
238 it("shows a link the relay holds as publish-only as off and relinks it as managed", async () => {
239 + using _setup = setup();
240 testState.relayProviderKind = "manual";
234 - await mountController();
241 + await using screen = await mountController();
242
236 - expect(controller?.managedTunnelActive).toBe(false);
237 - expect(controller?.managedTunnelOutOfSync).toBe(true);
238 - expect(await reconcile({ managedTunnel: true, publish: false })).toBe(true);
243 + expect(screen.controller?.managedTunnelActive).toBe(false);
244 + expect(screen.controller?.managedTunnelOutOfSync).toBe(true);
245 + expect(await screen.reconcile({ managedTunnel: true, publish: false })).toBe(true);
246 expect(testState.link).toHaveBeenCalledExactlyOnceWith({
247 target,
248 clerkToken: "clerk-token",
@@ -244,17 +251,18 @@ describe("useCloudLinkController", () => {
251 });
252
253 it("shows a revoked link as off and links it again when turned on", async () => {
254 + using _setup = setup();
255 testState.snapshot = { ...linkedState, linkRevoked: true };
256 testState.renderedSnapshot = testState.snapshot;
249 - await mountController();
250 - expect(controller).toMatchObject({
257 + await using screen = await mountController();
258 + expect(screen.controller).toMatchObject({
259 linked: false,
260 linkRevoked: true,
261 managedTunnelActive: false,
262 managedTunnelOutOfSync: false,
263 });
264
257 - expect(await reconcile({ managedTunnel: true, publish: false })).toBe(true);
265 + expect(await screen.reconcile({ managedTunnel: true, publish: false })).toBe(true);
266 expect(testState.link).toHaveBeenCalledExactlyOnceWith({
267 target,
268 clerkToken: "clerk-token",
@@ -263,46 +271,50 @@ describe("useCloudLinkController", () => {
271 });
272
273 it("keeps a managed link that the relay also holds as managed", async () => {
274 + using _setup = setup();
275 testState.relayProviderKind = "cloudflare_tunnel";
267 - await mountController();
276 + await using screen = await mountController();
277
269 - expect(controller?.managedTunnelActive).toBe(true);
270 - expect(controller?.managedTunnelOutOfSync).toBe(false);
271 - expect(await reconcile({ managedTunnel: true, publish: false })).toBe(true);
278 + expect(screen.controller?.managedTunnelActive).toBe(true);
279 + expect(screen.controller?.managedTunnelOutOfSync).toBe(false);
280 + expect(await screen.reconcile({ managedTunnel: true, publish: false })).toBe(true);
281 expect(testState.link).not.toHaveBeenCalled();
282 });
283
284 it("stops the preference write if management permission is lost after linking", async () => {
276 - await mountController();
285 + using _setup = setup();
286 + await using screen = await mountController();
287 testState.link.mockImplementationOnce(async () => {
288 testState.scopes.delete(AuthRelayWriteScope);
289 return AsyncResult.success({});
290 });
291
282 - expect(await reconcile({ managedTunnel: false, publish: true })).toBe(false);
292 + expect(await screen.reconcile({ managedTunnel: false, publish: true })).toBe(false);
293 expect(testState.link).toHaveBeenCalledOnce();
294 expect(testState.preferences).not.toHaveBeenCalled();
295 expect(testState.refreshLink).toHaveBeenCalledOnce();
296 });
297
298 it("still lets an authorized user unlink when the cloud token is unavailable", async () => {
289 - await mountController();
299 + using _setup = setup();
300 + await using screen = await mountController();
301 testState.getToken.mockRejectedValueOnce(new Error("Cloud sign-in unavailable"));
302
292 - expect(await reconcile({ managedTunnel: false, publish: false })).toBe(true);
303 + expect(await screen.reconcile({ managedTunnel: false, publish: false })).toBe(true);
304 expect(testState.unlink).toHaveBeenCalledExactlyOnceWith({ target, clerkToken: null });
305 expect(testState.link).not.toHaveBeenCalled();
306 expect(testState.preferences).not.toHaveBeenCalled();
307 });
308
309 it("unlinks if the link-state read fails while requesting the cloud token", async () => {
299 - await mountController();
310 + using _setup = setup();
311 + await using screen = await mountController();
312 testState.getToken.mockImplementationOnce(async () => {
313 testState.snapshot = null;
314 throw new Error("Cloud sign-in unavailable");
315 });
316
305 - expect(await reconcile({ managedTunnel: false, publish: false })).toBe(true);
317 + expect(await screen.reconcile({ managedTunnel: false, publish: false })).toBe(true);
318 expect(testState.unlink).toHaveBeenCalledExactlyOnceWith({ target, clerkToken: null });
319 expect(testState.link).not.toHaveBeenCalled();
320 expect(testState.preferences).not.toHaveBeenCalled();
apps/web/src/components/BranchToolbar.panel.browser.test.tsx
+33 -49
@@ -1,10 +1,10 @@
1 import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
2 -import { act, type ComponentProps } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
2 +import type { ComponentProps } from "react";
3 +import { expect, it, vi } from "vite-plus/test";
4 import { page, userEvent } from "vite-plus/test/browser";
5
6 import "~/index.css";
7 +import { act, render as renderUi } from "../../test/render";
8
9 const state = vi.hoisted(() => ({
10 worktreePath: "/tmp/worktree" as string | null,
@@ -32,51 +32,36 @@ vi.mock(import("../state/entities"), async (original) => ({
32
33 import { BranchToolbar } from "./BranchToolbar";
34
35 -let root: Root;
36 -let container: HTMLDivElement;
37 -
38 -beforeEach(() => {
39 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
40 - state.worktreePath = "/tmp/worktree";
35 +function render(
36 + props: Partial<ComponentProps<typeof BranchToolbar>>,
37 + { worktreePath = "/tmp/worktree" }: { worktreePath?: string | null } = {},
38 +) {
39 + state.worktreePath = worktreePath;
40 state.showContextMenu.mockReset().mockResolvedValue("copy-path");
41 state.writeTextToClipboard.mockReset().mockResolvedValue(true);
43 - container = document.createElement("div");
44 - document.body.append(container);
45 - root = createRoot(container);
46 -});
47 -
48 -afterEach(async () => {
49 - await act(async () => root.unmount());
50 - container.remove();
51 - vi.unstubAllGlobals();
52 -});
53 -
54 -function render(props: Partial<ComponentProps<typeof BranchToolbar>>) {
55 - return act(async () =>
56 - root.render(
57 - <BranchToolbar
58 - layout="panel"
59 - panelSection="workspace"
60 - environmentId={EnvironmentId.make("local")}
61 - threadId={ThreadId.make("thread")}
62 - projectId={ProjectId.make("project")}
63 - worktreePath={state.worktreePath}
64 - isServerThread
65 - showGitControls
66 - envMode="local"
67 - envLocked={false}
68 - startFromOrigin={false}
69 - onStartFromOriginChange={vi.fn()}
70 - onEnvModeChange={vi.fn()}
71 - {...props}
72 - />,
73 - ),
42 + return renderUi(
43 + <BranchToolbar
44 + layout="panel"
45 + panelSection="workspace"
46 + environmentId={EnvironmentId.make("local")}
47 + threadId={ThreadId.make("thread")}
48 + projectId={ProjectId.make("project")}
49 + worktreePath={state.worktreePath}
50 + isServerThread
51 + showGitControls
52 + envMode="local"
53 + envLocked={false}
54 + startFromOrigin={false}
55 + onStartFromOriginChange={vi.fn()}
56 + onEnvModeChange={vi.fn()}
57 + {...props}
58 + />,
59 );
60 }
61
62 it("keeps machine choices usable when the combined row's workspace is locked", async () => {
63 const onEnvironmentChange = vi.fn();
79 - await render({
64 + await using screen = await render({
65 onEnvironmentChange,
66 availableEnvironments: ["local", "remote"].map((id) => ({
67 environmentId: EnvironmentId.make(id),
@@ -86,9 +71,9 @@ it("keeps machine choices usable when the combined row's workspace is locked", a
71 machine: "server",
72 })),
73 });
89 - const trigger = container.querySelector("button")!;
74 + const trigger = screen.container.querySelector("button")!;
75 expect(trigger.textContent).toBe("local");
91 - expect(container.querySelectorAll("button")).toHaveLength(1);
76 + expect(screen.container.querySelectorAll("button")).toHaveLength(1);
77
78 // A ctrl-click is a macOS secondary click; it must not open the menu.
79 await act(async () => {
@@ -105,7 +90,7 @@ it("keeps machine choices usable when the combined row's workspace is locked", a
90 });
91
92 it("shows a started thread's primary machine as a static label in the composer", async () => {
108 - await render({
93 + await using screen = await render({
94 layout: "composer",
95 showGitControls: false,
96 availableEnvironments: ["local", "remote"].map((id) => ({
@@ -116,8 +101,8 @@ it("shows a started thread's primary machine as a static label in the composer",
101 machine: "server",
102 })),
103 });
119 - expect(container.textContent).toBe("local");
120 - expect(container.querySelector("button")).toBeNull();
104 + expect(screen.container.textContent).toBe("local");
105 + expect(screen.container.querySelector("button")).toBeNull();
106 });
107
108 it.each([
@@ -128,11 +113,10 @@ it.each([
113 ] as const)(
114 "copies only an existing workspace path with mode %s and worktree %s",
115 async (envMode, worktreePath, copiedPath) => {
131 - state.worktreePath = worktreePath;
132 - await render({ envMode });
116 + await using screen = await render({ envMode }, { worktreePath });
117 const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });
118 await act(async () => {
135 - container.querySelector('[aria-label="Run context"]')!.dispatchEvent(event);
119 + screen.container.querySelector('[aria-label="Run context"]')!.dispatchEvent(event);
120 });
121 expect(event.defaultPrevented).toBe(copiedPath !== null);
122 if (copiedPath === null) {
apps/web/src/components/ChatMarkdown.assets.browser.test.tsx
+45 -59
@@ -12,9 +12,10 @@ import * as Effect from "effect/Effect";
12 import * as Cause from "effect/Cause";
13 import * as Schema from "effect/Schema";
14 import { AtomRegistry } from "effect/reactivity";
15 -import { act, type ReactNode } from "react";
16 -import { createRoot, type Root } from "react-dom/client";
17 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
15 +import type { ReactNode } from "react";
16 +import { expect, it, vi } from "vite-plus/test";
17 +
18 +import { act, render } from "../../test/render";
19
20 const mint = vi.hoisted(() => vi.fn<() => Promise<AssetCreateUrlResult>>());
21 const remoteOpen = vi.hoisted(() => ({
@@ -87,9 +88,6 @@ vi.mock(import("../remoteOpen"), async (original) => ({
88 import ChatMarkdown from "./ChatMarkdown";
89 import { toastManager } from "./ui/toast";
90
90 -const roots: Root[] = [];
91 -let registry: AtomRegistry.AtomRegistry;
92 -
91 const imageUrl = (version: string) =>
92 `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>#${version}`;
93 const assetResult = (version: string): AssetCreateUrlResult => ({
@@ -97,22 +95,15 @@ const assetResult = (version: string): AssetCreateUrlResult => ({
95 expiresAt: 1,
96 });
97
100 -beforeEach(() => {
101 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
102 - registry = AtomRegistry.make();
98 +function setup() {
99 mint.mockReset().mockResolvedValue(assetResult("updated"));
104 -});
105 -afterEach(async () => {
106 - for (const root of roots.splice(0)) await act(async () => root.unmount());
107 - registry.dispose();
108 - document.body.replaceChildren();
100 remoteOpen.isResolved = true;
101 remoteOpen.state.mode = "local-exec";
102 remoteOpen.label = "media-host";
103 remoteOpen.httpBaseUrl = "https://host.test";
113 - vi.restoreAllMocks();
114 - vi.unstubAllGlobals();
115 -});
104 + const registry = AtomRegistry.make();
105 + return { registry, [Symbol.dispose]: () => registry.dispose() };
106 +}
107
108 function deferred<T>() {
109 let resolve!: (value: T) => void;
@@ -124,27 +115,21 @@ function deferred<T>() {
115 return { promise, resolve, reject };
116 }
117
127 -function createTestRoot() {
128 - const container = document.body.appendChild(document.createElement("div"));
129 - const root = createRoot(container);
130 - roots.push(root);
131 - return {
132 - container,
133 - render: (children: ReactNode) =>
134 - act(async () => {
135 - root.render(
136 - <RegistryContext.Provider value={registry}>{children}</RegistryContext.Provider>,
137 - );
138 - }),
139 - };
118 +async function renderInRegistry(registry: AtomRegistry.AtomRegistry, ui: ReactNode) {
119 + const wrap = (node: ReactNode) => (
120 + <RegistryContext.Provider value={registry}>{node}</RegistryContext.Provider>
121 + );
122 + const screen = await render(wrap(ui));
123 + return Object.assign(screen, { update: (node: ReactNode) => screen.rerender(wrap(node)) });
124 }
125
126 it("opens host media through server authorization before the client grant loads", async () => {
127 + using env = setup();
128 mint.mockResolvedValue({ relativeUrl: "/api/assets/image.png", expiresAt: 1 });
129 const expanded = deferred<unknown>();
130 const onImageExpand = vi.fn(expanded.resolve);
146 - const { container, render } = createTestRoot();
147 - await render(
131 + await using screen = await renderInRegistry(
132 + env.registry,
133 <ChatMarkdown
134 cwd="/repo"
135 threadRef={{
@@ -155,7 +140,7 @@ it("opens host media through server authorization before the client grant loads"
140 onImageExpand={onImageExpand}
141 />,
142 );
158 - const link = container.querySelector<HTMLAnchorElement>('a[href="/tmp/image.png"]');
143 + const link = screen.container.querySelector<HTMLAnchorElement>('a[href="/tmp/image.png"]');
144 expect(link).not.toBeNull();
145 await act(async () => link!.click());
146 expect(await expanded.promise).toMatchObject({
@@ -190,6 +175,7 @@ it.each([
175 description: "Only images, videos, audio, HTML, and PDF files can be previewed.",
176 },
177 ])("reports the media failure for $name", async (scenario) => {
178 + using env = setup();
179 const lookup = deferred<AssetCreateUrlResult>();
180 const started = deferred<void>();
181 const reported = deferred<Parameters<typeof toastManager.add>[0]>();
@@ -197,17 +183,16 @@ it.each([
183 started.resolve();
184 return lookup.promise;
185 });
200 - vi.spyOn(toastManager, "add").mockImplementation((toast) => {
186 + using _toast = vi.spyOn(toastManager, "add").mockImplementation((toast) => {
187 reported.resolve(toast);
188 return "media-toast";
189 });
190 remoteOpen.isResolved = false;
205 - const { container, render } = createTestRoot();
191 const content = (
192 <ChatMarkdown cwd="/repo" threadRef={threadRef} text="[Open image](~/Downloads/image.png)" />
193 );
209 - await render(content);
210 - const link = container.querySelector<HTMLAnchorElement>('a[href="~/Downloads/image.png"]');
194 + await using screen = await renderInRegistry(env.registry, content);
195 + const link = screen.container.querySelector<HTMLAnchorElement>('a[href="~/Downloads/image.png"]');
196 expect(link).not.toBeNull();
197 await act(async () => {
198 link!.click();
@@ -218,7 +203,7 @@ it.each([
203 remoteOpen.state.mode = scenario.local ? "local-exec" : "remote-unavailable";
204 remoteOpen.httpBaseUrl = scenario.local ? "http://localhost:3773" : "https://host.test";
205 remoteOpen.label = "settled-host";
221 - await render(content);
206 + await screen.update(content);
207 const resource = {
208 _tag: "media-file" as const,
209 path: "~/Downloads/image.png",
@@ -258,33 +243,33 @@ function renderedImage(container: HTMLElement) {
243 }
244
245 it("ordinary chat keeps its embedded asset URL across renders and reopening", async () => {
261 - const { container, render } = createTestRoot();
262 - await render(markdown());
263 - expect(renderedImage(container)).toBe(imageUrl("updated"));
246 + using env = setup();
247 + await using screen = await renderInRegistry(env.registry, markdown());
248 + expect(renderedImage(screen.container)).toBe(imageUrl("updated"));
249 mint.mockResolvedValue(assetResult("changed"));
250
266 - await render(markdown());
267 - await render(null);
268 - await render(markdown());
251 + await screen.update(markdown());
252 + await screen.update(null);
253 + await screen.update(markdown());
254
270 - expect(renderedImage(container)).toBe(imageUrl("updated"));
255 + expect(renderedImage(screen.container)).toBe(imageUrl("updated"));
256 expect(mint).toHaveBeenCalledTimes(1);
257 });
258
259 it.each(["URL", "failure"] as const)(
260 "reopening a file preview with no workspace mutation replaces its cached %s",
261 async (cached) => {
262 + using env = setup();
263 if (cached === "failure") mint.mockRejectedValueOnce(new Error("Image missing"));
264 else mint.mockResolvedValueOnce(assetResult("stale"));
279 - const { container, render } = createTestRoot();
280 - await render(markdown(null));
281 - expect(renderedImage(container)).toBe(cached === "URL" ? imageUrl("stale") : undefined);
282 - await render(null);
265 + await using screen = await renderInRegistry(env.registry, markdown(null));
266 + expect(renderedImage(screen.container)).toBe(cached === "URL" ? imageUrl("stale") : undefined);
267 + await screen.update(null);
268
269 mint.mockResolvedValue(assetResult("updated"));
285 - await render(markdown(null));
270 + await screen.update(markdown(null));
271
287 - expect(renderedImage(container)).toBe(imageUrl("updated"));
272 + expect(renderedImage(screen.container)).toBe(imageUrl("updated"));
273 expect(mint).toHaveBeenCalledTimes(2);
274 },
275 );
@@ -292,21 +277,22 @@ it.each(["URL", "failure"] as const)(
277 it.each(["initial", "refresh"] as const)(
278 "shows the latest workspace edit after a pending %s asset request settles",
279 async (request) => {
280 + using env = setup();
281 let resolvePending!: (value: AssetCreateUrlResult) => void;
282 const pending = new Promise<AssetCreateUrlResult>((resolve) => {
283 resolvePending = resolve;
284 });
299 - const { container, render } = createTestRoot();
285 + await using screen = await renderInRegistry(env.registry, null);
286 if (request === "refresh") {
301 - await render(markdown("m0"));
302 - expect(renderedImage(container)).toBe(imageUrl("updated"));
287 + await screen.update(markdown("m0"));
288 + expect(renderedImage(screen.container)).toBe(imageUrl("updated"));
289 }
290
291 mint.mockReturnValueOnce(pending).mockResolvedValue(assetResult("latest"));
306 - await render(markdown("m1"));
292 + await screen.update(markdown("m1"));
293 const callsBeforeEdits = mint.mock.calls.length;
308 - await render(markdown("m2"));
309 - await render(markdown("m3"));
294 + await screen.update(markdown("m2"));
295 + await screen.update(markdown("m3"));
296 expect(mint).toHaveBeenCalledTimes(callsBeforeEdits);
297
298 await act(async () => {
@@ -314,9 +300,9 @@ it.each(["initial", "refresh"] as const)(
300 await pending;
301 });
302
317 - expect(renderedImage(container)).toBe(imageUrl("latest"));
303 + expect(renderedImage(screen.container)).toBe(imageUrl("latest"));
304 expect(mint).toHaveBeenCalledTimes(callsBeforeEdits + 1);
319 - await render(markdown("m3"));
305 + await screen.update(markdown("m3"));
306 expect(mint).toHaveBeenCalledTimes(callsBeforeEdits + 1);
307 },
308 );
apps/web/src/components/ChatMarkdown.browser.test.tsx
+267 -188
@@ -2,11 +2,11 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 import { searchableMessageSegments } from "@t3tools/shared/threadFindText";
3 import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
4 import { AsyncResult } from "effect/reactivity";
5 -import { act, useEffect, type ReactElement } from "react";
6 -import { createRoot, type Root } from "react-dom/client";
7 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5 +import { useEffect, type ReactElement } from "react";
6 +import { describe, expect, it, vi } from "vite-plus/test";
7 import { page, userEvent } from "vite-plus/test/browser";
8
9 +import { act, render, stubGlobal } from "../../test/render";
10 import "../index.css";
11 import { useTheme } from "../hooks/useTheme";
12 import { applyThemeColorPreview, getStandardThemeColors } from "../themePalette";
@@ -86,37 +86,15 @@ import ChatMarkdown from "./ChatMarkdown";
86 import { serializeTableElementToCsv, chatMarkdownClipboardPayload } from "../markdown-clipboard";
87 import { captureAssistantTextSelection } from "../lib/assistantTextSelection";
88
89 -const roots: Root[] = [];
90 -
91 -beforeEach(() => {
89 +function setup() {
90 settingsOverrides.mathRenderingEnabled = false;
91 renderDiagram.mockReset();
92 workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
93 filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] }));
96 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
97 -});
98 -
99 -afterEach(async () => {
100 - for (const root of roots.splice(0)) await act(async () => root.unmount());
101 - document.body.replaceChildren();
102 - CSS.highlights.clear();
103 - vi.restoreAllMocks();
104 - vi.unstubAllGlobals();
105 -});
106 -
107 -async function render(element: ReactElement) {
108 - const container = document.body.appendChild(document.createElement("div"));
109 - const root = createRoot(container);
110 - roots.push(root);
111 - await act(async () => root.render(element));
112 - return {
113 - container,
114 - rerender: (next: ReactElement) => act(async () => root.render(next)),
115 - };
94 }
95
118 -async function renderText(text: string, props: Partial<Parameters<typeof ChatMarkdown>[0]> = {}) {
119 - return (await render(<ChatMarkdown cwd="/tmp/project" text={text} {...props} />)).container;
96 +function renderText(text: string, props: Partial<Parameters<typeof ChatMarkdown>[0]> = {}) {
97 + return render(<ChatMarkdown cwd="/tmp/project" text={text} {...props} />);
98 }
99
100 function linkTexts(container: HTMLElement) {
@@ -136,16 +114,10 @@ function fileOptions(container: HTMLElement) {
114 }
115
116 describe("ChatMarkdown theme drafts", () => {
139 - afterEach(() => {
140 - act(() => {
141 - localStorage.clear();
142 - window.dispatchEvent(new StorageEvent("storage", { key: null }));
143 - });
144 - });
145 -
117 it.each(["dark", "light"] as const)(
118 "previews opposite syntax colors and restores saved %s colors on cancel",
119 async (savedAppearance) => {
120 + setup();
121 let selection: ReturnType<typeof useTheme>;
122 function Preview() {
123 const theme = useTheme();
@@ -155,7 +127,15 @@ describe("ChatMarkdown theme drafts", () => {
127 return <ChatMarkdown cwd={undefined} text={"```typescript\nconst answer = 42;\n```"} />;
128 }
129 await getSyntaxHighlighterPromise("typescript");
158 - const { container } = await render(<Preview />);
130 + await using screen = await render(<Preview />);
131 + // Disposed before the unmount, while useTheme still listens for the storage event.
132 + using _storage = {
133 + [Symbol.dispose]() {
134 + localStorage.clear();
135 + window.dispatchEvent(new StorageEvent("storage", { key: null }));
136 + },
137 + };
138 + const { container } = screen;
139 await act(async () => {
140 selection.setTheme(savedAppearance);
141 selection.setAppearanceMode(savedAppearance);
@@ -199,7 +179,8 @@ describe("ChatMarkdown table layout", () => {
179 ])(
180 "wraps expanded cells with fit=$fits in a $width rem container (timeline=$timeline)",
181 async ({ width, timeline, fits }) => {
202 - const { container } = await render(
182 + setup();
183 + await using screen = await render(
184 <div style={{ width: `${width}rem` }}>
185 <div className={timeline ? "@container/chat-lane chat-content-lane overflow-x-clip" : ""}>
186 <ChatMarkdown
@@ -213,6 +194,7 @@ describe("ChatMarkdown table layout", () => {
194 </div>
195 </div>,
196 );
197 + const { container } = screen;
198 const table = container.querySelector("table")!;
199 const viewport = table.closest<HTMLElement>('[data-slot="scroll-area-viewport"]')!;
200 const cell = table.tBodies[0]!.rows[0]!.cells[0]!;
@@ -252,9 +234,11 @@ describe("ChatMarkdown bare anchor placeholders", () => {
234 it.each(["<A>", "<a>", "<a >", "<a/>", "<A/>", "<a />"])(
235 "preserves unmatched %s without linking later blocks",
236 async (token) => {
255 - const container = await renderText(
237 + setup();
238 + await using screen = await renderText(
239 `- **"From ${token}"** appears in the header.\n\n- **Tests:** cover inheritance.\n\nThe deferred move continues on B.\n\nSee <a href="https://example.com">the link</a>.`,
240 );
241 + const { container } = screen;
242 expect(container.querySelector("strong")?.textContent).toBe(`"From ${token}"`);
243 expect(linkTexts(container)).toEqual(["the link"]);
244 expect(container.querySelectorAll("li")).toHaveLength(2);
@@ -267,29 +251,37 @@ describe("ChatMarkdown bare anchor placeholders", () => {
251 it.each(["</a> ", "<div>more</div>\n</a>"])(
252 "preserves a paired anchor closing in the raw block %s",
253 async (closing) => {
270 - const container = await renderText(`See <a>label\n\n${closing}\n\nfinish`);
254 + setup();
255 + await using screen = await renderText(`See <a>label\n\n${closing}\n\nfinish`);
256 + const { container } = screen;
257 expect(container.querySelector("p")?.textContent).toBe("See label");
258 },
259 );
260
261 it("preserves a paired anchor after comment-looking raw text", async () => {
276 - const container = await renderText("See <a>label<script><!-- </script> --></a>");
262 + setup();
263 + await using screen = await renderText("See <a>label<script><!-- </script> --></a>");
264 + const { container } = screen;
265 expect(container.querySelector("p")?.textContent).toBe("See label -->");
266 });
267
268 it.each(["<!-- </a> -->", '<div title="</a>">more</div>', '<script>"</a>"</script>'])(
269 "ignores apparent closing anchors inside %s",
270 async (html) => {
283 - const container = await renderText(`Before <A>.\n\n${html}\n\nAfter.`);
271 + setup();
272 + await using screen = await renderText(`Before <A>.\n\n${html}\n\nAfter.`);
273 + const { container } = screen;
274 expect(container.querySelector("p")?.textContent).toBe("Before <A>.");
275 expect(container.querySelectorAll("a")).toHaveLength(0);
276 },
277 );
278
279 it("preserves paired HTML anchors, details, markdown links, and inline code", async () => {
290 - const container = await renderText(
280 + setup();
281 + await using screen = await renderText(
282 'Bare <a>label</a>, <a id="section"></a>, `<A>`, and [docs](https://example.com).\n\n<details><summary>More</summary>Details</details>',
283 );
284 + const { container } = screen;
285 expect(linkTexts(container)).toEqual(["label", "", "docs"]);
286 expect(container.querySelector("code")?.textContent).toBe("<A>");
287 expect(container.querySelector("[data-markdown-details]")?.textContent).toContain("More");
@@ -298,6 +290,7 @@ describe("ChatMarkdown bare anchor placeholders", () => {
290
291 describe("ChatMarkdown Mermaid streaming", () => {
292 it("reveals a completed fence while streaming and preserves it through later prose and stream end", async () => {
293 + setup();
294 let finishRender!: (label: string) => void;
295 renderDiagram.mockReturnValue(
296 new Promise<string>((resolve) => {
@@ -310,7 +303,8 @@ describe("ChatMarkdown Mermaid streaming", () => {
303 const message = (text: string, isStreaming = true) => (
304 <ChatMarkdown cwd={undefined} text={text} isStreaming={isStreaming} />
305 );
313 - const { container, rerender } = await render(message(open));
306 + await using screen = await render(message(open));
307 + const { container, rerender } = screen;
308 expect(container.querySelector("pre")?.textContent).toContain(source);
309 expect(renderDiagram).not.toHaveBeenCalled();
310
@@ -353,8 +347,10 @@ describe("ChatMarkdown Mermaid streaming", () => {
347 "\n ```",
348 ],
349 ])("keeps a %s in source until a real closer arrives", async (_, open, closing) => {
350 + setup();
351 const message = (text: string) => <ChatMarkdown cwd={undefined} text={text} isStreaming />;
357 - const { container, rerender } = await render(message(open));
352 + await using screen = await render(message(open));
353 + const { container, rerender } = screen;
354 expect(renderDiagram).not.toHaveBeenCalled();
355 expect(container.querySelector("pre")?.textContent).toContain("A --> B");
356
@@ -363,9 +359,11 @@ describe("ChatMarkdown Mermaid streaming", () => {
359 });
360
361 it("does not mistake a CRLF stream cut after CR for a closed fence", async () => {
362 + setup();
363 const open = "```mermaid\r\nflowchart LR\r\nA --> B\r\n\t```";
364 const message = (text: string) => <ChatMarkdown cwd={undefined} text={text} isStreaming />;
368 - const { container, rerender } = await render(message(open));
365 + await using screen = await render(message(open));
366 + const { container, rerender } = screen;
367 expect(renderDiagram).not.toHaveBeenCalled();
368 await rerender(message(`${open}\r`));
369 expect(renderDiagram).not.toHaveBeenCalled();
@@ -376,12 +374,16 @@ describe("ChatMarkdown Mermaid streaming", () => {
374 });
375
376 it("falls back to source when a completed diagram fails during streaming", async () => {
377 + setup();
378 await getSyntaxHighlighterPromise("mermaid");
379 renderDiagram.mockImplementation(() => {
380 throw new Error("Invalid Mermaid diagram");
381 });
383 - vi.spyOn(console, "error").mockImplementation(() => {});
384 - const container = await renderText("```mermaid\ninvalid diagram\n```", { isStreaming: true });
382 + using _consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
383 + await using screen = await renderText("```mermaid\ninvalid diagram\n```", {
384 + isStreaming: true,
385 + });
386 + const { container } = screen;
387 expect(renderDiagram).toHaveBeenCalledWith(expect.stringContaining("invalid diagram"));
388 expect(container.querySelector('svg[role="img"]')).toBeNull();
389 expect(container.querySelector("pre")?.textContent).toContain("invalid diagram");
@@ -391,9 +393,10 @@ describe("ChatMarkdown Mermaid streaming", () => {
393
394 describe("ChatMarkdown context references", () => {
395 it("renders text and image references through the chip renderer, with readable fallback", async () => {
396 + setup();
397 const text =
398 "See [Terminal output](t3-context://v1/terminal/term-1) and ![Error image](t3-context://v1/image/img-1).";
396 - const { container, rerender } = await render(
399 + await using screen = await render(
400 <ChatMarkdown
401 cwd={undefined}
402 text={text}
@@ -404,6 +407,7 @@ describe("ChatMarkdown context references", () => {
407 )}
408 />,
409 );
410 + const { container, rerender } = screen;
411 expect([...container.querySelectorAll("button")].map((button) => button.textContent)).toEqual([
412 "terminal: Terminal output",
413 "image: Error image",
@@ -415,8 +419,9 @@ describe("ChatMarkdown context references", () => {
419 });
420
421 it("reads formatted context labels through nested markup instead of the context id", async () => {
422 + setup();
423 const seen: Array<string> = [];
419 - await render(
424 + await using _screen = await render(
425 <ChatMarkdown
426 cwd={undefined}
427 text="See [**Bold** `code`](t3-context://v1/terminal/term-1)."
@@ -432,8 +437,10 @@ describe("ChatMarkdown context references", () => {
437
438 describe("ChatMarkdown favicon privacy", () => {
439 it("suppresses private link images while preserving public links across updates", async () => {
440 + setup();
441 const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
436 - const { container, rerender } = await render(markdown("https://example.com"));
442 + await using screen = await render(markdown("https://example.com"));
443 + const { container, rerender } = screen;
444 expect([...container.querySelectorAll("img")].map((image) => image.src)).toEqual([
445 "https://www.google.com/s2/favicons?domain=example.com&sz=32",
446 ]);
@@ -451,6 +458,7 @@ describe("ChatMarkdown favicon privacy", () => {
458
459 describe("ChatMarkdown streaming", () => {
460 it("runs only a complete single-line shell block after a click", async () => {
461 + setup();
462 const onRunShellCommand = vi.fn();
463 const message = (text: string, isStreaming = false) => (
464 <ChatMarkdown
@@ -460,7 +468,8 @@ describe("ChatMarkdown streaming", () => {
468 onRunShellCommand={onRunShellCommand}
469 />
470 );
463 - const { container, rerender } = await render(message("```bash\necho hello\n```", true));
471 + await using screen = await render(message("```bash\necho hello\n```", true));
472 + const { container, rerender } = screen;
473 const runButtons = () => buttonsLabelled(container, "Run in terminal");
474 expect(runButtons()).toHaveLength(0);
475
@@ -497,10 +506,12 @@ describe("ChatMarkdown streaming", () => {
506 });
507
508 it("does not retokenize completed lines when streaming finishes", async () => {
509 + setup();
510 const highlighter = await getSyntaxHighlighterPromise("typescript");
501 - const highlight = vi.spyOn(highlighter, "codeToHast");
511 + using highlight = vi.spyOn(highlighter, "codeToHast");
512 const text = "```typescript\nconst completed = 1;\nconst current = 2;";
503 - const { rerender } = await render(<ChatMarkdown cwd="/tmp/project" text={text} isStreaming />);
513 + await using screen = await render(<ChatMarkdown cwd="/tmp/project" text={text} isStreaming />);
514 + const { rerender } = screen;
515 await vi.waitFor(() => expect(highlight).toHaveBeenCalled());
516 highlight.mockClear();
517 await rerender(<ChatMarkdown cwd="/tmp/project" text={text + "\n```"} />);
@@ -508,19 +519,21 @@ describe("ChatMarkdown streaming", () => {
519 });
520
521 it("recovers highlighting after a failed fence changes without resetting its controls", async () => {
522 + setup();
523 const highlighter = await getSyntaxHighlighterPromise("text");
524 const codeToHast = highlighter.codeToHast.bind(highlighter);
525 let fail = true;
514 - vi.spyOn(highlighter, "codeToHast").mockImplementation((...args) => {
526 + using _codeToHast = vi.spyOn(highlighter, "codeToHast").mockImplementation((...args) => {
527 if (fail) throw new Error("Temporary highlighter failure");
528 return codeToHast(...args);
529 });
518 - vi.spyOn(console, "error").mockImplementation(() => {});
519 - vi.spyOn(console, "warn").mockImplementation(() => {});
530 + using _consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
531 + using _consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => {});
532
521 - const { container, rerender } = await render(
533 + await using screen = await render(
534 <ChatMarkdown cwd="/tmp/project" text={"```text\ninitial\n```"} isStreaming />,
535 );
536 + const { container, rerender } = screen;
537 const codeBlock = container.querySelector<HTMLElement>('[data-language="text"]')!;
538 const initialWrap = codeBlock.dataset.wrap === "true";
539 await act(async () =>
@@ -540,9 +553,10 @@ describe("ChatMarkdown streaming", () => {
553 });
554
555 it("preserves code controls and details without highlighting an unchanged fence again", async () => {
556 + setup();
557 const highlighter = await getSyntaxHighlighterPromise("text");
544 - const highlight = vi.spyOn(highlighter, "codeToHast");
545 - const writeText = vi
558 + using highlight = vi.spyOn(highlighter, "codeToHast");
559 + using writeText = vi
560 .spyOn(navigator.clipboard, "writeText")
561 .mockImplementation(async () => undefined);
562 const text = [
@@ -559,9 +573,8 @@ describe("ChatMarkdown streaming", () => {
573 "Streaming reply",
574 ].join("\n");
575
562 - const { container, rerender } = await render(
563 - <ChatMarkdown cwd="/tmp/project" text={text} isStreaming />,
564 - );
576 + await using screen = await render(<ChatMarkdown cwd="/tmp/project" text={text} isStreaming />);
577 + const { container, rerender } = screen;
578 const codeBlock = container.querySelector<HTMLElement>('[data-language="text"]')!;
579 const initialWrap = codeBlock.dataset.wrap === "true";
580 await act(async () => {
@@ -603,6 +616,7 @@ describe("ChatMarkdown streaming", () => {
616 });
617
618 it("edits the current task text and marker after reusing a renderer", async () => {
619 + setup();
620 let editedText: string | undefined;
621 let rerender: (next: ReactElement) => Promise<void> = async () => {};
622 const message = (text: string): ReactElement => (
@@ -615,7 +629,7 @@ describe("ChatMarkdown streaming", () => {
629 }}
630 />
631 );
618 - const rendered = await render(message("- [ ] First\n- [ ] Second"));
632 + await using rendered = await render(message("- [ ] First\n- [ ] Second"));
633 rerender = rendered.rerender;
634 const { container } = rendered;
635 const checkboxes = () => container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
@@ -631,8 +645,10 @@ describe("ChatMarkdown streaming", () => {
645
646 describe("ChatMarkdown skill chips", () => {
647 it("updates digit-leading skill labels when discovered skills change", async () => {
648 + setup();
649 const text = "Use $2spec with a $20k budget.";
635 - const { container, rerender } = await render(<ChatMarkdown cwd="/tmp/project" text={text} />);
650 + await using screen = await render(<ChatMarkdown cwd="/tmp/project" text={text} />);
651 + const { container, rerender } = screen;
652 expect(container.textContent).not.toContain("2Spec");
653
654 await rerender(
@@ -674,6 +690,7 @@ describe("ChatMarkdown workspace file opens", () => {
690 ])(
691 "opens a repo-relative chip at its indexed path in $cwd",
692 async ({ cwd, path, indexedPath }) => {
693 + setup();
694 workspaceSearch.mockResolvedValue(
695 AsyncResult.success({
696 entries: [
@@ -683,10 +700,11 @@ describe("ChatMarkdown workspace file opens", () => {
700 truncated: false,
701 }),
702 );
686 - const openFile = vi
703 + using openFile = vi
704 .spyOn(useRightPanelStore.getState(), "openFile")
705 .mockImplementation(() => {});
689 - const container = await renderText(`[Notes](${path}:7)`, { cwd, threadRef });
706 + await using screen = await renderText(`[Notes](${path}:7)`, { cwd, threadRef });
707 + const { container } = screen;
708
709 await act(async () => container.querySelector("a")!.click());
710
@@ -695,6 +713,7 @@ describe("ChatMarkdown workspace file opens", () => {
713 );
714
715 it("prefers an existing literal nested file over the stripped Windows match", async () => {
716 + setup();
717 filesystemMetadata.mockResolvedValue(
718 AsyncResult.success({ entries: [{ kind: "file", byteLength: 10 }] }),
719 );
@@ -707,13 +726,14 @@ describe("ChatMarkdown workspace file opens", () => {
726 truncated: false,
727 }),
728 );
710 - const openFile = vi
729 + using openFile = vi
730 .spyOn(useRightPanelStore.getState(), "openFile")
731 .mockImplementation(() => {});
713 - const container = await renderText("[Notes](physics/notes/a.md)", {
732 + await using screen = await renderText("[Notes](physics/notes/a.md)", {
733 cwd: "C:/school/Physics",
734 threadRef,
735 });
736 + const { container } = screen;
737
738 await act(async () => container.querySelector("a")!.click());
739
@@ -721,6 +741,7 @@ describe("ChatMarkdown workspace file opens", () => {
741 });
742
743 it("keeps a literal file omitted by a truncated search", async () => {
744 + setup();
745 workspaceSearch.mockResolvedValue(
746 AsyncResult.success({
747 entries: [{ path: "notes/a.md", kind: "file" }],
@@ -730,13 +751,14 @@ describe("ChatMarkdown workspace file opens", () => {
751 filesystemMetadata.mockResolvedValue(
752 AsyncResult.success({ entries: [{ kind: "file", byteLength: 10 }] }),
753 );
733 - const openFile = vi
754 + using openFile = vi
755 .spyOn(useRightPanelStore.getState(), "openFile")
756 .mockImplementation(() => {});
736 - const container = await renderText("[Notes](physics/notes/a.md:7)", {
757 + await using screen = await renderText("[Notes](physics/notes/a.md:7)", {
758 cwd: "/school/physics",
759 threadRef,
760 });
761 + const { container } = screen;
762
763 await act(async () => container.querySelector("a")!.click());
764
@@ -757,20 +779,22 @@ describe("ChatMarkdown workspace file opens", () => {
779 ])(
780 "keeps the literal target for a $kind when only its stripped twin exists",
781 async ({ href, imageBaseDir }) => {
782 + setup();
783 workspaceSearch.mockResolvedValue(
784 AsyncResult.success({
785 entries: [{ path: "notes/a.md", kind: "file" }],
786 truncated: false,
787 }),
788 );
766 - const openFile = vi
789 + using openFile = vi
790 .spyOn(useRightPanelStore.getState(), "openFile")
791 .mockImplementation(() => {});
769 - const container = await renderText(`[Notes](${href})`, {
792 + await using screen = await renderText(`[Notes](${href})`, {
793 cwd: "/school/physics",
794 imageBaseDir,
795 threadRef,
796 });
797 + const { container } = screen;
798
799 await act(async () => container.querySelector("a")!.click());
800
@@ -781,6 +805,7 @@ describe("ChatMarkdown workspace file opens", () => {
805 );
806
807 it("keeps a newer absolute file open when an earlier repo-relative lookup finishes", async () => {
808 + setup();
809 const result = AsyncResult.success({
810 entries: [{ path: "notes/a.md", kind: "file" }],
811 truncated: false,
@@ -790,16 +815,17 @@ describe("ChatMarkdown workspace file opens", () => {
815 resolvePending = resolve;
816 });
817 workspaceSearch.mockReturnValueOnce(pending);
793 - const openFile = vi
818 + using openFile = vi
819 .spyOn(useRightPanelStore.getState(), "openFile")
820 .mockImplementation(() => {});
796 - const container = await renderText(
821 + await using screen = await renderText(
822 "[Notes](physics/notes/a.md) and [Other](/elsewhere/b.md:9)",
823 {
824 cwd: "/school/physics",
825 threadRef,
826 },
827 );
828 + const { container } = screen;
829 const [notes, other] = container.querySelectorAll("a");
830 await act(async () => notes!.click());
831 expect(workspaceSearch).toHaveBeenCalledOnce();
@@ -817,20 +843,24 @@ describe("ChatMarkdown file citations", () => {
843 it.each([true, false])(
844 "renders Codex file citations as file chips with parseRawHtml=%s",
845 async (parseRawHtml) => {
820 - const container = await renderText(
846 + setup();
847 + await using screen = await renderText(
848 'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx" purpose="output"}.',
849 { lineBreaks: !parseRawHtml, parseRawHtml },
850 );
851 + const { container } = screen;
852 expect(container.textContent).not.toContain("codex-file-citation");
853 expect(fileOptions(container)).toEqual(["File options for report.xlsx"]);
854 },
855 );
856
857 it("leaves an unfinished streaming citation visible until it is complete", async () => {
830 - const container = await renderText(
858 + setup();
859 + await using screen = await renderText(
860 'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"',
861 { isStreaming: true },
862 );
863 + const { container } = screen;
864 expect(container.textContent).toContain(":codex-file-citation");
865 expect(fileOptions(container)).toEqual([]);
866 });
@@ -840,55 +870,66 @@ describe("ChatMarkdown file citations", () => {
870 ':codex-file-citation-extra{path="/tmp/project/outputs/report.xlsx"}',
871 'Example: \\:codex-file-citation{path="/tmp/project/outputs/report.xlsx"}',
872 ])("leaves %s literal", async (text) => {
843 - const container = await renderText(text);
873 + setup();
874 + await using screen = await renderText(text);
875 + const { container } = screen;
876 expect(container.textContent).toContain(text.replace("\\", ""));
877 expect(fileOptions(container)).toEqual([]);
878 });
879
880 it("preserves Codex file citation examples inside code", async () => {
881 + setup();
882 const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
850 - const container = await renderText(
883 + await using screen = await renderText(
884 `Example: \`${directive}\`\n\n\`\`\`text\n${directive}\n\`\`\``,
885 );
886 + const { container } = screen;
887 expect(container.textContent?.match(/:codex-file-citation/g)).toHaveLength(2);
888 expect(fileOptions(container)).toEqual([]);
889 });
890
891 it("does not create a nested link for citations inside link text", async () => {
892 + setup();
893 const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
859 - const container = await renderText(`[See ${directive}](https://example.com)`);
894 + await using screen = await renderText(`[See ${directive}](https://example.com)`);
895 + const { container } = screen;
896 expect(container.textContent).toContain("codex-file-citation");
897 expect(fileOptions(container)).toEqual([]);
898 });
899
900 it("renders file citations created by over-indented list recovery", async () => {
865 - const container = await renderText(
901 + setup();
902 + await using screen = await renderText(
903 '- Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"}',
904 );
905 + const { container } = screen;
906 expect(container.querySelector("pre")).toBeNull();
907 expect(container.querySelector("li")?.textContent).toContain("Created ");
908 expect(fileOptions(container)).toEqual(["File options for report.xlsx"]);
909 });
910
911 it("disambiguates Codex citations with the same basename", async () => {
874 - const container = await renderText(
912 + setup();
913 + await using screen = await renderText(
914 'Changed :codex-file-citation{path="/tmp/project/src/index.ts"} and :codex-file-citation{path="/tmp/project/test/index.ts"}.',
915 );
916 + const { container } = screen;
917 expect(container.textContent).toContain("index.ts · project/src");
918 expect(container.textContent).toContain("index.ts · project/test");
919 });
920
921 it("preserves rejected citations created by over-indented list recovery", async () => {
882 - const malformed = await renderText(
922 + setup();
923 + await using malformed = await renderText(
924 'Leading text before list.\n\n- Bad :codex-file-citation{purpose="output"}',
925 );
885 - expect(malformed.querySelector("li")?.textContent).toBe(
926 + expect(malformed.container.querySelector("li")?.textContent).toBe(
927 'Bad :codex-file-citation{purpose="output"}',
928 );
888 - const nestedLink = await renderText(
929 + await using nestedLink = await renderText(
930 'Leading text before list.\n\n- [Bad :codex-file-citation{path="/tmp/project/report.xlsx"}](https://example.com)',
931 );
891 - expect(nestedLink.textContent).toContain(
932 + expect(nestedLink.container.textContent).toContain(
933 'Bad :codex-file-citation{path="/tmp/project/report.xlsx"}',
934 );
935 });
@@ -896,17 +937,21 @@ describe("ChatMarkdown file citations", () => {
937
938 describe("ChatMarkdown Codex follow-up suggestions", () => {
939 it.each([true, false])("renders the label with parseRawHtml=%s", async (parseRawHtml) => {
899 - const container = await renderText(
940 + setup();
941 + await using screen = await renderText(
942 'Done.\n\n- :codex-followup[Prepare print version]{prompt="Prepare the document for printing."}',
943 { lineBreaks: !parseRawHtml, parseRawHtml },
944 );
945 + const { container } = screen;
946 expect(container.textContent).toContain("Prepare print version");
947 expect(container.textContent).not.toContain("codex-followup");
948 expect(container.textContent).not.toContain("Prepare the document for printing.");
949 });
950
951 it("keeps the label of a malformed follow-up created by over-indented list recovery", async () => {
909 - const container = await renderText("- Next :codex-followup[Prepare print version]");
952 + setup();
953 + await using screen = await renderText("- Next :codex-followup[Prepare print version]");
954 + const { container } = screen;
955 expect(container.querySelector("li")?.textContent).toBe(
956 "Next :codex-followup[Prepare print version]",
957 );
@@ -920,11 +965,13 @@ describe("ChatMarkdown artifact-template cards", () => {
965 it.each([true, false])(
966 "offers the Codex template from its card with parseRawHtml=%s",
967 async (parseRawHtml) => {
968 + setup();
969 const onUseArtifactTemplate = vi.fn();
924 - const container = await renderText(ARTIFACT_TEMPLATE_DIRECTIVE, {
970 + await using screen = await renderText(ARTIFACT_TEMPLATE_DIRECTIVE, {
971 parseRawHtml,
972 onUseArtifactTemplate,
973 });
974 + const { container } = screen;
975 expect(container.textContent).not.toContain("::artifact-template");
976 expect(container.textContent).toContain("Hello World");
977 expect(container.textContent).toContain("Document template");
@@ -943,7 +990,9 @@ describe("ChatMarkdown artifact-template cards", () => {
990 );
991
992 it("renders a passive card outside a composer-backed timeline", async () => {
946 - const container = await renderText(ARTIFACT_TEMPLATE_DIRECTIVE);
993 + setup();
994 + await using screen = await renderText(ARTIFACT_TEMPLATE_DIRECTIVE);
995 + const { container } = screen;
996 expect(container.textContent).toContain("Hello World");
997 expect(container.textContent).not.toContain("Use template");
998 });
@@ -954,15 +1003,19 @@ describe("ChatMarkdown artifact-template cards", () => {
1003 `\\${ARTIFACT_TEMPLATE_DIRECTIVE}`,
1004 ARTIFACT_TEMPLATE_DIRECTIVE.replace("::artifact-template", "::artifact-template-extra"),
1005 ])("leaves %s literal", async (text) => {
957 - const container = await renderText(text);
1006 + setup();
1007 + await using screen = await renderText(text);
1008 + const { container } = screen;
1009 expect(container.textContent).toContain("::artifact-template");
1010 expect(container.textContent).not.toContain("Document template");
1011 });
1012
1013 it("preserves artifact-template examples inside code", async () => {
963 - const container = await renderText(
1014 + setup();
1015 + await using screen = await renderText(
1016 `\`${ARTIFACT_TEMPLATE_DIRECTIVE}\`\n\n\`\`\`text\n${ARTIFACT_TEMPLATE_DIRECTIVE}\n\`\`\``,
1017 );
1018 + const { container } = screen;
1019 expect(container.textContent?.match(/::artifact-template/g)).toHaveLength(2);
1020 expect(container.textContent).not.toContain("Document template");
1021 });
@@ -970,9 +1023,11 @@ describe("ChatMarkdown artifact-template cards", () => {
1023
1024 describe("ChatMarkdown headings", () => {
1025 it("exposes headings below the host heading without changing their tags", async () => {
973 - const container = await renderText("# Top\n\n## Section\n\n###### Fine print", {
1026 + setup();
1027 + await using screen = await renderText("# Top\n\n## Section\n\n###### Fine print", {
1028 headingLevelOffset: 3,
1029 });
1030 + const { container } = screen;
1031 expect(
1032 [...container.querySelectorAll("h1, h2, h6")].map((heading) => [
1033 heading.tagName,
@@ -983,15 +1038,17 @@ describe("ChatMarkdown headings", () => {
1038 ["H2", "5"],
1039 ["H6", "6"],
1040 ]);
986 - const flat = await renderText("# Top");
987 - expect(flat.querySelector("h1")?.hasAttribute("aria-level")).toBe(false);
1041 + await using flat = await renderText("# Top");
1042 + expect(flat.container.querySelector("h1")?.hasAttribute("aria-level")).toBe(false);
1043 });
1044
1045 it("never gives two headings the same id, even when a suffix matches another heading", async () => {
991 - const container = await renderText(
1046 + setup();
1047 + await using screen = await renderText(
1048 '## Setup\n\n## Setup\n\n## Setup-1\n\n<h2 id="install-1">Pinned</h2>\n\n## Install\n\n## Install',
1049 { parseRawHtml: true },
1050 );
1051 + const { container } = screen;
1052 expect([...container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([
1053 "user-content-setup",
1054 "user-content-setup-1",
@@ -1022,43 +1079,50 @@ describe("ChatMarkdown Windows file links", () => {
1079 ["backslashes", String.raw`[Open](C:\Users\shawn\project\src\main.ts)`],
1080 ["reference links", "[Open][source]\n\n[source]: C:/Users/shawn/project/src/main.ts"],
1081 ])("resolves %s to the workspace file", async (_, text) => {
1082 + setup();
1083 for (const parseRawHtml of [true, false]) {
1026 - const container = await renderWindows(text, parseRawHtml);
1084 + await using screen = await renderWindows(text, parseRawHtml);
1085 + const { container } = screen;
1086 expect(fileHrefs(container)).toEqual(["C:/Users/shawn/project/src/main.ts"]);
1087 }
1088 });
1089
1090 it("keeps backslashes CommonMark would read as escapes", async () => {
1091 + setup();
1092 for (const parseRawHtml of [true, false]) {
1033 - const container = await renderWindows(
1093 + await using screen = await renderWindows(
1094 String.raw`[settings](C:\Users\shawn\.claude\settings.json)`,
1095 parseRawHtml,
1096 );
1097 + const { container } = screen;
1098 expect(fileHrefs(container)).toEqual(["C:/Users/shawn/.claude/settings.json"]);
1099 }
1100 });
1101
1102 it("distinguishes same-named backslash paths but not the same file twice", async () => {
1103 + setup();
1104 for (const parseRawHtml of [true, false]) {
1043 - const distinct = await renderWindows(
1105 + await using distinct = await renderWindows(
1106 String.raw`[Source](C:\Users\shawn\project\src\index.ts) and [Test](C:\Users\shawn\project\test\index.ts)`,
1107 parseRawHtml,
1108 );
1047 - expect(distinct.textContent).toContain("index.ts · project/src");
1048 - expect(distinct.textContent).toContain("index.ts · project/test");
1109 + expect(distinct.container.textContent).toContain("index.ts · project/src");
1110 + expect(distinct.container.textContent).toContain("index.ts · project/test");
1111 const path = String.raw`C:\Users\shawn\project\src\main.ts`;
1050 - const same = await renderWindows(`[Source](${path}) and \`${path}\``, parseRawHtml);
1051 - expect(fileHrefs(same)).toHaveLength(2);
1052 - expect(same.textContent).not.toContain("main.ts ·");
1112 + await using same = await renderWindows(`[Source](${path}) and \`${path}\``, parseRawHtml);
1113 + expect(fileHrefs(same.container)).toHaveLength(2);
1114 + expect(same.container.textContent).not.toContain("main.ts ·");
1115 }
1116 });
1117
1118 it("still rejects unsafe schemes", async () => {
1119 + setup();
1120 for (const parseRawHtml of [true, false]) {
1058 - const container = await renderWindows(
1121 + await using screen = await renderWindows(
1122 "[unsafe](javascript:alert(1)) and [unknown](d:alert(1))",
1123 parseRawHtml,
1124 );
1125 + const { container } = screen;
1126 expect(container.innerHTML).not.toContain("javascript:");
1127 expect(container.innerHTML).not.toContain("d:alert");
1128 expect(fileHrefs(container)).toEqual([]);
@@ -1070,14 +1134,16 @@ describe("ChatMarkdown in-page links", () => {
1134 it.each([true, false])(
1135 "scrolls a table-of-contents link to its heading without touching the URL (parseRawHtml=%s)",
1136 async (parseRawHtml) => {
1073 - const scrollIntoView = vi
1137 + setup();
1138 + using scrollIntoView = vi
1139 .spyOn(HTMLElement.prototype, "scrollIntoView")
1140 .mockImplementation(() => {});
1141 const href = window.location.href;
1077 - const container = await renderText(
1142 + await using screen = await renderText(
1143 "- [Operating model](#1-operating-model)\n- [Missing](#nowhere)\n\n## 1. Operating model\n\n## 1. Operating model",
1144 { parseRawHtml },
1145 );
1146 + const { container } = screen;
1147 const headings = [...container.querySelectorAll("h2")];
1148 expect(headings.map((heading) => heading.id)).toEqual([
1149 "user-content-1-operating-model",
@@ -1117,15 +1183,17 @@ describe("ChatMarkdown thread find", () => {
1183 }
1184 const frame = () =>
1185 act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
1186 + // Highlights live in a document-wide registry the rendered tree does not own.
1187 + const clearHighlights = () => ({ [Symbol.dispose]: () => CSS.highlights.clear() });
1188 const activeHighlights = () =>
1189 [...(CSS.highlights.get("t3-thread-find-active") ?? [])].map((range) =>
1190 (range as Range).toString(),
1191 );
1192
1193 it("opens a disclosure only when find selects a match inside it", async () => {
1126 - const container = document.body.appendChild(document.createElement("div"));
1127 - const root = createRoot(container);
1128 - roots.push(root);
1194 + setup();
1195 + using _highlights = clearHighlights();
1196 + const container = document.createElement("div");
1197 const markdown = (
1198 <ChatMarkdown
1199 cwd={undefined}
@@ -1136,20 +1204,19 @@ describe("ChatMarkdown thread find", () => {
1204 ].join("\n\n")}
1205 />
1206 );
1207 + const probe = (query: string, activeOccurrence: number) => (
1208 + <FindProbe container={container} query={query} activeOccurrence={activeOccurrence}>
1209 + {markdown}
1210 + </FindProbe>
1211 + );
1212 + await using screen = await render(probe("", 0), { container });
1213 const show = (query: string, activeOccurrence: number) =>
1140 - act(() =>
1141 - root.render(
1142 - <FindProbe container={container} query={query} activeOccurrence={activeOccurrence}>
1143 - {markdown}
1144 - </FindProbe>,
1145 - ),
1146 - );
1214 + screen.rerender(probe(query, activeOccurrence));
1215 const openStates = () =>
1216 [...container.querySelectorAll<HTMLElement>("[data-markdown-details-open]")].map(
1217 (node) => node.dataset.markdownDetailsOpen,
1218 );
1219
1152 - await show("", 0);
1220 expect(container.textContent).not.toContain("nothing here");
1221 await show("needle", 0);
1222 await frame();
@@ -1166,24 +1233,21 @@ describe("ChatMarkdown thread find", () => {
1233 });
1234
1235 it("keeps Mermaid diagrams rendered until find selects a match in their source", async () => {
1169 - const container = document.body.appendChild(document.createElement("div"));
1170 - const root = createRoot(container);
1171 - roots.push(root);
1236 + setup();
1237 + using _highlights = clearHighlights();
1238 + const container = document.createElement("div");
1239 const diagram = "```mermaid\ngraph TD; Alpha-->Beta\n```";
1173 - const show = (query: string) =>
1174 - act(() =>
1175 - root.render(
1176 - <FindProbe container={container} query={query}>
1177 - <ChatMarkdown cwd={undefined} text={`Needle first.\n\n${diagram}\n\n${diagram}`} />
1178 - </FindProbe>,
1179 - ),
1180 - );
1240 + const probe = (query: string) => (
1241 + <FindProbe container={container} query={query}>
1242 + <ChatMarkdown cwd={undefined} text={`Needle first.\n\n${diagram}\n\n${diagram}`} />
1243 + </FindProbe>
1244 + );
1245 const diagrams = () => container.querySelectorAll('svg[aria-label="Diagram"]').length;
1246
1183 - await show("Needle");
1247 + await using screen = await render(probe("Needle"), { container });
1248 await frame();
1249 expect(diagrams()).toBe(2);
1186 - await show("Alpha");
1250 + await screen.rerender(probe("Alpha"));
1251 await frame();
1252 await frame();
1253 expect(diagrams()).toBe(1);
@@ -1224,23 +1288,22 @@ describe("ChatMarkdown thread find", () => {
1288 ])(
1289 "highlights the indexed occurrences of $query in $text",
1290 async ({ text, query, count, lineBreaks, user, withTemplate }) => {
1291 + setup();
1292 const skills = [{ name: "test-t3-app", displayName: "T3 App Testing" }];
1228 - const container = document.body.appendChild(document.createElement("div"));
1229 - const root = createRoot(container);
1230 - roots.push(root);
1231 - await act(() =>
1232 - root.render(
1233 - <FindProbe container={container} query={query}>
1234 - <ChatMarkdown
1235 - text={text}
1236 - cwd={undefined}
1237 - skills={skills}
1238 - lineBreaks={lineBreaks ?? false}
1239 - parseRawHtml={!user}
1240 - onUseArtifactTemplate={withTemplate ? () => undefined : undefined}
1241 - />
1242 - </FindProbe>,
1243 - ),
1293 + using _highlights = clearHighlights();
1294 + const container = document.createElement("div");
1295 + await using _screen = await render(
1296 + <FindProbe container={container} query={query}>
1297 + <ChatMarkdown
1298 + text={text}
1299 + cwd={undefined}
1300 + skills={skills}
1301 + lineBreaks={lineBreaks ?? false}
1302 + parseRawHtml={!user}
1303 + onUseArtifactTemplate={withTemplate ? () => undefined : undefined}
1304 + />
1305 + </FindProbe>,
1306 + { container },
1307 );
1308 await frame();
1309 // Lazy blocks such as Mermaid can swap their source text after the first frame,
@@ -1290,17 +1353,19 @@ it.each([
1353 relative: "reports/report.csv",
1354 },
1355 ])("copies $name and shows the copied text", async ({ platform, cwd, href, full, relative }) => {
1293 - vi.spyOn(navigator, "platform", "get").mockReturnValue(platform);
1294 - vi.stubGlobal("ClipboardItem", undefined);
1295 - const writeText = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue(undefined);
1296 - const toast = vi.spyOn(toastManager, "add");
1356 + setup();
1357 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue(platform);
1358 + using _clipboardItem = stubGlobal("ClipboardItem", undefined);
1359 + using writeText = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue(undefined);
1360 + using toast = vi.spyOn(toastManager, "add");
1361 const api = readLocalApi();
1362 if (!api) throw new Error("Local API unavailable");
1299 - const choose = vi.spyOn(api.contextMenu, "show");
1300 - const container = await renderText(`[File](<${href}>)`, {
1363 + using choose = vi.spyOn(api.contextMenu, "show");
1364 + await using screen = await renderText(`[File](<${href}>)`, {
1365 cwd,
1366 environmentId: EnvironmentId.make("env-file-copy"),
1367 });
1368 + const { container } = screen;
1369 const link = container.querySelector(".chat-markdown-file-link");
1370 if (!link) throw new Error("File link unavailable");
1371 for (const [action, expected] of [
@@ -1324,21 +1389,24 @@ describe("ChatMarkdown math", () => {
1389 options: Partial<Parameters<typeof ChatMarkdown>[0]> = {},
1390 ) => {
1391 settingsOverrides.mathRenderingEnabled = true;
1327 - const { container: host } = await render(
1328 - <ChatMarkdown cwd="/tmp/project" text={text} {...options} />,
1392 + await using stack = new AsyncDisposableStack();
1393 + const screen = stack.use(
1394 + await render(<ChatMarkdown cwd="/tmp/project" text={text} {...options} />),
1395 );
1330 - host.setAttribute("data-assistant-citation-source", "assistant");
1396 + screen.container.setAttribute("data-assistant-citation-source", "assistant");
1397 await act(async () => {
1398 await import("./chat/MathTypeset");
1399 });
1334 - return { host };
1400 + stack.move();
1401 + return screen;
1402 };
1403
1404 it.each(["$x$", "$$x$$", "```math\nx\n```", "$\\notACommand{x}$"])(
1405 "keeps keyboard focus on the parent control in compact previews of %s",
1406 async (formula) => {
1407 + setup();
1408 settingsOverrides.mathRenderingEnabled = true;
1341 - const { container } = await render(
1409 + await using screen = await render(
1410 <>
1411 <button type="button">
1412 Preview <ChatMarkdown inline text={formula} cwd={undefined} />
@@ -1346,6 +1414,7 @@ describe("ChatMarkdown math", () => {
1414 <button type="button">After preview</button>
1415 </>,
1416 );
1417 + const { container } = screen;
1418 await act(async () => {
1419 await import("./chat/MathTypeset");
1420 });
@@ -1360,13 +1429,15 @@ describe("ChatMarkdown math", () => {
1429 );
1430
1431 it("keeps message formulas reachable by keyboard", async () => {
1432 + setup();
1433 settingsOverrides.mathRenderingEnabled = true;
1364 - const { container } = await render(
1434 + await using screen = await render(
1435 <>
1436 <button type="button">Before equation</button>
1437 <ChatMarkdown text="$x$" cwd={undefined} />
1438 </>,
1439 );
1440 + const { container } = screen;
1441 container.querySelector("button")!.focus();
1442 await act(() => userEvent.tab());
1443 expect(document.activeElement).toBe(
@@ -1375,11 +1446,12 @@ describe("ChatMarkdown math", () => {
1446 });
1447
1448 it("renders table formulas and exports their TeX instead of duplicate glyph text", async () => {
1378 - const rendered = await renderMath(
1449 + setup();
1450 + await using rendered = await renderMath(
1451 "| Name | Formula |\n| --- | --- |\n| Norm | $|x|$ and \\(\\|y\\|\\) |\n| Price | $5 and $10 |",
1452 );
1453
1382 - const table = rendered.host.querySelector("table")!;
1454 + const table = rendered.container.querySelector("table")!;
1455 expect([...table.rows].map((row) => row.cells.length)).toEqual([2, 2, 2]);
1456 expect(table.querySelectorAll(".katex")).toHaveLength(2);
1457 const norm = table.querySelectorAll(".katex")[1]!;
@@ -1402,34 +1474,36 @@ describe("ChatMarkdown math", () => {
1474 expect(payload.text).toBe("\\(|x|\\)");
1475 expect(payload.html).toContain("\\(|x|\\)");
1476 expect(payload.html).not.toContain("katex");
1405 - expect(captureAssistantTextSelection(rendered.host, selection)?.selector.text).toBe(
1477 + expect(captureAssistantTextSelection(rendered.container, selection)?.selector.text).toBe(
1478 "\\(|x|\\)",
1479 );
1480 });
1481
1482 it("renders explicit math fences and keeps unfinished streamed fences readable", async () => {
1411 - const rendered = await renderMath("```math\nx_i^2\n```\n\n`$literal$`\n\n$unfinished");
1483 + setup();
1484 + await using rendered = await renderMath("```math\nx_i^2\n```\n\n`$literal$`\n\n$unfinished");
1485
1413 - expect(rendered.host.querySelectorAll(".katex")).toHaveLength(1);
1414 - expect(rendered.host.textContent).toContain("$literal$");
1415 - expect(rendered.host.textContent).toContain("$unfinished");
1486 + expect(rendered.container.querySelectorAll(".katex")).toHaveLength(1);
1487 + expect(rendered.container.textContent).toContain("$literal$");
1488 + expect(rendered.container.textContent).toContain("$unfinished");
1489
1417 - const streamed = await renderMath("```math\nx_i^2", { isStreaming: true });
1490 + await using streamed = await renderMath("```math\nx_i^2", { isStreaming: true });
1491
1419 - expect(streamed.host.querySelector(".katex")).toBeNull();
1420 - expect(streamed.host.textContent).toContain("x_i^2");
1492 + expect(streamed.container.querySelector(".katex")).toBeNull();
1493 + expect(streamed.container.textContent).toContain("x_i^2");
1494 });
1495
1496 it.each(["$$\nx^2\n", "\\[\nx^2\n"])(
1497 "keeps unfinished display %s and following prose readable while streaming",
1498 async (source) => {
1499 + setup();
1500 for (const text of [source, `${source}\nFollowing prose.`]) {
1427 - const { host } = await renderMath(text, { isStreaming: true });
1428 - expect(host.querySelector(".katex")).toBeNull();
1429 - expect(host.querySelector("[data-markdown-math]")).toBeNull();
1430 - expect(host.textContent).toContain("x^2");
1501 + await using math = await renderMath(text, { isStreaming: true });
1502 + expect(math.container.querySelector(".katex")).toBeNull();
1503 + expect(math.container.querySelector("[data-markdown-math]")).toBeNull();
1504 + expect(math.container.textContent).toContain("x^2");
1505 if (text.includes("Following prose."))
1432 - expect(host.textContent).toContain("Following prose.");
1506 + expect(math.container.textContent).toContain("Following prose.");
1507 }
1508 },
1509 );
@@ -1437,46 +1511,51 @@ describe("ChatMarkdown math", () => {
1511 it.each(["$$x^2$$", "$$\nx^2\n$$", "\\[\nx^2\n\\]", "```math\nx^2\n```"])(
1512 "renders completed %s while the response is streaming",
1513 async (source) => {
1440 - const { host } = await renderMath(source, { isStreaming: true });
1441 - expect(host.querySelectorAll(".katex")).toHaveLength(1);
1442 - expect(host.querySelector('[data-markdown-math="display"]')).not.toBeNull();
1514 + setup();
1515 + await using math = await renderMath(source, { isStreaming: true });
1516 + expect(math.container.querySelectorAll(".katex")).toHaveLength(1);
1517 + expect(math.container.querySelector('[data-markdown-math="display"]')).not.toBeNull();
1518 },
1519 );
1520
1521 it("shows unsupported TeX as source and keeps active TeX commands inert", async () => {
1447 - const rendered = await renderMath(
1522 + setup();
1523 + await using rendered = await renderMath(
1524 "\\(\\notACommand{x}\\) and \\(\\href{https://example.com}{x}\\)",
1525 );
1526
1451 - expect(rendered.host.textContent).toContain("\\(\\notACommand{x}\\)");
1452 - expect(rendered.host.querySelector('a[href="https://example.com"]')).toBeNull();
1527 + expect(rendered.container.textContent).toContain("\\(\\notACommand{x}\\)");
1528 + expect(rendered.container.querySelector('a[href="https://example.com"]')).toBeNull();
1529 });
1530
1531 it("typesets only when enabled, keeping prices and task offsets intact", async () => {
1532 + setup();
1533 const text = "Area $\\pi r^2$ costs $5 and $10.\n\n\\[\nE = mc^2\n\\]\n\n- [ ] check \\(x\\)";
1457 - const off = await renderText(text);
1458 - expect(off.querySelector("[data-markdown-math]")).toBeNull();
1459 - const html = await renderText('<code class="language-math math-inline">x</code>');
1460 - expect(html.querySelector("[data-markdown-math]")).toBeNull();
1534 + await using off = await renderText(text);
1535 + expect(off.container.querySelector("[data-markdown-math]")).toBeNull();
1536 + await using html = await renderText('<code class="language-math math-inline">x</code>');
1537 + expect(html.container.querySelector("[data-markdown-math]")).toBeNull();
1538 for (const parseRawHtml of [true, false]) {
1539 let editedText = text;
1463 - const { host } = await renderMath(text, {
1540 + await using math = await renderMath(text, {
1541 parseRawHtml,
1542 onTaskListChange: ({ markerOffset, checked }) => {
1543 editedText = setMarkdownTaskChecked(text, markerOffset, checked);
1544 },
1545 });
1546 expect(
1470 - [...host.querySelectorAll("[data-markdown-math]")].map((node) =>
1547 + [...math.container.querySelectorAll("[data-markdown-math]")].map((node) =>
1548 node.getAttribute("data-markdown-copy"),
1549 ),
1550 ).toEqual(["\\(\\pi r^2\\)", "\\[\nE = mc^2\n\\]\n\n", "\\(x\\)"]);
1474 - await act(() => host.querySelector<HTMLInputElement>('input[type="checkbox"]')!.click());
1551 + await act(() =>
1552 + math.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.click(),
1553 + );
1554 expect(editedText).toBe(text.replace("- [ ]", "- [x]"));
1555 }
1477 - const { host } = await renderMath("- intro\n\n $$\n x^2\n $$");
1556 + await using math = await renderMath("- intro\n\n $$\n x^2\n $$");
1557 expect(
1479 - [...host.querySelectorAll("[data-markdown-math]")].map((node) =>
1558 + [...math.container.querySelectorAll("[data-markdown-math]")].map((node) =>
1559 node.getAttribute("data-markdown-copy"),
1560 ),
1561 ).toEqual(["\\[\nx^2\n\\]\n\n"]);
apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx
+50 -51
@@ -8,10 +8,9 @@ import {
8 type ThreadLinkedPullRequest,
9 } from "@t3tools/contracts";
10 import { AsyncResult } from "effect/reactivity";
11 -import { act } from "react";
12 -import { createRoot, type Root } from "react-dom/client";
13 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
11 +import { expect, it, vi } from "vite-plus/test";
12
13 +import { act, render } from "../../test/render";
14 import { useRightPanelStore } from "../rightPanelStore";
15
16 const state = vi.hoisted(() => ({
@@ -130,10 +129,9 @@ const serverConfig = {
129 shellRevealInFileManagerKind: "xdg-open",
130 environment: { platform: { os: "linux" }, capabilities: { threadPullRequestLinking: true } },
131 };
133 -const roots: Root[] = [];
134 -let container: HTMLDivElement;
132
136 -beforeEach(() => {
133 +function setup() {
134 + using stack = new DisposableStack();
135 state.allowed = true;
136 state.listeners.clear();
137 state.linkedPullRequest = null;
@@ -144,40 +142,35 @@ beforeEach(() => {
142 state.openFile.mockReset();
143 state.openExternal.mockReset().mockResolvedValue(undefined);
144 state.copy.mockReset().mockResolvedValue(undefined);
145 + const { openFile } = useRightPanelStore.getState();
146 useRightPanelStore.setState({ openFile: state.openFile });
148 - vi.spyOn(navigator.clipboard, "writeText").mockImplementation(state.copy);
149 - vi.spyOn(navigator.clipboard, "write").mockImplementation(async (items) => {
150 - const item = items[0]!;
151 - await state.copy(await (await item.getType("text/plain")).text());
152 - });
153 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
154 -});
155 -
156 -afterEach(async () => {
157 - for (const root of roots.splice(0)) await act(async () => root.unmount());
158 - document.body.replaceChildren();
159 - vi.restoreAllMocks();
160 - vi.unstubAllGlobals();
161 -});
162 -
163 -async function renderMarkdown(text: string) {
164 - container = document.body.appendChild(document.createElement("div"));
165 - const root = createRoot(container);
166 - roots.push(root);
167 - await act(async () =>
168 - root.render(<ChatMarkdown cwd="/work" threadRef={threadRef} text={text} />),
147 + stack.defer(() => useRightPanelStore.setState({ openFile }));
148 + stack.use(vi.spyOn(navigator.clipboard, "writeText").mockImplementation(state.copy));
149 + stack.use(
150 + vi.spyOn(navigator.clipboard, "write").mockImplementation(async (items) => {
151 + const item = items[0]!;
152 + await state.copy(await (await item.getType("text/plain")).text());
153 + }),
154 );
155 + return stack.move();
156 }
157
172 -function anchor() {
173 - return container.querySelector("a")!;
174 -}
175 -
176 -async function openContextMenu() {
177 - await act(async () => {
178 - anchor().dispatchEvent(
179 - new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 10, clientY: 10 }),
180 - );
158 +async function renderMarkdown(text: string) {
159 + const screen = await render(<ChatMarkdown cwd="/work" threadRef={threadRef} text={text} />);
160 + const anchor = () => screen.container.querySelector("a")!;
161 + return Object.assign(screen, {
162 + anchor,
163 + openContextMenu: () =>
164 + act(async () => {
165 + anchor().dispatchEvent(
166 + new MouseEvent("contextmenu", {
167 + bubbles: true,
168 + cancelable: true,
169 + clientX: 10,
170 + clientY: 10,
171 + }),
172 + );
173 + }),
174 });
175 }
176
@@ -193,20 +186,22 @@ async function setAllowed(allowed: boolean) {
186 }
187
188 it("removes host actions after revocation while keeping file preview and copying", async () => {
196 - await renderMarkdown("[Readme](docs/readme.md)");
197 - await openContextMenu();
189 + using _setup = setup();
190 + await using screen = await renderMarkdown("[Readme](docs/readme.md)");
191 + await screen.openContextMenu();
192 expect(offeredActions()).toEqual(["open", "reveal", "copy-relative", "copy-full"]);
193 await setAllowed(false);
194 state.choose.mockResolvedValue("copy-full");
201 - await openContextMenu();
195 + await screen.openContextMenu();
196 expect(offeredActions()).toEqual(["copy-relative", "copy-full"]);
197 await vi.waitFor(() => expect(state.copy).toHaveBeenCalledWith("/work/docs/readme.md"));
204 - await act(async () => anchor().click());
198 + await act(async () => screen.anchor().click());
199 expect(state.openFile).toHaveBeenCalledWith(threadRef, "docs/readme.md", undefined);
200 expect(state.openEditor).not.toHaveBeenCalled();
201 });
202
203 it("starts copying before the nested-file lookup finishes", async () => {
204 + using _setup = setup();
205 let finishLookup: () => void = () => {
206 throw new Error("Lookup not started");
207 };
@@ -218,8 +213,8 @@ it("starts copying before the nested-file lookup finishes", async () => {
213 }),
214 );
215 state.choose.mockResolvedValue("copy-full");
221 - await renderMarkdown("`readme.md:10:2`");
222 - await openContextMenu();
216 + await using screen = await renderMarkdown("`readme.md:10:2`");
217 + await screen.openContextMenu();
218 expect(navigator.clipboard.write).toHaveBeenCalledOnce();
219 expect(state.copy).not.toHaveBeenCalled();
220 await act(async () => finishLookup());
@@ -227,6 +222,7 @@ it("starts copying before the nested-file lookup finishes", async () => {
222 });
223
224 it("does not launch an editor after revocation during a native context menu", async () => {
225 + using _setup = setup();
226 let choose: (action: string) => void = () => {
227 throw new Error("Menu not opened");
228 };
@@ -236,8 +232,8 @@ it("does not launch an editor after revocation during a native context menu", as
232 choose = resolve;
233 }),
234 );
239 - await renderMarkdown("[Readme](docs/readme.md)");
240 - await openContextMenu();
235 + await using screen = await renderMarkdown("[Readme](docs/readme.md)");
236 + await screen.openContextMenu();
237 expect(offeredActions()).toContain("open");
238 await act(async () => {
239 state.allowed = false;
@@ -247,6 +243,7 @@ it("does not launch an editor after revocation during a native context menu", as
243 });
244
245 it("does not reveal a file after revocation during its workspace lookup", async () => {
246 + using _setup = setup();
247 let finishLookup: () => void = () => {
248 throw new Error("Lookup not started");
249 };
@@ -257,8 +254,8 @@ it("does not reveal a file after revocation during its workspace lookup", async
254 }),
255 );
256 state.choose.mockResolvedValue("reveal");
260 - await renderMarkdown("[Readme](readme.md)");
261 - await openContextMenu();
257 + await using screen = await renderMarkdown("[Readme](readme.md)");
258 + await screen.openContextMenu();
259 expect(state.search).toHaveBeenCalledOnce();
260 await act(async () => {
261 state.allowed = false;
@@ -270,11 +267,12 @@ it("does not reveal a file after revocation during its workspace lookup", async
267 it.each([false, true])(
268 "keeps PR links usable without offering metadata edits (linked=%s)",
269 async (linked) => {
270 + using _setup = setup();
271 state.allowed = false;
272 state.linkedPullRequest = linked ? linkedPullRequest : null;
273 state.choose.mockResolvedValue("open-external");
276 - await renderMarkdown(`[Review](${linkedPullRequest.url})`);
277 - await openContextMenu();
274 + await using screen = await renderMarkdown(`[Review](${linkedPullRequest.url})`);
275 + await screen.openContextMenu();
276 expect(offeredActions()).toEqual(["open-external", "copy-link"]);
277 await vi.waitFor(() => expect(state.openExternal).toHaveBeenCalledWith(linkedPullRequest.url));
278 expect(state.updateMetadata).not.toHaveBeenCalled();
@@ -284,6 +282,7 @@ it.each([false, true])(
282 it.each(["link-to-thread", "unlink-from-thread"])(
283 "rechecks %s after a native context menu returns",
284 async (action) => {
285 + using _setup = setup();
286 state.linkedPullRequest = action === "unlink-from-thread" ? linkedPullRequest : null;
287 let choose: (action: string) => void = () => {
288 throw new Error("Menu not opened");
@@ -294,8 +293,8 @@ it.each(["link-to-thread", "unlink-from-thread"])(
293 choose = resolve;
294 }),
295 );
297 - await renderMarkdown(`[Review](${linkedPullRequest.url})`);
298 - await openContextMenu();
296 + await using screen = await renderMarkdown(`[Review](${linkedPullRequest.url})`);
297 + await screen.openContextMenu();
298 expect(offeredActions()).toContain(action);
299 await act(async () => {
300 state.allowed = false;
@@ -305,7 +304,7 @@ it.each(["link-to-thread", "unlink-from-thread"])(
304
305 await setAllowed(true);
306 state.choose.mockResolvedValue(action);
308 - await openContextMenu();
307 + await screen.openContextMenu();
308 await vi.waitFor(() =>
309 expect(state.updateMetadata).toHaveBeenCalledExactlyOnceWith({
310 environmentId: threadRef.environmentId,
apps/web/src/components/CommandPalette.focus.browser.test.tsx
+29 -48
@@ -1,13 +1,14 @@
1 -import { act, useImperativeHandle, useRef } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { useImperativeHandle, useRef, type ReactNode } from "react";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3 +import { act, fakeTimers, render } from "../../test/render";
4 import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
5 import { CommandPalette } from "./CommandPalette";
6 import { useComposerHandleContext } from "../composerHandleContext";
7 import { openCommandPalette } from "../commandPaletteBus";
8 import { primaryServerKeybindingsAtom } from "../state/server";
9
10 -vi.mock("@tanstack/react-router", () => ({
10 +vi.mock("@tanstack/react-router", async (importOriginal) => ({
11 + ...(await importOriginal<typeof import("@tanstack/react-router")>()),
12 useNavigate: () => vi.fn(),
13 useParams: () => null,
14 useLocation: () => "/settings",
@@ -66,26 +67,20 @@ vi.mock("./settings/useAvailableSettingsSearchItems", () => ({
67 useAvailableSettingsSearchItems: () => [],
68 }));
69
69 -let root: Root;
70 -let container: HTMLDivElement;
71 -
72 -beforeEach(() => {
73 - vi.useFakeTimers();
74 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
75 - container = document.createElement("div");
76 - document.body.append(container);
77 - root = createRoot(container);
78 -});
79 -
80 -afterEach(async () => {
81 - await act(async () => {
82 - root.unmount();
83 - await vi.runOnlyPendingTimersAsync();
70 +// Navigation hooks are mocked above, and the test router would load on the fake clock too.
71 +async function renderPalette(children: ReactNode) {
72 + await using stack = new AsyncDisposableStack();
73 + stack.use(fakeTimers());
74 + // Runs after unmount, so timers the palette leaves behind fire on the fake clock.
75 + stack.defer(async () => {
76 + await act(() => vi.runOnlyPendingTimersAsync());
77 });
85 - container.remove();
86 - vi.unstubAllGlobals();
87 - vi.useRealTimers();
88 -});
78 + const screen = stack.use(
79 + await render(<CommandPalette>{children}</CommandPalette>, { router: false }),
80 + );
81 + const environment = stack.move();
82 + return Object.assign(screen, { [Symbol.asyncDispose]: () => environment.disposeAsync() });
83 +}
84
85 async function flushFocus() {
86 await act(() => vi.advanceTimersByTimeAsync(0));
@@ -120,14 +115,8 @@ function Composer() {
115
116 describe("command palette focus restoration", () => {
117 it("returns to the previously focused Settings field when no composer is mounted", async () => {
123 - await act(() =>
124 - root.render(
125 - <CommandPalette>
126 - <input aria-label="Settings field" />
127 - </CommandPalette>,
128 - ),
129 - );
130 - const field = container.querySelector("input")!;
118 + await using screen = await renderPalette(<input aria-label="Settings field" />);
119 + const field = screen.container.querySelector("input")!;
120 await act(() => field.focus());
121 await act(() => openCommandPalette());
122 await flushFocus();
@@ -137,14 +126,8 @@ describe("command palette focus restoration", () => {
126 });
127
128 it("focuses the replacement command input after leaving the file picker", async () => {
140 - await act(() =>
141 - root.render(
142 - <CommandPalette>
143 - <input aria-label="Settings field" />
144 - </CommandPalette>,
145 - ),
146 - );
147 - const field = container.querySelector("input")!;
129 + await using screen = await renderPalette(<input aria-label="Settings field" />);
130 + const field = screen.container.querySelector("input")!;
131 await act(() => field.focus());
132 await act(() =>
133 field.dispatchEvent(
@@ -175,20 +158,18 @@ describe("command palette focus restoration", () => {
158 });
159
160 it("focuses the mounted composer at the end instead of the previous field", async () => {
178 - await act(() =>
179 - root.render(
180 - <CommandPalette>
181 - <input aria-label="Previous field" />
182 - <Composer />
183 - </CommandPalette>,
184 - ),
161 + await using screen = await renderPalette(
162 + <>
163 + <input aria-label="Previous field" />
164 + <Composer />
165 + </>,
166 );
186 - await act(() => container.querySelector("input")!.focus());
167 + await act(() => screen.container.querySelector("input")!.focus());
168 await act(() => openCommandPalette());
169 await flushFocus();
170 expect(document.activeElement?.closest("[data-command-palette]")).not.toBeNull();
171 await dismissPalette();
191 - const composer = container.querySelector("textarea")!;
172 + const composer = screen.container.querySelector("textarea")!;
173 expect(document.activeElement).toBe(composer);
174 expect(composer.selectionStart).toBe(composer.value.length);
175 });
apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.browser.test.tsx
+7 -29
@@ -3,21 +3,13 @@ import {
3 serializeAssistantCitation,
4 withAssistantCitationComment,
5 } from "@t3tools/shared/assistantCitations";
6 -import { act, createRef, useState, type ReactNode } from "react";
7 -import { createRoot, type Root } from "react-dom/client";
8 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
6 +import { createRef, useState } from "react";
7 +import { expect, it } from "vite-plus/test";
8
9 import { page, userEvent } from "vite-plus/test/browser";
10
11 import { findAssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
13 -
14 -// No router is mounted; the citation chip only needs navigation to exist.
15 -vi.mock(import("@tanstack/react-router"), async (original) => ({
16 - ...(await original()),
17 - useNavigate: () => async () => {},
18 - Link: (({ children }: { children: ReactNode }) => <a>{children}</a>) as never,
19 -}));
20 -
12 +import { act, render } from "../../test/render";
13 import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";
14
15 const citation = {
@@ -33,20 +25,6 @@ const citation = {
25 };
26 const promptBefore = `See ${serializeAssistantCitation(citation)} `;
27
36 -let root: Root;
37 -let container: HTMLDivElement;
38 -
39 -beforeEach(() => {
40 - container = document.createElement("div");
41 - document.body.append(container);
42 - root = createRoot(container);
43 -});
44 -
45 -afterEach(async () => {
46 - await act(async () => root.unmount());
47 - container.remove();
48 -});
49 -
28 function Composer({
29 question,
30 editorRef,
@@ -88,9 +66,9 @@ function Composer({
66
67 it("keeps an unsaved citation comment when a question takes the composer", async () => {
68 const editorRef = createRef<ComposerPromptEditorHandle>();
91 - const drafts = () => container.querySelector("output")?.dataset;
69 + await using screen = await render(<Composer question={false} editorRef={editorRef} />);
70 + const drafts = () => screen.container.querySelector("output")?.dataset;
71
93 - await act(async () => root.render(<Composer question={false} editorRef={editorRef} />));
72 const sourceAnchor = findAssistantCitationSourceAnchor(document, citation);
73 if (!sourceAnchor) throw new Error("Citation source did not resolve");
74 await act(async () =>
@@ -107,9 +85,9 @@ it("keeps an unsaved citation comment when a question takes the composer", async
85 await comment.click();
86 await userEvent.keyboard("check this");
87
110 - await act(async () => root.render(<Composer question editorRef={editorRef} />));
88 + await screen.rerender(<Composer question editorRef={editorRef} />);
89 expect(drafts()?.answer).toBe("");
112 - await act(async () => root.render(<Composer question={false} editorRef={editorRef} />));
90 + await screen.rerender(<Composer question={false} editorRef={editorRef} />);
91
92 expect(drafts()?.prompt).toBe(
93 `See ${serializeAssistantCitation(withAssistantCitationComment(citation, "check this"))} `,
apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx
+84 -76
@@ -10,9 +10,10 @@ import {
10 import { userEvent } from "vite-plus/test/browser";
11 import type { ServerProviderSkill } from "@t3tools/contracts";
12 import type { Editor } from "@tiptap/core";
13 -import { act, createElement, createRef, useEffect, useState } from "react";
14 -import { createRoot, type Root } from "react-dom/client";
15 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13 +import { createElement, createRef, useEffect, useState } from "react";
14 +import { describe, expect, it, vi } from "vite-plus/test";
15 +
16 +import { act, render } from "../../test/render";
17
18 import { detectComposerTrigger } from "~/composer-logic";
19 import { serializeEditorDoc } from "~/composer-rich-text-doc";
@@ -22,22 +23,6 @@ import {
23 type ComposerPromptEditorProps,
24 } from "./ComposerPromptEditor";
25
25 -let root: Root;
26 -let container: HTMLDivElement;
27 -
28 -beforeEach(() => {
29 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
30 - container = document.createElement("div");
31 - document.body.append(container);
32 - root = createRoot(container);
33 -});
34 -
35 -afterEach(async () => {
36 - await act(async () => root.unmount());
37 - container.remove();
38 - vi.unstubAllGlobals();
39 -});
40 -
26 const babysit: ServerProviderSkill = {
27 name: "babysit",
28 path: "/skills/babysit/SKILL.md",
@@ -75,27 +60,39 @@ function Composer({
60 );
61 }
62
78 -async function mountEditor(
63 +function composer(
64 value: string,
65 richTextEnabled = true,
66 skills: ReadonlyArray<ServerProviderSkill> = [],
67 onChange?: ComposerPromptEditorProps["onChange"],
68 ) {
84 - await act(async () =>
85 - root.render(
86 - <Composer
87 - value={value}
88 - richTextEnabled={richTextEnabled}
89 - skills={skills}
90 - onChange={onChange}
91 - />,
92 - ),
69 + return (
70 + <Composer value={value} richTextEnabled={richTextEnabled} skills={skills} onChange={onChange} />
71 );
72 +}
73 +
74 +function editorIn(container: HTMLElement) {
75 const element = container.querySelector<HTMLElement & { editor: Editor }>(".tiptap");
76 if (!element) throw new Error("Composer did not mount");
77 return element.editor;
78 }
79
80 +async function mountEditor(...props: Parameters<typeof composer>) {
81 + await using stack = new AsyncDisposableStack();
82 + const screen = stack.use(await render(composer(...props)));
83 + const editor = editorIn(screen.container);
84 + const environment = stack.move();
85 + return Object.assign(screen, {
86 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
87 + editor,
88 + /** Rerenders the same composer with new props, as a parent would. */
89 + update: async (...next: Parameters<typeof composer>) => {
90 + await screen.rerender(composer(...next));
91 + return editorIn(screen.container);
92 + },
93 + });
94 +}
95 +
96 async function replaceDomText(editor: Editor, text: string, isComposing = false) {
97 await act(async () => {
98 const node = editor.view.dom.querySelector("p")?.firstChild;
@@ -140,7 +137,8 @@ it.each([
137 { value: "clean _build and node", code: [] },
138 { value: "clean `_build` and `node", code: ["_build"] },
139 ])("keeps a typed underscore literal after $value", async ({ value, code }) => {
143 - const editor = await mountEditor(value);
140 + await using screen = await mountEditor(value);
141 + const { editor } = screen;
142 await act(async () => {
143 editor.commands.focus("end");
144 const { from, to } = editor.state.selection;
@@ -152,7 +150,8 @@ it.each([
150 });
151
152 it("still italicizes text when typing a closing asterisk", async () => {
155 - const editor = await mountEditor("clean *build");
153 + await using screen = await mountEditor("clean *build");
154 + const { editor } = screen;
155 await act(async () => {
156 editor.commands.focus("end");
157 const { from, to } = editor.state.selection;
@@ -166,7 +165,8 @@ it.each([false, true])(
165 "composes an umlaut without wrapping the preedit text (rich text: %s)",
166 async (richTextEnabled) => {
167 // The middle dot stands in for the provisional text shown by the Compose key.
169 - const editor = await mountEditor("·", richTextEnabled);
168 + await using screen = await mountEditor("·", richTextEnabled);
169 + const { editor } = screen;
170 await act(async () => {
171 editor.view.focus();
172 editor.view.dom.dispatchEvent(new CompositionEvent("compositionstart"));
@@ -182,7 +182,8 @@ it.each([false, true])(
182 );
183
184 it("commits a composed quote without surrounding the preedit text", async () => {
185 - const editor = await mountEditor("·");
185 + await using screen = await mountEditor("·");
186 + const { editor } = screen;
187 await act(async () => {
188 editor.view.focus();
189 editor.view.dom.dispatchEvent(new CompositionEvent("compositionstart"));
@@ -193,7 +194,8 @@ it("commits a composed quote without surrounding the preedit text", async () =>
194 });
195
196 it("lets composition replace selected text without surrounding it", async () => {
196 - const editor = await mountEditor("word");
197 + await using screen = await mountEditor("word");
198 + const { editor } = screen;
199 await act(async () => {
200 editor.commands.setTextSelection({ from: 1, to: 5 });
201 editor.view.dom.dispatchEvent(new CompositionEvent("compositionstart"));
@@ -203,7 +205,8 @@ it("lets composition replace selected text without surrounding it", async () =>
205 });
206
207 it("replaces text outside the selected range without surrounding it", async () => {
206 - const editor = await mountEditor("word");
208 + await using screen = await mountEditor("word");
209 + const { editor } = screen;
210 await act(async () => {
211 editor.commands.setTextSelection({ from: 1, to: 5 });
212 typeText(editor, 2, 3, '"');
@@ -214,7 +217,8 @@ it("replaces text outside the selected range without surrounding it", async () =
217 it.each([false, true])(
218 "still surrounds selected text with quotes (rich text: %s)",
219 async (richTextEnabled) => {
217 - const editor = await mountEditor("word", richTextEnabled);
220 + await using screen = await mountEditor("word", richTextEnabled);
221 + const { editor } = screen;
222 await act(async () => {
223 editor.commands.setTextSelection({ from: 1, to: 5 });
224 editor.view.focus();
@@ -226,7 +230,8 @@ it.each([false, true])(
230
231 it("keeps unknown dollar names editable when restoring and pasting a draft", async () => {
232 const value = "echo $HOME $PATH $anything $notaskill $20 $20k $babysit ";
229 - const editor = await mountEditor(value, true, [babysit]);
233 + await using screen = await mountEditor(value, true, [babysit]);
234 + const { editor } = screen;
235 expect(editor.state.doc.textContent).toBe(value.replace("$babysit", ""));
236 expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
237 await act(async () => {
@@ -246,7 +251,13 @@ it("keeps unknown dollar names editable when restoring and pasting a draft", asy
251
252 it("keeps skill queries active before whitespace and line breaks, suppressing only real chips", async () => {
253 const onChange = vi.fn<ComposerPromptEditorProps["onChange"]>();
249 - const editor = await mountEditor("use now\nfirst \n$babysit tail", true, [babysit], onChange);
254 + await using screen = await mountEditor(
255 + "use now\nfirst \n$babysit tail",
256 + true,
257 + [babysit],
258 + onChange,
259 + );
260 + const { editor } = screen;
261 const trigger = () => {
262 const [value, , expandedCursor, suppressTrigger] = onChange.mock.lastCall!;
263 return suppressTrigger ? null : detectComposerTrigger(value, expandedCursor);
@@ -284,16 +295,17 @@ it("keeps skill queries active before whitespace and line breaks, suppressing on
295
296 it("keeps the caret inside unknown dollar text across rich and plain remounts", async () => {
297 const value = "echo $HOME now";
287 - let editor = await mountEditor(value);
298 + await using screen = await mountEditor(value);
299 + let { editor } = screen;
300 await act(async () => {
301 editor.commands.setTextSelection("echo $HO".length + 1);
302 });
291 - editor = await mountEditor(value, false);
303 + editor = await screen.update(value, false);
304 await act(async () => {
305 editor.commands.insertContent("X");
306 });
307 expect(serializeEditorDoc(editor.state.doc).value).toBe("echo $HOXME now");
296 - editor = await mountEditor(value, true);
308 + editor = await screen.update(value, true);
309 await act(async () => {
310 editor.commands.insertContent("Y");
311 });
@@ -304,18 +316,19 @@ it("reconciles provider skills and metadata without losing formatting, caret, or
316 const value = "run **use $babysit now** then $HOME";
317 const disabled = { ...babysit, enabled: false };
318 const agentOnly = { ...babysit, userInvocable: false };
307 - const editor = await mountEditor(value, true, [disabled]);
319 + await using screen = await mountEditor(value, true, [disabled]);
320 + const { editor } = screen;
321 expect.soft(editor.state.doc.textContent).toBe("run use $babysit now then $HOME");
309 - await mountEditor(value, true, [agentOnly]);
322 + await screen.update(value, true, [agentOnly]);
323 expect.soft(editor.state.doc.textContent).toBe("run use $babysit now then $HOME");
324 await act(async () => {
325 editor.commands.setTextSelection("run use $baby".length + 1);
326 });
314 - await mountEditor(value, true, [disabled, babysit]);
327 + await screen.update(value, true, [disabled, babysit]);
328 expect(editor.state.doc.textContent).toBe("run use now then $HOME");
329 const chip = serializeEditorDoc(editor.state.doc).runs.find((run) => run.kind === "token")!;
330 expect(editor.state.selection.from).toBe(chip.pmPos + 1);
318 - await mountEditor(value, true, [disabled]);
331 + await screen.update(value, true, [disabled]);
332 expect.soft(editor.state.doc.textContent).toBe("run use $babysit now then $HOME");
333 expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
334 await act(async () => {
@@ -328,25 +341,25 @@ it("reconciles provider skills and metadata without losing formatting, caret, or
341 expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
342 expect(editor.state.doc.textContent).toBe("run use $babysit now then $HOME");
343
331 - await mountEditor(value, true, [babysit]);
344 + await screen.update(value, true, [babysit]);
345 await act(async () => {
346 editor.commands.deleteRange({ from: chip.pmPos, to: chip.pmPos + 1 });
347 });
335 - await mountEditor(value, true, [agentOnly]);
348 + await screen.update(value, true, [agentOnly]);
349 await act(async () => {
350 editor.commands.undo();
351 });
352 expect(editor.state.doc.textContent).toBe("run use $babysit now then $HOME");
353 expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
354
342 - await mountEditor(value, true, [{ ...babysit, description: "Previous provider description" }]);
355 + await screen.update(value, true, [{ ...babysit, description: "Previous provider description" }]);
356 await act(async () => {
344 - container
357 + screen.container
358 .querySelector<HTMLButtonElement>('[aria-label="Skill Babysit. Show details"]')!
359 .click();
360 });
361 expect(document.body.textContent).toContain("Previous provider description");
349 - await mountEditor(value, true, [
362 + await screen.update(value, true, [
363 { ...disabled, displayName: "Disabled Babysit" },
364 {
365 ...babysit,
@@ -354,11 +367,11 @@ it("reconciles provider skills and metadata without losing formatting, caret, or
367 shortDescription: " Current short description ",
368 },
369 ]);
357 - expect(container.textContent).toContain("Current Babysit");
370 + expect(screen.container.textContent).toContain("Current Babysit");
371 expect(document.body.textContent).toContain("Current short description");
372 expect(document.body.textContent).not.toContain("Previous provider description");
360 - await mountEditor(value, true, [{ ...babysit, displayName: "Current Babysit" }]);
361 - expect(container.textContent).toContain("Current Babysit");
373 + await screen.update(value, true, [{ ...babysit, displayName: "Current Babysit" }]);
374 + expect(screen.container.textContent).toContain("Current Babysit");
375 expect(document.body.textContent).not.toContain("Current short description");
376 expect(document.body.textContent).toContain("No description is available for this skill.");
377 expect(document.body.textContent).not.toContain("Previous provider description");
@@ -431,18 +444,14 @@ describe("composer context undo lifetime", () => {
444 return createElement(ComposerPromptEditor, editorProps);
445 }
446
434 - const render = async (targetKey: string) => {
435 - await act(async () => root.render(createElement(Composer, { targetKey })));
436 - };
437 - const editor = () => {
438 - const element = container.querySelector<HTMLElement & { editor: Editor }>(".tiptap");
439 - if (!element) throw new Error("Composer did not mount");
440 - return element.editor;
441 - };
442 - await render("a");
443 - return {
447 + await using stack = new AsyncDisposableStack();
448 + const screen = stack.use(await render(createElement(Composer, { targetKey: "a" })));
449 + const editor = () => editorIn(screen.container);
450 + const environment = stack.move();
451 + return Object.assign(screen, {
452 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
453 initialValue,
445 - render,
454 + show: (targetKey: string) => screen.rerender(createElement(Composer, { targetKey })),
455 editor,
456 draft: () => current,
457 retained: () => retained,
@@ -459,11 +468,11 @@ describe("composer context undo lifetime", () => {
468 editor().commands.undo();
469 });
470 },
462 - };
471 + });
472 }
473
474 it("preserves typing focus across draft switches without taking focus from another control", async () => {
466 - const composer = await mountComposer("Draft B");
475 + await using composer = await mountComposer("Draft B");
476 const previousEditor = composer.editor();
477 await act(async () => {
478 previousEditor.commands.setTextSelection(previousEditor.state.doc.content.size - 1);
@@ -471,7 +480,7 @@ describe("composer context undo lifetime", () => {
480 });
481 expect(document.activeElement).toBe(previousEditor.view.dom);
482
474 - await composer.render("b");
483 + await composer.show("b");
484 const nextEditor = composer.editor();
485 expect(nextEditor).not.toBe(previousEditor);
486 expect(document.activeElement).toBe(nextEditor.view.dom);
@@ -479,48 +488,47 @@ describe("composer context undo lifetime", () => {
488 expect(composer.draft().value).toBe("xDraft B");
489
490 const button = document.createElement("button");
482 - container.append(button);
491 + composer.container.append(button);
492 button.focus();
484 - await composer.render("a");
493 + await composer.show("a");
494 expect(document.activeElement).toBe(button);
495 expect(composer.draft().value).toBe(composer.initialValue);
496 });
497
498 it("restores a deleted chip and its file bytes on same-draft undo, then releases them on unmount", async () => {
490 - const composer = await mountComposer();
499 + await using composer = await mountComposer();
500 await composer.deleteDraft();
501 expect(composer.draft()).toEqual({ value: "", files: [] });
502 const retained = composer.retained();
503 expect(retained.files.get(fileContextReference(file).contextId)?.file).toBe(file.file);
504
496 - await composer.render("a");
505 + await composer.show("a");
506 await composer.undo();
507 expect(serializeEditorDoc(composer.editor().state.doc).value).toBe(composer.initialValue);
508 expect(composer.draft()).toEqual({ value: composer.initialValue, files: [file] });
509 expect(composer.draft().files[0]?.file).toBe(file.file);
510
511 await composer.deleteDraft();
503 - await act(async () => root.unmount());
512 + await composer.unmount();
513 expect(retained.files.size).toBe(0);
505 - root = createRoot(container);
514 });
515
516 it.each(["", "Draft B"])(
517 "releases deleted payloads and prevents undo into the previous draft when switching to %j",
518 async (destinationValue) => {
511 - const composer = await mountComposer(destinationValue);
519 + await using composer = await mountComposer(destinationValue);
520 await composer.deleteDraft();
521 expect(composer.draft()).toEqual({ value: "", files: [] });
522 const retained = composer.retained();
523 expect(retained.files.get(fileContextReference(file).contextId)?.file).toBe(file.file);
524
517 - await composer.render("b");
525 + await composer.show("b");
526 expect(retained.files.size).toBe(0);
527 await composer.undo();
528 expect(serializeEditorDoc(composer.editor().state.doc).value).toBe(destinationValue);
529 expect(composer.draft()).toEqual({ value: destinationValue, files: [] });
530
523 - await composer.render("a");
531 + await composer.show("a");
532 await composer.undo();
533 expect(serializeEditorDoc(composer.editor().state.doc).value).toBe("");
534 expect(composer.draft()).toEqual({ value: "", files: [] });
apps/web/src/components/ComposerPromptEditorTiptap.navigation.browser.test.tsx
+53 -53
@@ -1,52 +1,37 @@
1 import type { Editor } from "@tiptap/core";
2 import { TextSelection } from "@tiptap/pm/state";
3 -import { act, createRef } from "react";
4 -import { createRoot, type Root } from "react-dom/client";
5 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 +import { createRef } from "react";
4 +import { describe, expect, it, vi } from "vite-plus/test";
5
6 +import { act, render } from "../../test/render";
7 import { serializeEditorDoc } from "~/composer-rich-text-doc";
8 import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";
9
10 const draft =
11 "> **Assistant and reasoning text still save intermediate full snapshots**, using the existing 50 ms batching. Compaction still preserves their `turn-item.updated` events. [Code](/Users/yashsingh/p/projects/t3code/apps/server/src/orchestration-v2/ProjectionMaintenance.ts:235)";
12
13 -let root: Root;
14 -let container: HTMLDivElement;
15 -
16 -beforeEach(() => {
17 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
18 - container = document.createElement("div");
19 - document.body.append(container);
20 - root = createRoot(container);
21 -});
22 -
23 -afterEach(async () => {
24 - await act(async () => root.unmount());
25 - container.remove();
26 - vi.restoreAllMocks();
27 - vi.unstubAllGlobals();
28 -});
29 -
30 -async function mountEditor(value: string, richTextEnabled = true) {
31 - await act(async () =>
32 - root.render(
33 - <ComposerPromptEditor
34 - editorRef={createRef<ComposerPromptEditorHandle>()}
35 - value={value}
36 - cursor={0}
37 - richTextEnabled={richTextEnabled}
38 - contextRecords={new Map()}
39 - skills={[]}
40 - disabled={false}
41 - placeholder=""
42 - onChange={() => {}}
43 - onPaste={() => {}}
44 - />,
45 - ),
13 +async function mountEditor(value: string, richTextEnabled = true, container?: HTMLElement) {
14 + const screen = await render(
15 + <ComposerPromptEditor
16 + editorRef={createRef<ComposerPromptEditorHandle>()}
17 + value={value}
18 + cursor={0}
19 + richTextEnabled={richTextEnabled}
20 + contextRecords={new Map()}
21 + skills={[]}
22 + disabled={false}
23 + placeholder=""
24 + onChange={() => {}}
25 + onPaste={() => {}}
26 + />,
27 + container ? { container } : {},
28 );
47 - const element = container.querySelector<HTMLElement & { editor: Editor }>(".tiptap");
48 - if (!element) throw new Error("Composer did not mount");
49 - return element.editor;
29 + const element = screen.container.querySelector<HTMLElement & { editor: Editor }>(".tiptap");
30 + if (!element) {
31 + await screen[Symbol.asyncDispose]();
32 + throw new Error("Composer did not mount");
33 + }
34 + return Object.assign(screen, { editor: element.editor });
35 }
36
37 function press(editor: Editor, key: string, options: KeyboardEventInit = {}) {
@@ -57,7 +42,8 @@ function press(editor: Editor, key: string, options: KeyboardEventInit = {}) {
42 }
43
44 it("keeps Up before the opening bold marker in a quote, including while typing", async () => {
60 - const editor = await mountEditor(draft);
45 + await using screen = await mountEditor(draft);
46 + const { editor } = screen;
47 const position = editor.state.selection.from;
48 await act(async () => {
49 editor.view.focus();
@@ -77,7 +63,8 @@ it("keeps Up before the opening bold marker in a quote, including while typing",
63 });
64
65 it("keeps Down after a closing marker, including while typing", async () => {
80 - const editor = await mountEditor("> **bold**");
66 + await using screen = await mountEditor("> **bold**");
67 + const { editor } = screen;
68 await act(async () => {
69 editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
70 expect(press(editor, "ArrowDown")).toBe(true);
@@ -88,7 +75,8 @@ it("keeps Down after a closing marker, including while typing", async () => {
75 });
76
77 it("leaves vertical navigation between paragraphs to the browser", async () => {
91 - const editor = await mountEditor("**first**\n**second**");
78 + await using screen = await mountEditor("**first**\n**second**");
79 + const { editor } = screen;
80 await act(async () => {
81 const first = editor.state.doc.child(0);
82 editor.commands.setTextSelection(first.nodeSize + 1);
@@ -101,7 +89,8 @@ it("leaves vertical navigation between paragraphs to the browser", async () => {
89 it.each([{ shiftKey: true }, { altKey: true }, { ctrlKey: true }, { isComposing: true }])(
90 "preserves modified Up behavior for %j",
91 async (options) => {
104 - const editor = await mountEditor(draft);
92 + await using screen = await mountEditor(draft);
93 + const { editor } = screen;
94 await act(async () => {
95 expect(press(editor, "ArrowUp", options)).toBe(false);
96 editor.commands.insertContent("x");
@@ -111,10 +100,11 @@ it.each([{ shiftKey: true }, { altKey: true }, { ctrlKey: true }, { isComposing:
100 );
101
102 describe("macOS boundary navigation", () => {
114 - beforeEach(() => {
115 - vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
103 + function macContainer() {
104 + const container = document.createElement("div");
105 container.style.width = "600px";
117 - });
106 + return container;
107 + }
108
109 const markdown = String.raw`Fixed the top padding to 16px and updated the offline index and ZIP.
110
@@ -129,7 +119,9 @@ The original Fall 2022, 2023, and 2024 sample exams also have circle-constrained
119 it.each(["ArrowRight", "ArrowDown"])(
120 "keeps Command-%s after the closing marker in the pasted draft",
121 async (key) => {
132 - const editor = await mountEditor(markdown);
122 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
123 + await using screen = await mountEditor(markdown, true, macContainer());
124 + const { editor } = screen;
125 await act(async () => {
126 editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
127 editor.view.focus();
@@ -156,7 +148,9 @@ The original Fall 2022, 2023, and 2024 sample exams also have circle-constrained
148 it.each(["ArrowRight", "ArrowDown"])(
149 "moves Command-%s from inside bold to outside its closing marker",
150 async (key) => {
159 - const editor = await mountEditor("**bold**");
151 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
152 + await using screen = await mountEditor("**bold**", true, macContainer());
153 + const { editor } = screen;
154 await act(async () => {
155 editor.commands.setTextSelection(3);
156 editor.view.focus();
@@ -168,7 +162,9 @@ The original Fall 2022, 2023, and 2024 sample exams also have circle-constrained
162 );
163
164 it.each(["ArrowLeft", "ArrowUp"])("moves Command-%s before the opening marker", async (key) => {
171 - const editor = await mountEditor("**bold**");
165 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
166 + await using screen = await mountEditor("**bold**", true, macContainer());
167 + const { editor } = screen;
168 await act(async () => {
169 editor.commands.setTextSelection(3);
170 editor.view.focus();
@@ -181,7 +177,9 @@ The original Fall 2022, 2023, and 2024 sample exams also have circle-constrained
177 it.each(["ArrowRight", "ArrowDown"])(
178 "extends Shift-Command-%s to the end without collapsing the selection",
179 async (key) => {
184 - const editor = await mountEditor("**bold**");
180 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
181 + await using screen = await mountEditor("**bold**", true, macContainer());
182 + const { editor } = screen;
183 await act(async () => {
184 editor.commands.setTextSelection(3);
185 editor.view.focus();
@@ -195,8 +193,9 @@ The original Fall 2022, 2023, and 2024 sample exams also have circle-constrained
193 );
194
195 it("leaves Command-arrow navigation to the browser on other platforms", async () => {
198 - vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
199 - const editor = await mountEditor("**bold**");
196 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
197 + await using screen = await mountEditor("**bold**", true, macContainer());
198 + const { editor } = screen;
199 await act(async () => {
200 editor.view.focus();
201 expect(press(editor, "ArrowDown", { metaKey: true })).toBe(false);
@@ -205,7 +204,8 @@ The original Fall 2022, 2023, and 2024 sample exams also have circle-constrained
204 });
205
206 it("leaves literal Markdown navigation to the browser in plain mode", async () => {
208 - const editor = await mountEditor(draft, false);
207 + await using screen = await mountEditor(draft, false);
208 + const { editor } = screen;
209 await act(async () => {
210 editor.commands.setTextSelection(5);
211 expect(press(editor, "ArrowUp")).toBe(false);
apps/web/src/components/DiffPanel.browser.test.tsx
+57 -58
@@ -12,11 +12,11 @@ import {
12 import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
13 import * as DateTime from "effect/DateTime";
14 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
15 -import { act } from "react";
16 -import { createRoot, type Root } from "react-dom/client";
17 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
15 +import { expect, it, vi } from "vite-plus/test";
16 import { page } from "vite-plus/test/browser";
17
18 +import { act, render } from "../../test/render";
19 +
20 vi.mock("../hooks/useThreadRouteTarget", () => ({
21 useThreadRouteRef: () => threadRef,
22 useThreadRouteTarget: () => ({ ...threadRef, kind: "thread" }),
@@ -112,65 +112,62 @@ const patchAtoms = Atom.family((path: string) =>
112 path === "e.txt" ? AsyncResult.initial() : AsyncResult.success(loadedPatch(path)),
113 ),
114 );
115 -let registry: AtomRegistry.AtomRegistry;
116 -let container: HTMLDivElement;
117 -let root: Root;
118 -
119 -beforeEach(() => {
120 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
115 +function setup() {
116 localStorage.setItem("t3code.diffFileTreeOpen", "true");
117 useDiffPanelStore.setState({ byThreadKey: {}, branchBaseRefByThreadKey: {} });
123 - registry = AtomRegistry.make();
124 - container = document.createElement("div");
118 + const registry = AtomRegistry.make();
119 + return {
120 + registry,
121 + [Symbol.dispose]() {
122 + registry.dispose();
123 + localStorage.clear();
124 + },
125 + };
126 +}
127 +function renderPanel(registry: AtomRegistry.AtomRegistry) {
128 + const container = document.createElement("div");
129 container.style.cssText = "width: 1000px; height: 300px";
126 - document.body.append(container);
127 - root = createRoot(container);
128 -});
129 -afterEach(async () => {
130 - await act(async () => root.unmount());
131 - container.remove();
132 - registry.dispose();
133 - localStorage.clear();
134 - vi.unstubAllGlobals();
135 -});
136 -async function render() {
137 - await act(async () =>
138 - root.render(
139 - <RegistryContext.Provider value={registry}>
140 - <DiffPanel
141 - visible
142 - mode="embedded"
143 - composerDraftTarget={threadRef}
144 - workspaceMutationId={null}
145 - />
146 - </RegistryContext.Provider>,
147 - ),
130 + return render(
131 + <RegistryContext.Provider value={registry}>
132 + <DiffPanel
133 + visible
134 + mode="embedded"
135 + composerDraftTarget={threadRef}
136 + workspaceMutationId={null}
137 + />
138 + </RegistryContext.Provider>,
139 + { container },
140 );
141 }
142 const toggle = (path: string, expanded: boolean) =>
143 page.getByRole("button", { name: `${expanded ? "Collapse" : "Expand"} ${path}`, exact: true });
152 -const viewport = () => container.querySelector<HTMLElement>(".diff-render-surface")!;
144 +const viewport = (container: HTMLElement) =>
145 + container.querySelector<HTMLElement>(".diff-render-surface")!;
146 async function selectTurn(path?: string, turn = turns[0]!) {
147 await act(async () => useDiffPanelStore.getState().selectTurn(threadRef, turn.runId, path));
148 }
156 -async function expectRevealed(path: string) {
149 +async function expectRevealed(container: HTMLElement, path: string) {
150 await expect.element(toggle(path, true)).toBeInTheDocument();
151 await expect
152 .poll(() => {
160 - const bounds = viewport().getBoundingClientRect();
153 + const bounds = viewport(container).getBoundingClientRect();
154 const header = toggle(path, true).element().getBoundingClientRect();
162 - return viewport().scrollTop > 0 && header.top >= bounds.top && header.bottom <= bounds.bottom;
155 + return (
156 + viewport(container).scrollTop > 0 &&
157 + header.top >= bounds.top &&
158 + header.bottom <= bounds.bottom
159 + );
160 })
161 .toBe(true);
162 }
166 -async function scrollToStart() {
163 +async function scrollToStart(container: HTMLElement) {
164 await act(async () => {
168 - viewport().scrollTop = 0;
169 - viewport().dispatchEvent(new Event("scroll"));
165 + viewport(container).scrollTop = 0;
166 + viewport(container).dispatchEvent(new Event("scroll"));
167 await new Promise(requestAnimationFrame);
168 });
169 }
173 -async function selectTreeFile(path: string) {
170 +async function selectTreeFile(container: HTMLElement, path: string) {
171 const tree = container.querySelector("file-tree-container")!;
172 const row = tree.shadowRoot!.querySelector<HTMLElement>(`[data-item-path="${path}"]`)!;
173 await act(async () =>
@@ -181,30 +178,31 @@ async function selectTreeFile(path: string) {
178 }
179
180 it("reveals a delayed turn selection, preserves siblings, and repeats after scope changes", async () => {
181 + using env = setup();
182 await selectTurn("e.txt");
185 - await render();
183 + await using screen = await renderPanel(env.registry);
184 await expect
185 .element(page.getByRole("status", { name: "Loading checkpoint diff..." }))
186 .toBeInTheDocument();
189 - await act(async () => registry.set(checkpointAtom, paths.map(filePatch).join("")));
190 - await expectRevealed("e.txt");
187 + await act(async () => env.registry.set(checkpointAtom, paths.map(filePatch).join("")));
188 + await expectRevealed(screen.container, "e.txt");
189 await act(async () => useDiffPanelStore.getState().selectGitScope(threadRef, "branch"));
190 await expect.element(toggle("a.txt", false)).toBeInTheDocument();
191 await selectTurn("e.txt");
194 - await expectRevealed("e.txt");
195 - await scrollToStart();
192 + await expectRevealed(screen.container, "e.txt");
193 + await scrollToStart(screen.container);
194 await toggle("a.txt", false).click();
195 await selectTurn("b.txt");
196 await expect.element(toggle("b.txt", true)).toBeInTheDocument();
197 await toggle("b.txt", true).click();
198 await selectTurn("e.txt");
201 - await expectRevealed("e.txt");
202 - await scrollToStart();
199 + await expectRevealed(screen.container, "e.txt");
200 + await scrollToStart(screen.container);
201 await expect.element(toggle("a.txt", true)).toBeInTheDocument();
202 await expect.element(toggle("b.txt", false)).toBeInTheDocument();
203 await expect.element(toggle("c.txt", false)).toBeInTheDocument();
204 await selectTurn("e.txt");
207 - await expectRevealed("e.txt");
205 + await expectRevealed(screen.container, "e.txt");
206
207 await selectTurn(undefined, turns[1]!);
208 await expect.element(toggle("a.txt", false)).toBeInTheDocument();
@@ -212,21 +210,22 @@ it("reveals a delayed turn selection, preserves siblings, and repeats after scop
210 });
211
212 it("waits for a lazy Git patch while preserving sibling choices and expanded defaults", async () => {
215 - registry.set(collapsedAtom, false);
216 - await render();
213 + using env = setup();
214 + env.registry.set(collapsedAtom, false);
215 + await using screen = await renderPanel(env.registry);
216 await toggle("b.txt", true).click();
218 - await selectTreeFile("b.txt");
217 + await selectTreeFile(screen.container, "b.txt");
218 await expect.element(toggle("b.txt", true)).toBeInTheDocument();
219 await toggle("b.txt", true).click();
221 - await scrollToStart();
222 - await selectTreeFile("e.txt");
223 - expect(viewport().scrollTop).toBe(0);
220 + await scrollToStart(screen.container);
221 + await selectTreeFile(screen.container, "e.txt");
222 + expect(viewport(screen.container).scrollTop).toBe(0);
223 await expect.element(toggle("e.txt", true)).not.toBeInTheDocument();
224 await act(async () =>
226 - registry.set(patchAtoms("e.txt"), AsyncResult.success(loadedPatch("e.txt"))),
225 + env.registry.set(patchAtoms("e.txt"), AsyncResult.success(loadedPatch("e.txt"))),
226 );
228 - await expectRevealed("e.txt");
229 - await scrollToStart();
227 + await expectRevealed(screen.container, "e.txt");
228 + await scrollToStart(screen.container);
229 await expect.element(toggle("a.txt", true)).toBeInTheDocument();
230 await expect.element(toggle("b.txt", false)).toBeInTheDocument();
231 await act(async () => useDiffPanelStore.getState().selectGitScope(threadRef, "unstaged"));
apps/web/src/components/GitActionsControl.browser.test.tsx
+54 -51
@@ -6,12 +6,12 @@ import {
6 } from "@t3tools/contracts";
7 import * as Cause from "effect/Cause";
8 import { AsyncResult } from "effect/reactivity";
9 -import { act, memo } from "react";
10 -import { createRoot, type Root } from "react-dom/client";
11 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
9 +import { memo } from "react";
10 +import { describe, expect, it, vi } from "vite-plus/test";
11 import { page, userEvent } from "vite-plus/test/browser";
12
13 import "~/index.css";
14 +import { act, render } from "../../test/render";
15
16 type Branched = { readonly branch: string };
17 type GitActionInput = { featureBranch?: boolean; threadId?: string; action: string };
@@ -168,20 +168,15 @@ import GitActionsControl from "./GitActionsControl";
168 // ThreadDetailsPanel keeps this component mounted behind React.memo when threads change.
169 const MemoGitActionsControl = memo(GitActionsControl);
170
171 -let root: Root;
172 -let container: HTMLDivElement;
173 -
174 -function render(thread = "thread", cwd = "/repo") {
175 - return act(async () =>
176 - root.render(
177 - <MemoGitActionsControl
178 - gitCwd={cwd}
179 - activeThreadRef={{
180 - environmentId: EnvironmentId.make("environment"),
181 - threadId: ThreadId.make(thread),
182 - }}
183 - />,
184 - ),
171 +function control(thread = "thread", cwd = "/repo") {
172 + return (
173 + <MemoGitActionsControl
174 + gitCwd={cwd}
175 + activeThreadRef={{
176 + environmentId: EnvironmentId.make("environment"),
177 + threadId: ThreadId.make(thread),
178 + }}
179 + />
180 );
181 }
182
@@ -195,8 +190,8 @@ async function openCommitDialog() {
190 await expect.element(page.getByRole("dialog", { name: "Commit changes" })).toBeVisible();
191 }
192
198 -beforeEach(() => {
199 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
193 +// The mocked modules read `state`, so every test starts by resetting all of it.
194 +function setup() {
195 state.scopes = new Set([AuthSourceControlWriteScope]);
196 state.primaryScopes = new Set([AuthSourceControlWriteScope, AuthOrchestrationOperateScope]);
197 state.shell = { branch: "main" };
@@ -218,21 +213,12 @@ beforeEach(() => {
213 if (state.draft && input.branch) state.draft = { ...state.draft, branch: input.branch };
214 },
215 });
221 - container = document.createElement("div");
222 - document.body.append(container);
223 - root = createRoot(container);
224 -});
225 -
226 -afterEach(async () => {
227 - await act(async () => root.unmount());
228 - container.remove();
229 - vi.unstubAllGlobals();
230 - await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')).toBeNull());
231 -});
216 +}
217
218 describe("Git actions while thread details load", () => {
219 it("does not offer a feature branch for a server thread without task permission", async () => {
235 - await render();
220 + setup();
221 + await using _screen = await render(control());
222 await openCommitDialog();
223
224 // The primary environment's task grant must not leak into this thread's environment.
@@ -241,8 +227,9 @@ describe("Git actions while thread details load", () => {
227 });
228
229 it("checks the task grant again when the feature-branch commit runs", async () => {
230 + setup();
231 state.scopes.add(AuthOrchestrationOperateScope);
245 - await render();
232 + await using _screen = await render(control());
233 await openCommitDialog();
234 state.scopes.delete(AuthOrchestrationOperateScope);
235
@@ -254,9 +241,10 @@ describe("Git actions while thread details load", () => {
241 });
242
243 it("commits and synchronizes the server thread before details finish loading", async () => {
244 + setup();
245 state.primaryScopes.clear();
246 state.scopes.add(AuthOrchestrationOperateScope);
259 - await render();
247 + await using _screen = await render(control());
248 await openCommitDialog();
249 await userEvent.click(button("Commit on new branch"));
250
@@ -267,11 +255,12 @@ describe("Git actions while thread details load", () => {
255 });
256
257 it("synchronizes archived thread detail after its shell disappears", async () => {
258 + setup();
259 state.scopes.add(AuthOrchestrationOperateScope);
260 state.detail = { branch: "main" };
272 - await render();
261 + await using screen = await render(control());
262 state.shell = null;
274 - await render();
263 + await screen.rerender(control());
264 await openCommitDialog();
265 await userEvent.click(button("Commit on new branch"));
266
@@ -281,9 +270,10 @@ describe("Git actions while thread details load", () => {
270 });
271
272 it("requires task permission before changing an archived thread's branch", async () => {
273 + setup();
274 state.shell = null;
275 state.detail = { branch: "main" };
286 - await render();
276 + await using _screen = await render(control());
277 await openCommitDialog();
278
279 await expect.element(button("Commit on new branch")).toBeDisabled();
@@ -291,9 +281,10 @@ describe("Git actions while thread details load", () => {
281 });
282
283 it("uses the current shell branch when cached detail names the new branch", async () => {
284 + setup();
285 state.scopes.add(AuthOrchestrationOperateScope);
286 state.detail = { branch: "feature" };
296 - await render();
287 + await using _screen = await render(control());
288 await openCommitDialog();
289 await userEvent.click(button("Commit on new branch"));
290
@@ -307,9 +298,10 @@ describe("Git actions while thread details load", () => {
298 ] as const)(
299 "uses the fresh task grant after Git finishes, revoking %s",
300 async (revokedScope, syncsThread) => {
301 + setup();
302 state.scopes.add(AuthOrchestrationOperateScope);
303 state.afterGitAction = () => state.scopes.delete(revokedScope);
312 - await render();
304 + await using _screen = await render(control());
305 await openCommitDialog();
306 await userEvent.click(button("Commit on new branch"));
307
@@ -321,7 +313,8 @@ describe("Git actions while thread details load", () => {
313 );
314
315 it("keeps ordinary commits available while details load", async () => {
324 - await render();
316 + setup();
317 + await using _screen = await render(control());
318 await openCommitDialog();
319 await userEvent.click(button("Commit"));
320
@@ -331,9 +324,10 @@ describe("Git actions while thread details load", () => {
324 });
325
326 it("keeps feature-branch commits available for a local draft", async () => {
327 + setup();
328 state.shell = null;
329 state.draft = { branch: "main", worktreePath: null, envMode: "local" };
336 - await render();
330 + await using _screen = await render(control());
331 await openCommitDialog();
332 await userEvent.click(button("Commit on new branch"));
333
@@ -344,17 +338,19 @@ describe("Git actions while thread details load", () => {
338 });
339
340 describe("Changed-file editor targets", () => {
347 - beforeEach(() => {
341 + function setupNestedFiles() {
342 + setup();
343 state.scopes.add(AuthOrchestrationOperateScope);
344 state.files = [
345 { path: "nested/new.txt", insertions: 0, deletions: 0 },
346 { path: "nested/tracked.txt", insertions: 1, deletions: 0 },
347 ];
353 - });
348 + }
349
350 it("resolves repository-relative paths against the status root, not the project cwd", async () => {
351 + setupNestedFiles();
352 state.workingTreeRoot = "/repo";
357 - await render("thread", "/repo/nested");
353 + await using _screen = await render(control("thread", "/repo/nested"));
354 await openCommitDialog();
355
356 await userEvent.click(button("Open nested/new.txt in editor"));
@@ -371,7 +367,8 @@ describe("Changed-file editor targets", () => {
367 });
368
369 it("does not guess a file location when the server reports no root", async () => {
374 - await render("thread", "/repo/nested");
370 + setupNestedFiles();
371 + await using _screen = await render(control("thread", "/repo/nested"));
372 await openCommitDialog();
373
374 await expect.element(button("Open nested/new.txt in editor")).toBeDisabled();
@@ -380,13 +377,15 @@ describe("Changed-file editor targets", () => {
377 });
378
379 describe("Default branch prompt", () => {
383 - beforeEach(() => {
380 + function setupDefaultRef() {
381 + setup();
382 state.isDefaultRef = true;
383 state.scopes.add(AuthOrchestrationOperateScope);
386 - });
384 + }
385
386 it("moves the commit to a feature branch when asked", async () => {
389 - await render();
387 + setupDefaultRef();
388 + await using _screen = await render(control());
389 await userEvent.click(button(/^Commit & push/));
390 await expect
391 .element(page.getByRole("dialog", { name: "Commit & push to default ref?" }))
@@ -400,7 +399,8 @@ describe("Default branch prompt", () => {
399 });
400
401 it("checks the task grant again when the feature branch is chosen", async () => {
403 - await render();
402 + setupDefaultRef();
403 + await using _screen = await render(control());
404 await userEvent.click(button(/^Commit & push/));
405 await expect
406 .element(page.getByRole("dialog", { name: "Commit & push to default ref?" }))
@@ -418,12 +418,13 @@ describe("Git action targets across thread navigation", () => {
418 const quickAction = () => button(/^Commit, push & /);
419
420 it("runs a retained PR toast in the thread that produced it", async () => {
421 - await render("first", "/first");
421 + setup();
422 + await using screen = await render(control("first", "/first"));
423 await userEvent.click(quickAction());
424 await vi.waitFor(() => expect(state.toasts.some((toast) => toast.actionProps)).toBe(true));
425 const toast = state.toasts.find((toast) => toast.actionProps)!;
426
426 - await render("second", "/second");
427 + await screen.rerender(control("second", "/second"));
428 await act(async () => toast.actionProps!.onClick());
429
430 expect(state.actions.at(-1)).toMatchObject({
@@ -433,12 +434,14 @@ describe("Git action targets across thread navigation", () => {
434 });
435
436 it("runs the memoized button in the current thread after navigation", async () => {
437 + setup();
438 + await using screen = await render(control("first", "/first"));
439 for (const [thread, cwd] of [
440 ["first", "/first"],
441 ["second", "/second"],
442 ["first", "/first"],
443 ] as const) {
441 - await render(thread, cwd);
444 + await screen.rerender(control(thread, cwd));
445 await userEvent.click(quickAction());
446 await vi.waitFor(() =>
447 expect(state.actions.at(-1)).toMatchObject({ scope: { cwd }, input: { threadId: thread } }),
apps/web/src/components/HostedEmptyState.browser.test.tsx
+7 -19
@@ -2,9 +2,9 @@ import type { Discovery } from "@t3tools/client-runtime/relay";
2 import { EnvironmentId } from "@t3tools/contracts";
3 import * as Option from "effect/Option";
4 import { AsyncResult } from "effect/reactivity";
5 -import { act } from "react";
6 -import { createRoot, type Root } from "react-dom/client";
7 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
5 +import { expect, it, vi } from "vite-plus/test";
6 +
7 +import { act, render } from "../../test/render";
8
9 type DiscoveredEnvironments = Discovery.RelayEnvironmentDiscoveryState["environments"];
10 type Availability = "checking" | "online";
@@ -83,11 +83,7 @@ async function publish(environments: DiscoveredEnvironments) {
83 const registeredIds = () =>
84 discovery.register.mock.calls.map(([registration]) => registration.target.environmentId);
85
86 -let root: Root;
87 -let container: HTMLDivElement;
88 -
89 -beforeEach(() => {
90 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
86 +function setup() {
87 discovery.listeners.clear();
88 discovery.state = {
89 environments: new Map(),
@@ -96,21 +92,13 @@ beforeEach(() => {
92 error: Option.none(),
93 };
94 discovery.register.mockReset().mockResolvedValue(AsyncResult.success(undefined));
99 - container = document.createElement("div");
100 - document.body.append(container);
101 - root = createRoot(container);
102 -});
103 -
104 -afterEach(async () => {
105 - await act(async () => root.unmount());
106 - container.remove();
107 - vi.unstubAllGlobals();
108 -});
95 +}
96
97 // The first added computer replaces this screen with the app, so every
98 // registration has to start in the same pass, after all health checks finish.
99 it("adds every linked computer only after discovery finishes checking them", async () => {
113 - await act(async () => root.render(<T3ConnectSteps />));
100 + setup();
101 + await using _screen = await render(<T3ConnectSteps />);
102
103 await publish(linked({ [laptopId]: "checking", [desktopId]: "checking" }));
104 await publish(linked({ [laptopId]: "online", [desktopId]: "checking" }));
apps/web/src/components/KeybindingsConfigWarning.browser.test.tsx
+23 -32
@@ -6,9 +6,9 @@ import {
6 type AuthSessionState,
7 } from "@t3tools/contracts";
8 import { AsyncResult, Atom } from "effect/reactivity";
9 -import { act } from "react";
10 -import { createRoot, type Root } from "react-dom/client";
11 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
9 +import { expect, it, vi } from "vite-plus/test";
10 +
11 +import { act, render } from "../../test/render";
12
13 type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
14 const state = vi.hoisted(() => ({
@@ -40,8 +40,6 @@ import { appAtomRegistry } from "../rpc/atomRegistry";
40 import { KeybindingsConfigWarning } from "./KeybindingsConfigWarning";
41
42 const environmentId = EnvironmentId.make("warning-environment");
43 -let root: Root;
44 -let container: HTMLDivElement;
43 const session = (scopes: readonly AuthEnvironmentScope[]): AuthSessionState => ({
44 authenticated: true,
45 scopes,
@@ -54,10 +52,8 @@ const session = (scopes: readonly AuthEnvironmentScope[]): AuthSessionState => (
52 });
53 const setScopes = (scopes: readonly AuthEnvironmentScope[]) =>
54 appAtomRegistry.set(state.sessions.get(environmentId)!, AsyncResult.success(session(scopes)));
57 -const button = () => container.querySelector("button")!;
55
59 -beforeEach(() => {
60 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
56 +function setup(): Disposable {
57 localStorage.setItem("t3code:last-editor", JSON.stringify("vscode"));
58 state.sessions.set(
59 environmentId,
@@ -67,33 +63,28 @@ beforeEach(() => {
63 );
64 state.run.mockReset().mockResolvedValue(AsyncResult.success(undefined));
65 state.toast.mockReset();
70 - container = document.createElement("div");
71 - document.body.append(container);
72 - root = createRoot(container);
73 -});
74 -
75 -afterEach(async () => {
76 - await act(async () => root.unmount());
77 - container.remove();
78 - localStorage.clear();
79 - state.sessions.clear();
80 - vi.unstubAllGlobals();
81 -});
66 + return {
67 + [Symbol.dispose]() {
68 + localStorage.clear();
69 + state.sessions.clear();
70 + },
71 + };
72 +}
73
74 it("updates a visible warning on revocation and blocks a click that raced it until regrant", async () => {
84 - await act(async () =>
85 - root.render(
86 - <RegistryContext.Provider value={appAtomRegistry}>
87 - <KeybindingsConfigWarning
88 - environmentId={environmentId}
89 - configPath="/t3/keybindings.json"
90 - availableEditors={["vscode"]}
91 - message="Invalid shortcut"
92 - />
93 - </RegistryContext.Provider>,
94 - ),
75 + using _state = setup();
76 + await using screen = await render(
77 + <RegistryContext.Provider value={appAtomRegistry}>
78 + <KeybindingsConfigWarning
79 + environmentId={environmentId}
80 + configPath="/t3/keybindings.json"
81 + availableEditors={["vscode"]}
82 + message="Invalid shortcut"
83 + />
84 + </RegistryContext.Provider>,
85 );
96 - expect(container.textContent).toContain("Invalid shortcut");
86 + const button = () => screen.container.querySelector("button")!;
87 + expect(screen.container.textContent).toContain("Invalid shortcut");
88 expect(button().disabled).toBe(false);
89
90 // The click lands before React re-renders the revoked grant.
apps/web/src/components/PermissionUpdateNotice.browser.test.tsx
+23 -27
@@ -1,6 +1,6 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
1 +import { expect, it, vi } from "vite-plus/test";
2 +
3 +import { render } from "../../test/render";
4
5 type Session = {
6 _tag: "Success" | "Failure";
@@ -37,12 +37,9 @@ vi.mock(import("./ui/toast"), async (original) => {
37 });
38 import { PermissionUpdateNotice } from "./PermissionUpdateNotice";
39
40 -let root: Root;
41 -let container: HTMLDivElement;
40 const storageKey = () => `t3code:permission-update:v1:env-${state.id}`;
41
44 -beforeEach(() => {
45 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
42 +function setup(): Disposable {
43 state.id++;
44 state.session = {
45 _tag: "Success",
@@ -50,15 +47,9 @@ beforeEach(() => {
47 value: { authenticated: true, permissions: ["orchestration:operate"] },
48 };
49 vi.clearAllMocks();
53 - container = document.createElement("div");
54 - root = createRoot(container);
55 -});
56 -afterEach(async () => {
57 - await act(async () => root.unmount());
58 - localStorage.clear();
59 - vi.unstubAllGlobals();
60 -});
61 -const render = () => act(async () => root.render(<PermissionUpdateNotice />));
50 + return { [Symbol.dispose]: () => localStorage.clear() };
51 +}
52 +
53 type Notice = {
54 timeout: number;
55 actionProps: { onClick: () => void };
@@ -67,7 +58,8 @@ type Notice = {
58 const notice = () => state.add.mock.calls[0]![0] as Notice;
59
60 it("keeps the notice visible and persists dismissal, with a route to pairing settings", async () => {
70 - await render();
61 + using _state = setup();
62 + await using _screen = await render(<PermissionUpdateNotice />);
63 expect(notice().timeout).toBe(0);
64 expect(localStorage.getItem(storageKey())).toBeNull();
65 notice().actionProps.onClick();
@@ -76,37 +68,41 @@ it("keeps the notice visible and persists dismissal, with a route to pairing set
68 expect(localStorage.getItem(storageKey())).toBe("true");
69 });
70 it("does not repeat on session refresh or remount", async () => {
79 - await render();
80 - await act(async () => root.unmount());
81 - root = createRoot(container);
71 + using _state = setup();
72 + await using screen = await render(<PermissionUpdateNotice />);
73 + await screen.unmount();
74 state.session = { ...state.session };
83 - await render();
75 + await using _remounted = await render(<PermissionUpdateNotice />);
76 expect(state.add).toHaveBeenCalledTimes(1);
77 });
78 it("skips a notice dismissed on an earlier launch", async () => {
79 + using _state = setup();
80 localStorage.setItem(storageKey(), "true");
88 - await render();
81 + await using _screen = await render(<PermissionUpdateNotice />);
82 expect(state.add).not.toHaveBeenCalled();
83 });
84 it("waits for a successful, settled session check", async () => {
85 + using _state = setup();
86 state.session._tag = "Failure";
93 - await render();
87 + await using screen = await render(<PermissionUpdateNotice />);
88 expect(state.add).not.toHaveBeenCalled();
89 state.session = { ...state.session, _tag: "Success", waiting: true };
96 - await render();
90 + await screen.rerender(<PermissionUpdateNotice />);
91 expect(state.add).not.toHaveBeenCalled();
92 state.session = { ...state.session, waiting: false };
99 - await render();
93 + await screen.rerender(<PermissionUpdateNotice />);
94 expect(state.add).toHaveBeenCalledTimes(1);
95 });
96 it("does not warn for a granular grant", async () => {
97 + using _state = setup();
98 state.session.value.permissions.push("filesystem:read");
104 - await render();
99 + await using _screen = await render(<PermissionUpdateNotice />);
100 expect(state.add).not.toHaveBeenCalled();
101 });
102
103 it("persists the secondary dismissal without relying on the toast close callback", async () => {
109 - await render();
104 + using _state = setup();
105 + await using _screen = await render(<PermissionUpdateNotice />);
106 notice().data.secondaryActionProps.onClick();
107 expect(localStorage.getItem(storageKey())).toBe("true");
108 expect(state.close).toHaveBeenCalledWith("notice");
apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx
+59 -49
@@ -2,9 +2,9 @@ import type { ResolvedKeybindingsConfig, ScopedThreadRef } from "@t3tools/contra
2 import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
3 import * as Cause from "effect/Cause";
4 import { AsyncResult } from "effect/reactivity";
5 -import { act } from "react";
6 -import { createRoot, type Root } from "react-dom/client";
7 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5 +import { describe, expect, it, vi } from "vite-plus/test";
6 +
7 +import { act, render } from "../../test/render";
8
9 const state = vi.hoisted(() => ({
10 keybindings: [] as ResolvedKeybindingsConfig,
@@ -86,33 +86,9 @@ const snapshot = {
86 canGoForward: false,
87 updatedAt: "2026-09-22T12:00:00.000Z",
88 } as const;
89 -let root: Root;
89 let menuAction: ((action: string) => void) | undefined;
90
92 -async function render() {
93 - await act(() => root.render(<ReopenClosedViewShortcut />));
94 -}
95 -
96 -function press(target: Element = document.body) {
97 - const event = new KeyboardEvent("keydown", {
98 - key: "T",
99 - ctrlKey: true,
100 - shiftKey: true,
101 - bubbles: true,
102 - cancelable: true,
103 - });
104 - target.dispatchEvent(event);
105 - return event;
106 -}
107 -
108 -function openCommandPalette() {
109 - const palette = document.createElement("div");
110 - palette.dataset.commandPalette = "";
111 - document.body.append(palette);
112 - return palette;
113 -}
114 -
115 -beforeEach(() => {
91 +function setup() {
92 vi.clearAllMocks();
93 Object.assign(state, {
94 keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
@@ -127,8 +103,11 @@ beforeEach(() => {
103 terminalUiStateByThreadKey: {},
104 suppressedTerminalIdsByThreadKey: {},
105 });
130 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
131 - vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
106 +}
107 +
108 +async function renderShortcut() {
109 + await using stack = new AsyncDisposableStack();
110 + stack.use(vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"));
111 window.desktopBridge = {
112 preview: { setForwardedShortcuts: state.setShortcuts },
113 onMenuAction: (listener: (action: string) => void) => {
@@ -138,23 +117,47 @@ beforeEach(() => {
117 };
118 },
119 } as unknown as NonNullable<typeof window.desktopBridge>;
141 - root = createRoot(document.createElement("div"));
142 -});
120 + stack.defer(() => {
121 + delete window.desktopBridge;
122 + });
123 + stack.use(await render(<ReopenClosedViewShortcut />));
124 + const environment = stack.move();
125 + return {
126 + /** Attaches an element to the document until the test ends. */
127 + append(element: HTMLElement) {
128 + document.body.append(element);
129 + environment.defer(() => element.remove());
130 + return element;
131 + },
132 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
133 + };
134 +}
135
144 -afterEach(async () => {
145 - await act(() => root.unmount());
146 - delete window.desktopBridge;
147 - document.body.replaceChildren();
148 - vi.restoreAllMocks();
149 - vi.unstubAllGlobals();
150 -});
136 +function press(target: Element = document.body) {
137 + const event = new KeyboardEvent("keydown", {
138 + key: "T",
139 + ctrlKey: true,
140 + shiftKey: true,
141 + bubbles: true,
142 + cancelable: true,
143 + });
144 + target.dispatchEvent(event);
145 + return event;
146 +}
147 +
148 +function commandPalette() {
149 + const palette = document.createElement("div");
150 + palette.dataset.commandPalette = "";
151 + return palette;
152 +}
153
154 describe("root reopen shortcut", () => {
155 it("restores a tab from settings to its owning remote thread", async () => {
156 + setup();
157 useClosedViewStore
158 .getState()
159 .remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } });
157 - await render();
160 + await using _view = await renderShortcut();
161 await act(() => {
162 expect(press().defaultPrevented).toBe(true);
163 });
@@ -166,32 +169,35 @@ describe("root reopen shortcut", () => {
169 });
170
171 it("leaves native shortcuts alone without history or while the palette is open", async () => {
169 - await render();
172 + setup();
173 + await using view = await renderShortcut();
174 expect(press().defaultPrevented).toBe(false);
175 await act(() => {
176 useClosedViewStore
177 .getState()
178 .remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } });
179 });
176 - openCommandPalette();
180 + view.append(commandPalette());
181 expect(press().defaultPrevented).toBe(false);
182 expect(state.navigate).not.toHaveBeenCalled();
183 expect(useClosedViewStore.getState().entries).toHaveLength(1);
184 });
185
186 it("lets the keybinding recorder capture the chord", async () => {
187 + setup();
188 useClosedViewStore
189 .getState()
190 .remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } });
186 - await render();
191 + await using view = await renderShortcut();
192 const recorder = document.createElement("input");
193 recorder.dataset.keybindingCapture = "";
189 - document.body.append(recorder);
194 + view.append(recorder);
195 expect(press(recorder).defaultPrevented).toBe(false);
196 expect(useClosedViewStore.getState().entries).toHaveLength(1);
197 });
198
199 it("serializes deliberate presses while a browser restore waits for RPC", async () => {
200 + setup();
201 useClosedViewStore
202 .getState()
203 .remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "files", id: "files" } });
@@ -202,7 +208,7 @@ describe("root reopen shortcut", () => {
208 finish = resolve;
209 }),
210 );
205 - await render();
211 + await using _view = await renderShortcut();
212 await act(() => {
213 press();
214 press();
@@ -217,6 +223,7 @@ describe("root reopen shortcut", () => {
223 });
224
225 it("does not create a second browser when navigation fails after restoring it", async () => {
226 + setup();
227 const store = useClosedViewStore.getState();
228 const older = store.remember({
229 kind: "panel-tab",
@@ -226,7 +233,7 @@ describe("root reopen shortcut", () => {
233 store.remember({ kind: "browser", threadRef: ref, snapshot });
234 state.openPreview.mockResolvedValue(AsyncResult.success({ tabId: "new-tab" }));
235 state.navigate.mockRejectedValueOnce(new Error("navigation failed"));
229 - await render();
236 + await using _view = await renderShortcut();
237 await act(() => {
238 press();
239 });
@@ -250,6 +257,7 @@ describe("root reopen shortcut", () => {
257 it.each(["files", "file", "browser"] as const)(
258 "keeps a failed %s restore retryable without blocking older history",
259 async (kind) => {
260 + setup();
261 const store = useClosedViewStore.getState();
262 const older = store.remember({
263 kind: "panel-tab",
@@ -276,7 +284,7 @@ describe("root reopen shortcut", () => {
284 );
285 state.workspaceAvailable = false;
286 state.openPreview.mockResolvedValue(AsyncResult.failure(Cause.fail(new Error("offline"))));
279 - await render();
287 + await using _view = await renderShortcut();
288 await act(() => {
289 press();
290 });
@@ -307,6 +315,7 @@ describe("root reopen shortcut", () => {
315 );
316
317 it("forwards the chord to a focused desktop browser only while history exists", async () => {
318 + setup();
319 const forwardedCommands = () =>
320 (state.setShortcuts.mock.lastCall as unknown as [Array<{ command: string }>])[0].map(
321 ({ command }) => command,
@@ -314,7 +323,7 @@ describe("root reopen shortcut", () => {
323 useClosedViewStore
324 .getState()
325 .remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } });
317 - await render();
326 + await using _view = await renderShortcut();
327 expect(forwardedCommands()).toContain("view.reopenClosed");
328 await act(() => {
329 menuAction?.("view.reopenClosed");
@@ -324,7 +333,8 @@ describe("root reopen shortcut", () => {
333 });
334
335 it("always forwards the layout toggles out of a focused desktop browser", async () => {
327 - await render();
336 + setup();
337 + await using _view = await renderShortcut();
338 expect(state.setShortcuts).toHaveBeenLastCalledWith([
339 expect.objectContaining({ command: "sidebar.toggle" }),
340 expect.objectContaining({ command: "rightPanel.toggle" }),
apps/web/src/components/RightPanelTabs.browser.test.tsx
+84 -87
@@ -1,8 +1,8 @@
1 import type { DesktopPreviewFavicon, PreviewSessionSnapshot } from "@t3tools/contracts";
2 import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
3 -import { act } from "react";
4 -import { createRoot, type Root } from "react-dom/client";
5 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 +import { describe, expect, it, vi } from "vite-plus/test";
4 +
5 +import { act, render } from "../../test/render";
6
7 const setAudioMuted = vi.hoisted(() => vi.fn(async () => undefined));
8
@@ -80,107 +80,101 @@ function overlay(
80 };
81 }
82
83 -let root: Root;
84 -let container: HTMLDivElement;
83 const noop = () => undefined;
84
87 -beforeEach(() => {
88 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
89 - setAudioMuted.mockClear();
90 - container = document.createElement("div");
91 - document.body.append(container);
92 - root = createRoot(container);
93 -});
94 -
95 -afterEach(async () => {
96 - await act(() => root.unmount());
97 - container.remove();
98 - vi.unstubAllGlobals();
99 -});
100 -
101 -async function renderTabs(
85 +function tabs(
86 first: DesktopPreviewFavicon | null,
87 second?: DesktopPreviewFavicon,
88 audio?: { audible?: boolean; audioMuted?: boolean },
89 previewRuntimeTabId: ((tabId: string) => string) | null = (tabId) => `runtime:${tabId}`,
90 ) {
107 - await act(() =>
108 - root.render(
109 - <RightPanelTabs
110 - mode="inline"
111 - open
112 - keybindings={DEFAULT_RESOLVED_KEYBINDINGS}
113 - getShortcutContext={() => ({
114 - terminalFocus: false,
115 - terminalOpen: false,
116 - previewFocus: false,
117 - previewOpen: false,
118 - isWeb: true,
119 - isDesktop: false,
120 - })}
121 - surfaces={second ? [previewSurface, secondSurface] : [previewSurface]}
122 - environmentId={null}
123 - activeSurfaceId={previewSurface.id}
124 - pendingSurfaceIds={new Set()}
125 - previewSessions={sessions}
126 - desktopByTabId={{
127 - "tab-1": overlay(first, audio),
128 - ...(second ? { "tab-2": overlay(second) } : {}),
129 - }}
130 - {...(previewRuntimeTabId ? { previewRuntimeTabId } : {})}
131 - terminalLabelsById={new Map()}
132 - onActivate={noop}
133 - onCloseSurface={noop}
134 - onCloseOtherSurfaces={noop}
135 - onCloseSurfacesToRight={noop}
136 - onCloseAllSurfaces={noop}
137 - onCopyFilePath={noop}
138 - onAddBrowser={noop}
139 - onAddBrowserInProfile={noop}
140 - onAddTerminal={noop}
141 - onAddPullRequest={noop}
142 - onAddPullRequests={noop}
143 - onAddDiff={noop}
144 - onAddFiles={noop}
145 - onAddDevice={noop}
146 - browserAvailable
147 - terminalAvailable={false}
148 - diffAvailable={false}
149 - filesAvailable={false}
150 - pullRequestAvailable={false}
151 - pullRequestsAvailable={false}
152 - deviceAvailable={false}
153 - >
154 - <div>content</div>
155 - </RightPanelTabs>,
156 - ),
91 + return (
92 + <RightPanelTabs
93 + mode="inline"
94 + open
95 + keybindings={DEFAULT_RESOLVED_KEYBINDINGS}
96 + getShortcutContext={() => ({
97 + terminalFocus: false,
98 + terminalOpen: false,
99 + previewFocus: false,
100 + previewOpen: false,
101 + isWeb: true,
102 + isDesktop: false,
103 + })}
104 + surfaces={second ? [previewSurface, secondSurface] : [previewSurface]}
105 + environmentId={null}
106 + activeSurfaceId={previewSurface.id}
107 + pendingSurfaceIds={new Set()}
108 + previewSessions={sessions}
109 + desktopByTabId={{
110 + "tab-1": overlay(first, audio),
111 + ...(second ? { "tab-2": overlay(second) } : {}),
112 + }}
113 + {...(previewRuntimeTabId ? { previewRuntimeTabId } : {})}
114 + terminalLabelsById={new Map()}
115 + onActivate={noop}
116 + onCloseSurface={noop}
117 + onCloseOtherSurfaces={noop}
118 + onCloseSurfacesToRight={noop}
119 + onCloseAllSurfaces={noop}
120 + onCopyFilePath={noop}
121 + onAddBrowser={noop}
122 + onAddBrowserInProfile={noop}
123 + onAddTerminal={noop}
124 + onAddPullRequest={noop}
125 + onAddPullRequests={noop}
126 + onAddDiff={noop}
127 + onAddFiles={noop}
128 + onAddDevice={noop}
129 + browserAvailable
130 + terminalAvailable={false}
131 + diffAvailable={false}
132 + filesAvailable={false}
133 + pullRequestAvailable={false}
134 + pullRequestsAvailable={false}
135 + deviceAvailable={false}
136 + >
137 + <div>content</div>
138 + </RightPanelTabs>
139 );
140 }
141
160 -const imageSources = () => [...container.querySelectorAll("img")].map((image) => image.src);
161 -const button = (name: string) =>
142 +function setup() {
143 + setAudioMuted.mockClear();
144 +}
145 +
146 +function renderTabs(...args: Parameters<typeof tabs>) {
147 + return render(tabs(...args));
148 +}
149 +
150 +const imageSources = (container: HTMLElement) =>
151 + [...container.querySelectorAll("img")].map((image) => image.src);
152 +const button = (container: HTMLElement, name: string) =>
153 [...container.querySelectorAll("button")].find((element) => element.ariaLabel === name);
154
155 describe("preview tab favicon", () => {
156 it("prefers a live capture and never asks a public provider about a private hostname", async () => {
166 - await renderTabs(favicon(PIXEL_A, "http://24x.xf.local/"));
167 - expect(imageSources()).toEqual([PIXEL_A]);
157 + setup();
158 + await using screen = await renderTabs(favicon(PIXEL_A, "http://24x.xf.local/"));
159 + expect(imageSources(screen.container)).toEqual([PIXEL_A]);
160
169 - await renderTabs(null);
170 - expect(imageSources()).toEqual([]);
161 + await screen.rerender(tabs(null));
162 + expect(imageSources(screen.container)).toEqual([]);
163 });
164
165 it("keeps route-specific captures isolated between live tabs on one origin", async () => {
174 - await renderTabs(
166 + setup();
167 + await using screen = await renderTabs(
168 favicon(PIXEL_A, "http://24x.xf.local/"),
169 favicon(PIXEL_B, "http://24x.xf.local/admin"),
170 );
178 - expect(imageSources()).toEqual([PIXEL_A, PIXEL_B]);
171 + expect(imageSources(screen.container)).toEqual([PIXEL_A, PIXEL_B]);
172 });
173
174 it("hides a capture while the server session still describes another origin", async () => {
182 - await renderTabs(favicon(PIXEL_A, "https://example.com/"));
183 - expect(imageSources()).not.toContain(PIXEL_A);
175 + setup();
176 + await using screen = await renderTabs(favicon(PIXEL_A, "https://example.com/"));
177 + expect(imageSources(screen.container)).not.toContain(PIXEL_A);
178 });
179 });
180
@@ -189,22 +183,25 @@ describe("preview tab audio toggle", () => {
183 { audible: false, audioMuted: false },
184 { audible: false, audioMuted: true },
185 ])("is absent for a silent tab (muted=$audioMuted)", async (audio) => {
192 - await renderTabs(null, undefined, audio);
193 - expect(button("Mute Local site")).toBeUndefined();
194 - expect(button("Unmute Local site")).toBeUndefined();
186 + setup();
187 + await using screen = await renderTabs(null, undefined, audio);
188 + expect(button(screen.container, "Mute Local site")).toBeUndefined();
189 + expect(button(screen.container, "Unmute Local site")).toBeUndefined();
190 });
191
192 it.each([
193 { audioMuted: false, label: "Mute Local site", nextMuted: true },
194 { audioMuted: true, label: "Unmute Local site", nextMuted: false },
195 ])("$label addresses the desktop by runtime tab id", async ({ audioMuted, label, nextMuted }) => {
201 - await renderTabs(null, undefined, { audible: true, audioMuted });
202 - await act(() => button(label)!.click());
196 + setup();
197 + await using screen = await renderTabs(null, undefined, { audible: true, audioMuted });
198 + await act(() => button(screen.container, label)!.click());
199 expect(setAudioMuted).toHaveBeenCalledExactlyOnceWith("runtime:tab-1", nextMuted);
200 });
201
202 it("hides the toggle when no runtime tab id can be resolved", async () => {
207 - await renderTabs(null, undefined, { audible: true }, null);
208 - expect(button("Mute Local site")).toBeUndefined();
203 + setup();
204 + await using screen = await renderTabs(null, undefined, { audible: true }, null);
205 + expect(button(screen.container, "Mute Local site")).toBeUndefined();
206 });
207 });
apps/web/src/components/RightPanelTabs.keyboard.browser.test.tsx
+129 -124
@@ -1,109 +1,108 @@
1 -import { act, type ComponentProps } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import type { ComponentProps } from "react";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3 import {
4 compileResolvedKeybindingsConfig,
5 DEFAULT_RESOLVED_KEYBINDINGS,
6 } from "@t3tools/shared/keybindings";
7
8 +import { act, fakeTimers, render, stubGlobal } from "../../test/render";
9 import { RightPanelTabs } from "./RightPanelTabs";
10
11 vi.mock("~/hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "light" }) }));
12 vi.mock("~/browser/browserDefaults", () => ({ useBrowserDefaults: () => ({ profiles: [] }) }));
13
14 -let root: Root;
15 -let container: HTMLDivElement;
16 -const addFiles = vi.fn();
14 const noop = () => undefined;
15
19 -beforeEach(() => {
20 - vi.useFakeTimers();
21 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
22 - vi.stubGlobal(
23 - "ResizeObserver",
24 - class {
25 - observe() {}
26 - disconnect() {}
27 - unobserve() {}
28 - },
29 - );
30 - Object.defineProperty(Element.prototype, "getAnimations", {
31 - configurable: true,
32 - value: () => [],
33 - });
34 - vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
35 - addFiles.mockClear();
36 - container = document.createElement("div");
37 - document.body.append(container);
38 - root = createRoot(container);
39 -});
40 -
41 -afterEach(async () => {
42 - await act(() => root.unmount());
43 - container.remove();
44 - vi.restoreAllMocks();
45 - vi.unstubAllGlobals();
46 - vi.useRealTimers();
47 -});
16 +async function settle() {
17 + await act(() => vi.advanceTimersByTimeAsync(0));
18 + await act(() => vi.advanceTimersToNextFrame());
19 +}
20
49 -async function renderPanel(overrides: Partial<ComponentProps<typeof RightPanelTabs>> = {}) {
50 - await act(() =>
51 - root.render(
52 - <RightPanelTabs
53 - mode="inline"
54 - open
55 - keybindings={DEFAULT_RESOLVED_KEYBINDINGS}
56 - getShortcutContext={() => ({
57 - terminalFocus: false,
58 - terminalOpen: false,
59 - previewFocus: false,
60 - previewOpen: false,
61 - isWeb: true,
62 - isDesktop: false,
63 - })}
64 - surfaces={[]}
65 - environmentId={null}
66 - activeSurfaceId={null}
67 - pendingSurfaceIds={new Set()}
68 - previewSessions={{}}
69 - desktopByTabId={{}}
70 - terminalLabelsById={new Map()}
71 - onActivate={noop}
72 - onCloseSurface={noop}
73 - onCloseOtherSurfaces={noop}
74 - onCloseSurfacesToRight={noop}
75 - onCloseAllSurfaces={noop}
76 - onCopyFilePath={noop}
77 - onAddBrowser={noop}
78 - onAddBrowserInProfile={noop}
79 - onAddTerminal={noop}
80 - onAddDiff={noop}
81 - onAddFiles={addFiles}
82 - onAddPullRequest={noop}
83 - onAddPullRequests={noop}
84 - onAddDevice={noop}
85 - browserAvailable={false}
86 - terminalAvailable={false}
87 - diffAvailable={false}
88 - filesAvailable
89 - pullRequestAvailable={false}
90 - pullRequestsAvailable={false}
91 - deviceAvailable={false}
92 - {...overrides}
93 - >
94 - content
95 - </RightPanelTabs>,
21 +async function renderPanel(
22 + overrides: Partial<ComponentProps<typeof RightPanelTabs>> = {},
23 + platform = "MacIntel",
24 +) {
25 + await using stack = new AsyncDisposableStack();
26 + stack.use(fakeTimers());
27 + stack.use(
28 + stubGlobal(
29 + "ResizeObserver",
30 + class {
31 + observe() {}
32 + disconnect() {}
33 + unobserve() {}
34 + },
35 ),
36 );
98 - await act(() => vi.advanceTimersByTimeAsync(0));
99 - await act(() => vi.advanceTimersToNextFrame());
37 + // Menus wait for exit animations to finish, which never happens under fake timers.
38 + stack.use(vi.spyOn(Element.prototype, "getAnimations").mockReturnValue([]));
39 + stack.use(vi.spyOn(navigator, "platform", "get").mockReturnValue(platform));
40 + const addFiles = vi.fn();
41 + const panel = (props: Partial<ComponentProps<typeof RightPanelTabs>>) => (
42 + <RightPanelTabs
43 + mode="inline"
44 + open
45 + keybindings={DEFAULT_RESOLVED_KEYBINDINGS}
46 + getShortcutContext={() => ({
47 + terminalFocus: false,
48 + terminalOpen: false,
49 + previewFocus: false,
50 + previewOpen: false,
51 + isWeb: true,
52 + isDesktop: false,
53 + })}
54 + surfaces={[]}
55 + environmentId={null}
56 + activeSurfaceId={null}
57 + pendingSurfaceIds={new Set()}
58 + previewSessions={{}}
59 + desktopByTabId={{}}
60 + terminalLabelsById={new Map()}
61 + onActivate={noop}
62 + onCloseSurface={noop}
63 + onCloseOtherSurfaces={noop}
64 + onCloseSurfacesToRight={noop}
65 + onCloseAllSurfaces={noop}
66 + onCopyFilePath={noop}
67 + onAddBrowser={noop}
68 + onAddBrowserInProfile={noop}
69 + onAddTerminal={noop}
70 + onAddDiff={noop}
71 + onAddFiles={addFiles}
72 + onAddPullRequest={noop}
73 + onAddPullRequests={noop}
74 + onAddDevice={noop}
75 + browserAvailable={false}
76 + terminalAvailable={false}
77 + diffAvailable={false}
78 + filesAvailable
79 + pullRequestAvailable={false}
80 + pullRequestsAvailable={false}
81 + deviceAvailable={false}
82 + {...props}
83 + >
84 + content
85 + </RightPanelTabs>
86 + );
87 + // Nothing here navigates, and the test router would load on the fake clock too.
88 + const screen = stack.use(await render(panel(overrides), { router: false }));
89 + await settle();
90 + const environment = stack.move();
91 + return {
92 + container: screen.container,
93 + addFiles,
94 + rerender: async (props: Partial<ComponentProps<typeof RightPanelTabs>>) => {
95 + await screen.rerender(panel(props));
96 + await settle();
97 + },
98 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
99 + };
100 }
101
102 async function press(key: string, options: KeyboardEventInit = {}) {
103 const event = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...options });
104 await act(() => (document.activeElement ?? document.body).dispatchEvent(event));
105 - await act(() => vi.advanceTimersByTimeAsync(0));
106 - await act(() => vi.advanceTimersToNextFrame());
105 + await settle();
106 return event;
107 }
108
@@ -111,8 +110,7 @@ describe("right panel new-tab shortcut", () => {
110 it.each(["MacIntel", "Win32", "Linux x86_64"])(
111 "opens the menu on %s and chooses a tab",
112 async (platform) => {
114 - vi.spyOn(navigator, "platform", "get").mockReturnValue(platform);
115 - await renderPanel();
113 + await using screen = await renderPanel({}, platform);
114 const event = await press(
115 "t",
116 platform === "MacIntel" ? { metaKey: true } : { ctrlKey: true },
@@ -132,35 +130,35 @@ describe("right panel new-tab shortcut", () => {
130 ).defaultPrevented,
131 ).toBe(true);
132 await press("f");
135 - expect(addFiles).toHaveBeenCalledOnce();
133 + expect(screen.addFiles).toHaveBeenCalledOnce();
134 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
135 },
136 );
137
138 it("opens Files while a closed popup remains mounted", async () => {
141 - await renderPanel();
139 + await using screen = await renderPanel();
140 const popup = document.createElement("div");
141 popup.dataset.slot = "menu-popup";
142 popup.dataset.closed = "";
145 - container.append(popup);
143 + screen.container.append(popup);
144
145 expect((await press("f")).defaultPrevented).toBe(true);
148 - expect(addFiles).toHaveBeenCalledOnce();
146 + expect(screen.addFiles).toHaveBeenCalledOnce();
147 });
148
149 it("opens the add-surface menu while a closed popup remains mounted", async () => {
152 - await renderPanel();
150 + await using screen = await renderPanel();
151 const popup = document.createElement("div");
152 popup.dataset.slot = "menu-popup";
153 popup.dataset.closed = "";
156 - container.append(popup);
154 + screen.container.append(popup);
155
156 expect((await press("t", { metaKey: true })).defaultPrevented).toBe(true);
157 expect(document.querySelector('[role="menu"]:not([data-closed])')).not.toBeNull();
158 });
159
160 it("leaves the shortcut alone while the mounted panel is closed", async () => {
163 - await renderPanel({ open: false });
161 + await using _screen = await renderPanel({ open: false });
162 expect((await press("t", { metaKey: true })).defaultPrevented).toBe(false);
163 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
164 });
@@ -168,21 +166,23 @@ describe("right panel new-tab shortcut", () => {
166 it.each(["Win32", "Linux x86_64"])(
167 "leaves Ctrl+T for the focused terminal on %s",
168 async (platform) => {
171 - vi.spyOn(navigator, "platform", "get").mockReturnValue(platform);
172 - await renderPanel({
173 - getShortcutContext: () => ({
174 - terminalFocus: true,
175 - terminalOpen: true,
176 - previewFocus: false,
177 - previewOpen: false,
178 - isWeb: true,
179 - isDesktop: false,
180 - }),
181 - });
169 + await using screen = await renderPanel(
170 + {
171 + getShortcutContext: () => ({
172 + terminalFocus: true,
173 + terminalOpen: true,
174 + previewFocus: false,
175 + previewOpen: false,
176 + isWeb: true,
177 + isDesktop: false,
178 + }),
179 + },
180 + platform,
181 + );
182 const terminal = document.createElement("textarea");
183 const onKeyDown = vi.fn();
184 terminal.addEventListener("keydown", onKeyDown);
185 - container.append(terminal);
185 + screen.container.append(terminal);
186 await act(() => terminal.focus());
187 const event = await press("t", { ctrlKey: true });
188 expect(event.defaultPrevented).toBe(false);
@@ -193,10 +193,11 @@ describe("right panel new-tab shortcut", () => {
193
194 it("uses a custom binding from a text field and closes on Escape", async () => {
195 const input = document.createElement("input");
196 - await renderPanel({
196 + await using screen = await renderPanel({
197 keybindings: compileResolvedKeybindingsConfig([{ key: "mod+y", command: "rightPanel.new" }]),
198 });
199 document.body.append(input);
200 + using _input = { [Symbol.dispose]: () => input.remove() };
201 input.focus();
202 expect((await press("t", { metaKey: true })).defaultPrevented).toBe(false);
203 await press("y", { metaKey: true });
@@ -205,25 +206,24 @@ describe("right panel new-tab shortcut", () => {
206 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
207 // The menu hands focus back to its trigger once its close finishes, a few frames later.
208 // Timers are fake here, so advance them instead of polling in real time.
208 - const trigger = container.querySelector('[aria-label="Add panel surface"]');
209 + const trigger = screen.container.querySelector('[aria-label="Add panel surface"]');
210 for (let frame = 0; frame < 10 && document.activeElement !== trigger; frame++) {
211 await act(() => vi.advanceTimersToNextFrame());
212 }
213 expect(document.activeElement).toBe(trigger);
213 - input.remove();
214 });
215
216 it("does not open over another popup or during text composition", async () => {
217 - await renderPanel();
217 + await using screen = await renderPanel();
218 expect((await press("t", { metaKey: true, isComposing: true })).defaultPrevented).toBe(false);
219 const dialog = document.createElement("div");
220 dialog.dataset.slot = "dialog-popup";
221 dialog.dataset.open = "";
222 - container.append(dialog);
222 + screen.container.append(dialog);
223 for (const state of ["data-open", "data-ending-style"]) {
224 dialog.setAttribute(state, "");
225 expect((await press("f")).defaultPrevented, state).toBe(false);
226 - expect(addFiles, state).not.toHaveBeenCalled();
226 + expect(screen.addFiles, state).not.toHaveBeenCalled();
227 expect((await press("t", { metaKey: true })).defaultPrevented, state).toBe(false);
228 expect(document.querySelector('[role="menu"]'), state).toBeNull();
229 dialog.removeAttribute(state);
@@ -231,16 +231,16 @@ describe("right panel new-tab shortcut", () => {
231 });
232
233 it("blocks panel shortcuts until a mounted popup finishes closing", async () => {
234 - await renderPanel();
234 + await using screen = await renderPanel();
235 const popover = document.createElement("div");
236 popover.dataset.slot = "popover-popup";
237 popover.dataset.open = "";
238 - container.append(popover);
238 + screen.container.append(popover);
239
240 expect((await press("t", { metaKey: true })).defaultPrevented).toBe(false);
241 expect((await press("f")).defaultPrevented).toBe(false);
242 expect(document.querySelector('[role="menu"]')).toBeNull();
243 - expect(addFiles).not.toHaveBeenCalled();
243 + expect(screen.addFiles).not.toHaveBeenCalled();
244
245 delete popover.dataset.open;
246 popover.dataset.closed = "";
@@ -248,12 +248,12 @@ describe("right panel new-tab shortcut", () => {
248 expect((await press("t", { metaKey: true })).defaultPrevented).toBe(false);
249 expect((await press("f")).defaultPrevented).toBe(false);
250 expect(document.querySelector('[role="menu"]')).toBeNull();
251 - expect(addFiles).not.toHaveBeenCalled();
251 + expect(screen.addFiles).not.toHaveBeenCalled();
252
253 delete popover.dataset.endingStyle;
254 popover.hidden = true;
255 expect((await press("f")).defaultPrevented).toBe(true);
256 - expect(addFiles).toHaveBeenCalledOnce();
256 + expect(screen.addFiles).toHaveBeenCalledOnce();
257 expect((await press("t", { metaKey: true })).defaultPrevented).toBe(true);
258 expect(document.querySelector('[role="menu"]')?.textContent).toContain("Files");
259 expect(document.activeElement?.closest('[role="menu"]')).not.toBeNull();
@@ -264,18 +264,18 @@ describe("right panel new-tab shortcut", () => {
264 mode: "sheet" as const,
265 surfaces: [{ id: "files" as const, kind: "files" as const }],
266 };
267 - await renderPanel(panel);
267 + await using screen = await renderPanel(panel);
268 await press("t", { metaKey: true });
269 await press("ArrowDown");
270 await press("ArrowDown");
271 await press("ArrowDown");
272 expect(document.activeElement?.textContent).toContain("Files");
273 await press("Enter");
274 - expect(addFiles).toHaveBeenCalledOnce();
274 + expect(screen.addFiles).toHaveBeenCalledOnce();
275 await press("t", { metaKey: true });
276 - await renderPanel({ ...panel, open: false });
276 + await screen.rerender({ ...panel, open: false });
277 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
278 - await renderPanel(panel);
278 + await screen.rerender(panel);
279 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
280 });
281 });
@@ -285,8 +285,13 @@ describe("right panel tab middle click", () => {
285 const onActivate = vi.fn();
286 const onCloseSurface = vi.fn();
287 const files = { id: "files" as const, kind: "files" as const };
288 - await renderPanel({ surfaces: [files], activeSurfaceId: files.id, onActivate, onCloseSurface });
289 - const tabLabel = container.querySelector("[data-active-tab] span.truncate")!;
288 + await using screen = await renderPanel({
289 + surfaces: [files],
290 + activeSurfaceId: files.id,
291 + onActivate,
292 + onCloseSurface,
293 + });
294 + const tabLabel = screen.container.querySelector("[data-active-tab] span.truncate")!;
295 const mouse = async (type: string, button: number) => {
296 const event = new MouseEvent(type, { button, bubbles: true, cancelable: true });
297 await act(() => tabLabel.dispatchEvent(event));
apps/web/src/components/ServerUpdateAction.browser.test.tsx
+96 -86
@@ -3,9 +3,10 @@ import { AuthSessionState, type EnvironmentId, type ServerInstallation } from "@
3 import * as Cause from "effect/Cause";
4 import * as Schema from "effect/Schema";
5 import { AsyncResult, Atom } from "effect/reactivity";
6 -import { act, type ReactNode } from "react";
7 -import { createRoot, type Root } from "react-dom/client";
8 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
6 +import type { ReactNode } from "react";
7 +import { describe, expect, it, vi } from "vite-plus/test";
8 +
9 +import { act, render, type Screen } from "../../test/render";
10
11 type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
12 const testState = vi.hoisted(() => ({
@@ -90,37 +91,42 @@ const currentSession = {
91 const success = (method: "boot-service" | "desktop-app" = "boot-service", version = "0.0.31") =>
92 AsyncResult.success({ targetVersion: version, method });
93
93 -let root: Root;
94 -let container: HTMLDivElement;
94 let sessionAtom: Atom.Writable<SessionResult>;
95
96 function setSession(session: SessionResult) {
97 appAtomRegistry.set(sessionAtom, session);
98 }
99
101 -async function render(element: ReactNode) {
102 - await act(() =>
103 - root.render(
104 - <RegistryContext.Provider value={appAtomRegistry}>{element}</RegistryContext.Provider>,
105 - ),
100 +function setup(): Disposable {
101 + testState.updateServer.mockReset();
102 + testState.toast.mockReset();
103 + testState.clipboard.mockReset();
104 + testState.continueThreadsAfterServerUpdate = false;
105 + sessionAtom = Atom.make<SessionResult>(AsyncResult.success(currentSession));
106 + testState.sessionAtom = sessionAtom;
107 + resetConfirmDialogForTests();
108 + return { [Symbol.dispose]: resetConfirmDialogForTests };
109 +}
110 +
111 +function renderUpdate(element: ReactNode) {
112 + return render(
113 + <RegistryContext.Provider value={appAtomRegistry}>{element}</RegistryContext.Provider>,
114 );
115 }
116
109 -function button(name?: string) {
110 - const buttons = [...container.querySelectorAll("button")];
117 +function button(screen: Screen, name?: string) {
118 + const buttons = [...screen.container.querySelectorAll("button")];
119 return name === undefined
120 ? buttons[0]
121 : buttons.find((element) => element.textContent?.trim() === name);
122 }
123
116 -async function click(name?: string) {
117 - await act(async () => button(name)!.click());
124 +async function click(screen: Screen, name?: string) {
125 + await act(async () => button(screen, name)!.click());
126 }
127
120 -async function renderAction(
121 - props: Partial<Parameters<typeof ServerUpdateAction>[0]> = {},
122 -): Promise<void> {
123 - await render(
128 +function renderAction(props: Partial<Parameters<typeof ServerUpdateAction>[0]> = {}) {
129 + return renderUpdate(
130 <ServerUpdateAction
131 environmentId={"env-test" as EnvironmentId}
132 serverLabel="Test server"
@@ -131,27 +137,6 @@ async function renderAction(
137 );
138 }
139
134 -beforeEach(() => {
135 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
136 - testState.updateServer.mockReset();
137 - testState.toast.mockReset();
138 - testState.clipboard.mockReset();
139 - testState.continueThreadsAfterServerUpdate = false;
140 - sessionAtom = Atom.make<SessionResult>(AsyncResult.success(currentSession));
141 - testState.sessionAtom = sessionAtom;
142 - resetConfirmDialogForTests();
143 - container = document.createElement("div");
144 - document.body.append(container);
145 - root = createRoot(container);
146 -});
147 -
148 -afterEach(async () => {
149 - await act(async () => root.unmount());
150 - container.remove();
151 - resetConfirmDialogForTests();
152 - vi.unstubAllGlobals();
153 -});
154 -
140 describe("ServerUpdateAction", () => {
141 it.each([
142 { serverUpdateScope: undefined, scopes: ["orchestration:operate"], allowed: true },
@@ -169,6 +154,7 @@ describe("ServerUpdateAction", () => {
154 ] as const)(
155 "uses the advertised update scope $serverUpdateScope with grant $scopes",
156 async ({ serverUpdateScope, scopes, allowed }) => {
157 + using _state = setup();
158 setSession(
159 AsyncResult.success(
160 decodeSessionState({
@@ -183,29 +169,31 @@ describe("ServerUpdateAction", () => {
169 );
170 testState.updateServer.mockResolvedValue(success());
171
186 - await renderAction();
187 - expect(button("Update")!.disabled).toBe(!allowed);
188 - await click("Update");
172 + await using screen = await renderAction();
173 + expect(button(screen, "Update")!.disabled).toBe(!allowed);
174 + await click(screen, "Update");
175
176 expect(testState.updateServer).toHaveBeenCalledTimes(allowed ? 1 : 0);
177 },
178 );
179
180 it("keeps a known grant usable while the session refreshes", async () => {
181 + using _state = setup();
182 setSession(AsyncResult.waiting(AsyncResult.success(currentSession)));
183 testState.updateServer.mockResolvedValue(success());
184
198 - await renderAction();
199 - await click("Update");
185 + await using screen = await renderAction();
186 + await click(screen, "Update");
187
188 expect(testState.updateServer).toHaveBeenCalledOnce();
189 });
190
191 it("disables the action once maintenance access is removed", async () => {
205 - await renderAction();
192 + using _state = setup();
193 + await using screen = await renderAction();
194 await act(() => setSession(AsyncResult.success({ ...currentSession, scopes: [] })));
207 - expect(button("Update")!.disabled).toBe(true);
208 - await click("Update");
195 + expect(button(screen, "Update")!.disabled).toBe(true);
196 + await click(screen, "Update");
197 expect(testState.updateServer).not.toHaveBeenCalled();
198 });
199
@@ -236,8 +224,13 @@ describe("ServerUpdateAction", () => {
224 >)(
225 "copies an honest manual command for %j without invoking remote update",
226 async (installation, label, command, title, guidance) => {
239 - await renderAction({ selfUpdate: null, installation, targetVersion: "0.0.45" });
240 - await click(label);
227 + using _state = setup();
228 + await using screen = await renderAction({
229 + selfUpdate: null,
230 + installation,
231 + targetVersion: "0.0.45",
232 + });
233 + await click(screen, label);
234 expect(testState.clipboard).toHaveBeenCalledWith(command);
235 expect(testState.toast).toHaveBeenCalledWith(
236 expect.objectContaining({
@@ -250,10 +243,11 @@ describe("ServerUpdateAction", () => {
243 );
244
245 it("reports success only after the shared update flow reconnects", async () => {
246 + using _state = setup();
247 testState.updateServer.mockResolvedValue(success());
248
255 - await renderAction();
256 - await click("Update");
249 + await using screen = await renderAction();
250 + await click(screen, "Update");
251
252 expect(testState.updateServer).toHaveBeenCalledWith({
253 environmentId: "env-test",
@@ -267,6 +261,7 @@ describe("ServerUpdateAction", () => {
261 });
262
263 it("reports one result when the update action is double-clicked", async () => {
264 + using _state = setup();
265 let finishUpdate: (() => void) | undefined;
266 testState.updateServer.mockImplementation(
267 () =>
@@ -275,10 +270,10 @@ describe("ServerUpdateAction", () => {
270 }),
271 );
272
278 - await renderAction();
273 + await using screen = await renderAction();
274 await act(async () => {
280 - button("Update")!.click();
281 - button("Update")!.click();
275 + button(screen, "Update")!.click();
276 + button(screen, "Update")!.click();
277 });
278
279 expect(testState.updateServer).toHaveBeenCalledTimes(1);
@@ -287,29 +282,35 @@ describe("ServerUpdateAction", () => {
282 });
283
284 it("quietly releases the action when the operation is interrupted", async () => {
285 + using _state = setup();
286 testState.updateServer.mockResolvedValue(AsyncResult.failure(Cause.interrupt()));
287
292 - await renderAction();
293 - await click("Update");
288 + await using screen = await renderAction();
289 + await click(screen, "Update");
290
291 expect(testState.toast).not.toHaveBeenCalled();
292 });
293
294 it("keeps the manual instruction for desktop servers without remote update support", async () => {
299 - await renderAction({ selfUpdate: "desktop-managed" });
295 + using _state = setup();
296 + await using screen = await renderAction({ selfUpdate: "desktop-managed" });
297
301 - expect(container.textContent).toBe(
298 + expect(screen.container.textContent).toBe(
299 "Update the desktop app on that machine to update this server.",
300 );
304 - expect(button()).toBeUndefined();
301 + expect(button(screen)).toBeUndefined();
302 });
303
304 it("updates remote desktop apps through the shared update flow after confirmation", async () => {
305 + using _state = setup();
306 registerConfirmDialogHost();
307 testState.updateServer.mockResolvedValue(success("desktop-app", "0.0.34"));
308
311 - await renderAction({ selfUpdate: "desktop-managed", desktopAppUpdate: true });
312 - await click("Update");
309 + await using screen = await renderAction({
310 + selfUpdate: "desktop-managed",
311 + desktopAppUpdate: true,
312 + });
313 + await click(screen, "Update");
314 expect(readConfirmDialogState()).toEqual(
315 expect.objectContaining({
316 status: "confirming",
@@ -330,10 +331,11 @@ describe("ServerUpdateAction", () => {
331 });
332
333 it("leaves thread continuation off by default", async () => {
334 + using _state = setup();
335 testState.updateServer.mockResolvedValue(success());
336
335 - await renderAction({ threadContinuation: true });
336 - await click("Update");
337 + await using screen = await renderAction({ threadContinuation: true });
338 + await click(screen, "Update");
339
340 expect(testState.updateServer).toHaveBeenCalledWith({
341 environmentId: "env-test",
@@ -342,11 +344,12 @@ describe("ServerUpdateAction", () => {
344 });
345
346 it("applies the saved thread continuation preference automatically", async () => {
347 + using _state = setup();
348 testState.updateServer.mockResolvedValue(success());
349 testState.continueThreadsAfterServerUpdate = true;
350
348 - await renderAction({ threadContinuation: true });
349 - await click("Update");
351 + await using screen = await renderAction({ threadContinuation: true });
352 + await click(screen, "Update");
353
354 expect(testState.updateServer).toHaveBeenCalledWith({
355 environmentId: "env-test",
@@ -381,12 +384,13 @@ describe("ServerUpdatesAction", () => {
384 },
385 ];
386
384 - const mount = (batch = targets) => render(<ServerUpdatesAction targets={batch} />);
387 + const mount = (batch = targets) => renderUpdate(<ServerUpdatesAction targets={batch} />);
388
389 it("updates both supported machines with their own continuation preference and skips the manual machine", async () => {
390 + using _state = setup();
391 testState.updateServer.mockResolvedValue(success());
388 - await mount();
389 - await click("Update all");
392 + await using screen = await mount();
393 + await click(screen, "Update all");
394
395 expect(testState.updateServer.mock.calls.map(([target]) => target)).toEqual([
396 {
@@ -402,11 +406,12 @@ describe("ServerUpdatesAction", () => {
406 });
407
408 it("names a failed machine while letting the other machine complete", async () => {
409 + using _state = setup();
410 testState.updateServer
411 .mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Download failed"))))
412 .mockResolvedValueOnce(success());
408 - await mount();
409 - await click("Update all");
413 + await using screen = await mount();
414 + await click(screen, "Update all");
415
416 expect(testState.updateServer).toHaveBeenCalledTimes(2);
417 expect(testState.toast).toHaveBeenCalledWith({
@@ -417,10 +422,11 @@ describe("ServerUpdatesAction", () => {
422 expect(testState.toast).toHaveBeenCalledWith(
423 expect.objectContaining({ type: "success", title: "Office updated" }),
424 );
420 - expect(button("Update all")!.disabled).toBe(false);
425 + expect(button(screen, "Update all")!.disabled).toBe(false);
426 });
427
428 it("starts each machine once when double-clicked and disables the action until both finish", async () => {
429 + using _state = setup();
430 const completions: Array<() => void> = [];
431 testState.updateServer.mockImplementation(
432 () =>
@@ -428,28 +434,29 @@ describe("ServerUpdatesAction", () => {
434 completions.push(() => resolve(success()));
435 }),
436 );
431 - await mount();
437 + await using screen = await mount();
438 await act(async () => {
433 - button("Update all")!.click();
434 - button("Update all")!.click();
439 + button(screen, "Update all")!.click();
440 + button(screen, "Update all")!.click();
441 });
442 expect(testState.updateServer).toHaveBeenCalledTimes(2);
437 - expect(button("Update all")!.disabled).toBe(true);
443 + expect(button(screen, "Update all")!.disabled).toBe(true);
444 await act(async () => completions[0]!());
439 - expect(button("Update all")!.disabled).toBe(true);
445 + expect(button(screen, "Update all")!.disabled).toBe(true);
446 await act(async () => completions[1]!());
441 - expect(button("Update all")!.disabled).toBe(false);
447 + expect(button(screen, "Update all")!.disabled).toBe(false);
448 expect(testState.toast).toHaveBeenCalledTimes(2);
449 });
450
451 it("asks once for desktop machines and cancels the entire batch", async () => {
452 + using _state = setup();
453 registerConfirmDialogHost();
447 - await mount(
454 + await using screen = await mount(
455 targets.map((target, index) =>
456 index < 2 ? { ...target, selfUpdate: "desktop-managed", desktopAppUpdate: true } : target,
457 ),
458 );
452 - await click("Update all");
459 + await click(screen, "Update all");
460 expect(readConfirmDialogState()).toEqual(
461 expect.objectContaining({
462 status: "confirming",
@@ -459,13 +466,14 @@ describe("ServerUpdatesAction", () => {
466 expect(testState.updateServer).not.toHaveBeenCalled();
467 await act(async () => respondToConfirmDialog(false));
468 expect(testState.updateServer).not.toHaveBeenCalled();
462 - expect(button("Update all")!.disabled).toBe(false);
469 + expect(button(screen, "Update all")!.disabled).toBe(false);
470 });
471 });
472
473 describe("ServerUpdateProgress", () => {
474 it("shows one calm status for the restart wait", async () => {
468 - await render(
475 + using _state = setup();
476 + await using screen = await renderUpdate(
477 <ServerUpdateProgress
478 state={{
479 status: "running",
@@ -475,11 +483,12 @@ describe("ServerUpdateProgress", () => {
483 }}
484 />,
485 );
478 - expect(container.textContent).toBe("Restarting…");
486 + expect(screen.container.textContent).toBe("Restarting…");
487 });
488
489 it("folds the sub-second installing handoff into the download phase", async () => {
482 - await render(
490 + using _state = setup();
491 + await using screen = await renderUpdate(
492 <ServerUpdateProgress
493 state={{
494 status: "running",
@@ -489,11 +498,12 @@ describe("ServerUpdateProgress", () => {
498 }}
499 />,
500 );
492 - expect(container.textContent).toBe("Downloading…");
501 + expect(screen.container.textContent).toBe("Downloading…");
502 });
503
504 it("keeps the failure visible as an alert with its error", async () => {
496 - await render(
505 + using _state = setup();
506 + await using screen = await renderUpdate(
507 <ServerUpdateProgress
508 state={{
509 status: "failed",
@@ -504,7 +514,7 @@ describe("ServerUpdateProgress", () => {
514 }}
515 />,
516 );
507 - expect(container.querySelector("[role=alert]")?.textContent).toBe(
517 + expect(screen.container.querySelector("[role=alert]")?.textContent).toBe(
518 "The package could not be verified.",
519 );
520 });
apps/web/src/components/Sidebar.pointer.browser.test.tsx
+35 -26
@@ -1,7 +1,7 @@
1 import type { SensorProps } from "@dnd-kit/core";
2 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 -import { act, StrictMode } from "react";
4 -import { createRoot } from "react-dom/client";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3 +import { StrictMode } from "react";
4 +import { fakeTimers, render } from "../../test/render";
5 import { SidebarDragLifecycle, SidebarPointerSensor } from "./Sidebar.pointer";
6
7 const sensors: SidebarPointerSensor[] = [];
@@ -42,24 +42,23 @@ function gesture(
42 return { sensor, onFinish, ...callbacks };
43 }
44
45 -beforeEach(() => {
46 - vi.useFakeTimers();
47 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
45 +function setup() {
46 + const stack = new DisposableStack();
47 + stack.use(fakeTimers());
48 hidden = false;
49 - vi.spyOn(document, "hidden", "get").mockImplementation(() => hidden);
50 -});
51 -afterEach(() => {
52 - for (const sensor of sensors.splice(0)) sensor.cancel();
53 - // Cancelled sensors keep suppressing clicks on the shared document until the next press.
54 - document.dispatchEvent(pointer("pointerdown"));
55 - vi.runAllTimers();
56 - vi.useRealTimers();
57 - vi.restoreAllMocks();
58 - vi.unstubAllGlobals();
59 -});
49 + stack.use(vi.spyOn(document, "hidden", "get").mockImplementation(() => hidden));
50 + stack.defer(() => {
51 + for (const sensor of sensors.splice(0)) sensor.cancel();
52 + // Cancelled sensors keep suppressing clicks on the shared document until the next press.
53 + document.dispatchEvent(pointer("pointerdown"));
54 + vi.runAllTimers();
55 + });
56 + return stack;
57 +}
58
59 describe("sidebar pointer lifecycle", () => {
60 it("keeps a click idle and starts only after the drag threshold", () => {
61 + using _environment = setup();
62 const click = gesture();
63 document.dispatchEvent(pointer("pointermove", { clientY: 16 }));
64 expect(click.onStart).not.toHaveBeenCalled();
@@ -77,6 +76,7 @@ describe("sidebar pointer lifecycle", () => {
76 });
77
78 it("moves to the pointer on the move that starts the drag", () => {
79 + using _environment = setup();
80 const drag = gesture();
81 document.dispatchEvent(pointer("pointermove", { clientY: 90 }));
82 expect(drag.onStart).toHaveBeenCalledExactlyOnceWith({ x: 10, y: 10 });
@@ -98,6 +98,7 @@ describe("sidebar pointer lifecycle", () => {
98 };
99 for (const [name, interrupt] of Object.entries(interruptions)) {
100 it.each([false, true])(`cancels on ${name}, started=%s, and ignores late events`, (started) => {
101 + using _environment = setup();
102 const drag = gesture();
103 if (started) document.dispatchEvent(pointer("pointermove", { clientY: 20 }));
104 interrupt();
@@ -120,6 +121,7 @@ describe("sidebar pointer lifecycle", () => {
121 }
122
123 it("hands claimed moves and drops to the context handlers and cancels the sort", () => {
124 + using _environment = setup();
125 const onMove = vi.fn((point: { x: number; y: number }) => point.x > 50);
126 const onDrop = vi.fn((point: { x: number; y: number }) => point.x > 50);
127 const drag = gesture({ onMove, onDrop });
@@ -143,6 +145,7 @@ describe("sidebar pointer lifecycle", () => {
145 });
146
147 it("drops context when a zero-button move precedes pointerup", () => {
148 + using _environment = setup();
149 const onDrop = vi.fn((point: { x: number; y: number }) => point.x > 50);
150 const drag = gesture({ onMove: (point) => point.x > 50, onDrop });
151 document.dispatchEvent(pointer("pointermove", { clientY: 20 }));
@@ -160,6 +163,7 @@ describe("sidebar pointer lifecycle", () => {
163 });
164
165 it("cancels a missed sidebar release without committing a reorder", () => {
166 + using _environment = setup();
167 const onDrop = vi.fn((point: { x: number; y: number }) => point.x > 50);
168 const drag = gesture({ onMove: (point) => point.x > 50, onDrop });
169 document.dispatchEvent(pointer("pointermove", { clientX: 90, clientY: 30 }));
@@ -173,6 +177,7 @@ describe("sidebar pointer lifecycle", () => {
177 });
178
179 it("does not drop context when the button is released before activation", () => {
180 + using _environment = setup();
181 const onDrop = vi.fn(() => true);
182 const drag = gesture({ onDrop });
183 document.dispatchEvent(pointer("pointermove", { buttons: 0, clientX: 90, clientY: 30 }));
@@ -185,6 +190,7 @@ describe("sidebar pointer lifecycle", () => {
190 });
191
192 it("resumes reordering when a context drag returns to the sidebar", () => {
193 + using _environment = setup();
194 const drag = gesture({
195 onMove: (point) => point.x > 50,
196 onDrop: (point) => point.x > 50,
@@ -204,6 +210,7 @@ describe("sidebar pointer lifecycle", () => {
210 });
211
212 it.each([false, true])("suppresses a cancelled release click, started=%s", (started) => {
213 + using _environment = setup();
214 const drag = gesture();
215 if (started) document.dispatchEvent(pointer("pointermove", { clientY: 20 }));
216 drag.sensor.cancel();
@@ -220,6 +227,7 @@ describe("sidebar pointer lifecycle", () => {
227 });
228
229 it.each([false, true])("allows a fresh click after an outside release, started=%s", (started) => {
230 + using _environment = setup();
231 const drag = gesture();
232 if (started) document.dispatchEvent(pointer("pointermove", { clientY: 20 }));
233 drag.sensor.cancel();
@@ -231,6 +239,7 @@ describe("sidebar pointer lifecycle", () => {
239 });
240
241 it("does not move after cancellation during activation", () => {
242 + using _environment = setup();
243 const drag = gesture();
244 drag.onStart.mockImplementation(() => drag.sensor.cancel());
245 document.dispatchEvent(pointer("pointermove", { clientY: 20 }));
@@ -240,6 +249,7 @@ describe("sidebar pointer lifecycle", () => {
249 });
250
251 it("ignores events from other pointers", () => {
252 + using _environment = setup();
253 const drag = gesture();
254 document.dispatchEvent(pointer("pointermove", { pointerId: 2, buttons: 0, clientY: 100 }));
255 document.dispatchEvent(pointer("pointercancel", { pointerId: 2 }));
@@ -250,19 +260,17 @@ describe("sidebar pointer lifecycle", () => {
260 expect(drag.onStart).toHaveBeenCalledOnce();
261 });
262
253 - it.each([false, true])("cancels when search unmounts the list, started=%s", (started) => {
254 - const root = createRoot(document.createElement("div"));
263 + it.each([false, true])("cancels when search unmounts the list, started=%s", async (started) => {
264 + using _environment = setup();
265 let drag: ReturnType<typeof gesture> | undefined;
256 - act(() =>
257 - root.render(
258 - <StrictMode>
259 - <SidebarDragLifecycle onUnmount={() => drag?.sensor.cancel()} />
260 - </StrictMode>,
261 - ),
266 + await using screen = await render(
267 + <StrictMode>
268 + <SidebarDragLifecycle onUnmount={() => drag?.sensor.cancel()} />
269 + </StrictMode>,
270 );
271 drag = gesture();
272 if (started) document.dispatchEvent(pointer("pointermove", { clientY: 20 }));
265 - act(() => root.unmount());
273 + await screen.unmount();
274 document.dispatchEvent(pointer("pointermove", { clientY: 100 }));
275 document.dispatchEvent(pointer("pointerup", { buttons: 0 }));
276 expect(drag.onStart).toHaveBeenCalledTimes(started ? 1 : 0);
@@ -272,6 +280,7 @@ describe("sidebar pointer lifecycle", () => {
280 });
281
282 it("detaches a cancelled sensor before a replacement gesture starts", () => {
283 + using _environment = setup();
284 const previous = gesture();
285 document.dispatchEvent(pointer("pointermove", { clientY: 20 }));
286 previous.sensor.cancel();
apps/web/src/components/SidebarStageBackdrop.browser.test.tsx
+8 -27
@@ -1,39 +1,20 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
1 +import { expect, it } from "vite-plus/test";
2
3 +import { render } from "../../test/render";
4 import { StageBackdropArt } from "./SidebarStageBackdrop";
5
7 -let root: Root;
8 -let container: HTMLDivElement;
9 -
10 -beforeEach(() => {
11 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
12 - container = document.createElement("div");
13 - document.body.append(container);
14 - root = createRoot(container);
15 -});
16 -
17 -afterEach(async () => {
18 - await act(() => root.unmount());
19 - container.remove();
20 - vi.unstubAllGlobals();
21 -});
22 -
6 // Gradients and patterns resolve url(#id) document-wide, so a repeated id would paint one
7 // backdrop with another's definitions.
8 it.each(["nightly", "dev"] as const)(
9 "gives every %s backdrop its own SVG definitions when two are on the page",
10 async (variant) => {
28 - await act(() =>
29 - root.render(
30 - <>
31 - <StageBackdropArt variant={variant} />
32 - <StageBackdropArt variant={variant} />
33 - </>,
34 - ),
11 + await using screen = await render(
12 + <>
13 + <StageBackdropArt variant={variant} />
14 + <StageBackdropArt variant={variant} />
15 + </>,
16 );
36 - const [first, second] = container.querySelectorAll("svg");
17 + const [first, second] = screen.container.querySelectorAll("svg");
18 const ids = (svg: Element | undefined) => [...svg!.querySelectorAll("[id]")].map((el) => el.id);
19
20 expect(ids(first).length).toBeGreaterThan(0);
apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsx
+69 -64
@@ -3,9 +3,9 @@ import { EnvironmentId } from "@t3tools/contracts";
3 import * as DateTime from "effect/DateTime";
4 import * as Option from "effect/Option";
5 import { Atom, AtomRegistry } from "effect/reactivity";
6 -import { act } from "react";
7 -import { createRoot, type Root } from "react-dom/client";
8 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
6 +import { expect, it, vi } from "vite-plus/test";
7 +
8 +import { render, stubGlobal, type Screen } from "../../test/render";
9
10 const state = vi.hoisted(() => ({
11 mode: "notifications",
@@ -85,7 +85,6 @@ const thread = {
85 session: null as { status: string } | null,
86 latestTurn: { turnId: "turn", state: "running", completedAt: null as string | null },
87 };
88 -let root: Root;
88 let focused = false;
89 let visibility = "visible";
90
@@ -161,19 +160,14 @@ function complete(environment = "one", completedAt = "2026-09-13T08:00:00Z") {
160 shell({ latestTurn: { turnId: "turn", state: "completed", completedAt } }),
161 );
162 }
164 -async function render() {
165 - await act(async () =>
166 - root.render(
167 - <RegistryContext.Provider value={registry}>
168 - <ThreadNotificationCoordinator />
169 - </RegistryContext.Provider>,
170 - ),
171 - );
172 -}
173 -
174 -beforeEach(() => {
163 +// The mocked modules read `state`, the registry and the focus flags, so every test starts by
164 +// resetting them. The first render is left to the test because some tests change state first.
165 +function setup() {
166 vi.clearAllMocks();
167 + const stack = new AsyncDisposableStack();
168 registry = AtomRegistry.make();
169 + const testRegistry = registry;
170 + stack.defer(() => testRegistry.dispose());
171 state.mode = "notifications";
172 state.inApp = false;
173 state.environmentIds = ["one", "two"];
@@ -183,25 +177,32 @@ beforeEach(() => {
177 visibility = "visible";
178 TestNotification.permission = "granted";
179 TestNotification.sent = [];
186 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
187 - vi.stubGlobal("Notification", TestNotification);
188 - vi.spyOn(window, "focus").mockImplementation(() => undefined);
189 - vi.spyOn(document, "hasFocus").mockImplementation(() => focused);
190 - vi.spyOn(document, "visibilityState", "get").mockImplementation(
191 - () => visibility as DocumentVisibilityState,
180 + stack.use(stubGlobal("Notification", TestNotification));
181 + stack.use(vi.spyOn(window, "focus").mockImplementation(() => undefined));
182 + stack.use(vi.spyOn(document, "hasFocus").mockImplementation(() => focused));
183 + stack.use(
184 + vi
185 + .spyOn(document, "visibilityState", "get")
186 + .mockImplementation(() => visibility as DocumentVisibilityState),
187 );
193 - root = createRoot(document.createElement("div"));
194 -});
195 -
196 -afterEach(async () => {
197 - await act(async () => root.unmount());
198 - delete window.desktopBridge;
199 - registry.dispose();
200 - vi.restoreAllMocks();
201 - vi.unstubAllGlobals();
202 -});
188 + const ui = () => (
189 + <RegistryContext.Provider value={testRegistry}>
190 + <ThreadNotificationCoordinator />
191 + </RegistryContext.Provider>
192 + );
193 + let screen: Screen | undefined;
194 + return {
195 + async render() {
196 + if (screen) await screen.rerender(ui());
197 + else screen = stack.use(await render(ui()));
198 + },
199 + unmount: () => screen!.unmount(),
200 + [Symbol.asyncDispose]: () => stack.disposeAsync(),
201 + };
202 +}
203
204 it("uses bounded tags across threads and environments, replaces repeat alerts, and clears on focus", async () => {
205 + await using app = setup();
206 const environmentId = "fd6fff30-f90b-4ee7-9812-4cf497791b90";
207 const otherEnvironmentId = "25b62992-b996-4ee3-8d82-d988840e45c1";
208 const threadId = "a8395a98-a186-4fe7-9d4c-fb8ba63b7588";
@@ -213,19 +214,19 @@ it("uses bounded tags across threads and environments, replaces repeat alerts, a
214 state.environmentIds = [environmentId, otherEnvironmentId];
215 state.shells.set(environmentId, shell({ id: threadId }, { id: otherThreadId }));
216 state.shells.set(otherEnvironmentId, shell({ id: threadId }));
216 - await render();
217 + await app.render();
218 state.shells.set(environmentId, shell(completed(threadId), { id: otherThreadId }));
218 - await render();
219 + await app.render();
220 expect(state.badge).toHaveBeenLastCalledWith(1);
221 state.shells.set(environmentId, shell(completed(threadId), completed(otherThreadId)));
222 state.shells.set(otherEnvironmentId, shell(completed(threadId)));
222 - await render();
223 + await app.render();
224 expect(state.badge).toHaveBeenLastCalledWith(3);
225 state.shells.set(
226 environmentId,
227 shell(completed(threadId, "2026-09-13T08:01:00Z"), completed(otherThreadId)),
228 );
228 - await render();
229 + await app.render();
230 expect(state.badge).toHaveBeenLastCalledWith(3);
231 expect(TestNotification.sent).toHaveLength(4);
232 const [first, otherThread, otherEnvironment, replacement] = TestNotification.sent;
@@ -246,62 +247,62 @@ it("uses bounded tags across threads and environments, replaces repeat alerts, a
247 ).toBe(true);
248 focused = false;
249 state.shells.set(otherEnvironmentId, shell(completed(threadId, "2026-09-13T08:02:00Z")));
249 - await render();
250 + await app.render();
251 expect(state.badge).toHaveBeenLastCalledWith(1);
252 });
253
254 it("does not badge old completions on first load or reconnect", async () => {
255 + await using app = setup();
256 complete();
255 - await render();
257 + await app.render();
258 state.shells.set("one", { status: "connecting", snapshot: Option.none() });
257 - await render();
259 + await app.render();
260 complete("one", "2026-09-13T08:01:00Z");
259 - await render();
261 + await app.render();
262 expect(TestNotification.sent).toHaveLength(0);
263 expect(state.badge.mock.calls.every(([count]) => count === 0)).toBe(true);
264 });
265
266 it("removes alerts only from environments that leave the client", async () => {
265 - await render();
267 + await using app = setup();
268 + await app.render();
269 complete("one");
270 complete("two");
268 - await render();
271 + await app.render();
272 expect(state.badge).toHaveBeenLastCalledWith(2);
273 const [removed, retained] = TestNotification.sent;
274 state.environmentIds = ["two"];
272 - await render();
275 + await app.render();
276 expect(state.badge).toHaveBeenLastCalledWith(1);
277 expect(removed!.close).toHaveBeenCalledOnce();
278 expect(retained!.close).not.toHaveBeenCalled();
276 - await render();
279 + await app.render();
280 expect(removed!.close).toHaveBeenCalledOnce();
281 state.environmentIds = [];
279 - await render();
282 + await app.render();
283 expect(state.badge).toHaveBeenLastCalledWith(0);
284 expect(retained!.close).toHaveBeenCalledOnce();
285 });
286
287 it("starts a fresh count after another native app window gains focus", async () => {
288 + await using app = setup();
289 let clear: (() => void) | undefined;
290 const unsubscribe = vi.fn();
287 - Object.assign(window, {
288 - desktopBridge: {
289 - onNotificationBadgeClear: (listener: () => void) => {
290 - clear = listener;
291 - return unsubscribe;
292 - },
291 + using _bridge = stubGlobal("desktopBridge", {
292 + onNotificationBadgeClear: (listener: () => void) => {
293 + clear = listener;
294 + return unsubscribe;
295 },
296 });
295 - await render();
297 + await app.render();
298 complete();
297 - await render();
299 + await app.render();
300 clear!();
301 expect(state.badge).toHaveBeenLastCalledWith(0);
302 complete("two");
301 - await render();
303 + await app.render();
304 expect(state.badge).toHaveBeenLastCalledWith(1);
303 - await act(async () => root.unmount());
304 - root = createRoot(document.createElement("div"));
305 + await app.unmount();
306 expect(unsubscribe).toHaveBeenCalledOnce();
307 expect(state.badge).toHaveBeenLastCalledWith(0);
308 });
@@ -309,10 +310,11 @@ it("starts a fresh count after another native app window gains focus", async ()
310 it.each(["off", "sound", "focused", "denied", "archived"])(
311 "does not show visual alerts when %s",
312 async (condition) => {
313 + await using app = setup();
314 if (condition === "off" || condition === "sound") state.mode = condition;
315 if (condition === "focused") focused = true;
316 if (condition === "denied") TestNotification.permission = "denied";
315 - await render();
317 + await app.render();
318 complete();
319 if (condition === "archived")
320 state.shells.set(
@@ -322,7 +324,7 @@ it.each(["off", "sound", "focused", "denied", "archived"])(
324 hasPendingApprovals: true,
325 }),
326 );
325 - await render();
327 + await app.render();
328 expect(TestNotification.sent).toHaveLength(0);
329 expect(state.badge.mock.calls.every(([count]) => count === 0)).toBe(true);
330 },
@@ -331,9 +333,10 @@ it.each(["off", "sound", "focused", "denied", "archived"])(
333 it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
334 "badges %s and clears when notifications are disabled",
335 async (flag) => {
334 - await render();
336 + await using app = setup();
337 + await app.render();
338 state.shells.set("one", shell({ [flag]: true }));
336 - await render();
339 + await app.render();
340 expect(state.badge).toHaveBeenLastCalledWith(1);
341 const notification = TestNotification.sent[0]!;
342 notification.dispatchEvent(new Event("click"));
@@ -342,28 +345,30 @@ it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
345 params: { environmentId: EnvironmentId.make("one"), threadId: "thread" },
346 });
347 state.mode = "sound";
345 - await render();
348 + await app.render();
349 expect(state.badge).toHaveBeenLastCalledWith(0);
350 expect(notification.close).toHaveBeenCalled();
351 },
352 );
353
354 it("shows in-app alerts without adding a badge while focused", async () => {
355 + await using app = setup();
356 state.inApp = true;
357 focused = true;
354 - await render();
358 + await app.render();
359 complete();
356 - await render();
360 + await app.render();
361 expect(state.toast).toHaveBeenCalledOnce();
362 expect(TestNotification.sent).toHaveLength(0);
363 expect(state.badge.mock.calls.every(([count]) => count === 0)).toBe(true);
364 });
365
366 it("badges background failures with in-app notifications enabled", async () => {
367 + await using app = setup();
368 state.inApp = true;
364 - await render();
369 + await app.render();
370 state.shells.set("one", shell({ latestTurn: { ...thread.latestTurn, state: "error" } }));
366 - await render();
371 + await app.render();
372 expect(TestNotification.sent[0]?.title).toBe("Thread failed");
373 expect(state.badge).toHaveBeenLastCalledWith(1);
374 expect(state.toast).not.toHaveBeenCalled();
apps/web/src/components/ThreadNotificationCoordinator.browser.test.tsx
+80 -66
@@ -1,9 +1,9 @@
1 import type { ClientSettings } from "@t3tools/contracts/settings";
2 import * as DateTime from "effect/DateTime";
3 import * as Option from "effect/Option";
4 -import { act } from "react";
5 -import { createRoot, type Root } from "react-dom/client";
6 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4 +import { describe, expect, it, vi } from "vite-plus/test";
5 +
6 +import { render, stubGlobal, type Screen } from "../../test/render";
7
8 const state = vi.hoisted(() => ({
9 mode: "off" as ClientSettings["notificationMode"],
@@ -150,18 +150,9 @@ vi.mock(import("./ui/toast"), async (original) => {
150
151 import { ThreadNotificationCoordinator } from "./ThreadNotificationCoordinator";
152
153 -let root: Root;
154 -
155 -async function render() {
156 - await act(() => root.render(<ThreadNotificationCoordinator />));
157 -}
158 -
159 -async function complete() {
160 - state.completedAt = "2026-09-13T10:00:00.000Z";
161 - await render();
162 -}
163 -
164 -beforeEach(() => {
153 +// The mocked modules read `state`, so every test starts by resetting all of it. The first
154 +// render is left to the test because some tests change state before the coordinator mounts.
155 +function setup() {
156 vi.clearAllMocks();
157 Object.assign(state, {
158 mode: "off",
@@ -182,42 +173,54 @@ beforeEach(() => {
173 delegatedChild: null,
174 });
175 stableParent = null;
185 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
186 - vi.spyOn(document, "visibilityState", "get").mockImplementation(
187 - () => state.visible as DocumentVisibilityState,
176 + const stack = new AsyncDisposableStack();
177 + stack.use(
178 + vi
179 + .spyOn(document, "visibilityState", "get")
180 + .mockImplementation(() => state.visible as DocumentVisibilityState),
181 );
189 - vi.spyOn(document, "hasFocus").mockImplementation(() => state.focused);
190 - vi.stubGlobal("Notification", Object.assign(state.notification, { permission: "granted" }));
191 - root = createRoot(document.createElement("div"));
192 -});
193 -
194 -afterEach(async () => {
195 - await act(() => root.unmount());
196 - vi.restoreAllMocks();
197 - vi.unstubAllGlobals();
198 -});
182 + stack.use(vi.spyOn(document, "hasFocus").mockImplementation(() => state.focused));
183 + stack.use(
184 + stubGlobal("Notification", Object.assign(state.notification, { permission: "granted" })),
185 + );
186 + let screen: Screen | undefined;
187 + const renderCoordinator = async () => {
188 + if (screen) await screen.rerender(<ThreadNotificationCoordinator />);
189 + else screen = stack.use(await render(<ThreadNotificationCoordinator />));
190 + };
191 + return {
192 + render: renderCoordinator,
193 + complete: async () => {
194 + state.completedAt = "2026-09-13T10:00:00.000Z";
195 + await renderCoordinator();
196 + },
197 + [Symbol.asyncDispose]: () => stack.disposeAsync(),
198 + };
199 +}
200
201 describe("thread notifications", () => {
202 it.each([true, false])("keeps subagents silent with focus=%s", async (focused) => {
203 + await using app = setup();
204 state.subagent = true;
205 state.focused = focused;
206 state.mode = "notifications-and-sound";
205 - await render();
206 - await complete();
207 + await app.render();
208 + await app.complete();
209 state.input = true;
208 - await render();
210 + await app.render();
211 expect(state.sound).not.toHaveBeenCalled();
212 expect(state.add).not.toHaveBeenCalled();
213 expect(state.notification).not.toHaveBeenCalled();
214 });
215
216 it("alerts on the parent when its delegated subagent asks for approval", async () => {
217 + await using app = setup();
218 state.mode = "notifications-and-sound";
219 state.delegatedChild = "running";
217 - await render();
220 + await app.render();
221 state.delegatedChild = "approval";
219 - await render();
220 - await render();
222 + await app.render();
223 + await app.render();
224 expect(state.add).toHaveBeenCalledTimes(1);
225 expect(state.add).toHaveBeenLastCalledWith(
226 expect.objectContaining({ title: "Approval needed", description: "Fix the login form" }),
@@ -225,9 +228,10 @@ describe("thread notifications", () => {
228 });
229
230 it("alerts once with system alerts off and opens the completed thread", async () => {
228 - await render();
229 - await complete();
230 - await render();
231 + await using app = setup();
232 + await app.render();
233 + await app.complete();
234 + await app.render();
235 expect(state.add).toHaveBeenCalledTimes(1);
236 const toast = state.add.mock.calls[0]?.[0];
237 expect(toast?.title).toBe("Thread completed");
@@ -244,13 +248,14 @@ describe("thread notifications", () => {
248 it.each(["active", "blurred", "hidden", "archived", "disabled"])(
249 "does not show a completion toast for %s threads",
250 async (condition) => {
247 - await render();
251 + await using app = setup();
252 + await app.render();
253 if (condition === "active") state.active.threadId = "thread-1";
254 if (condition === "blurred") state.focused = false;
255 if (condition === "hidden") state.visible = "hidden";
256 if (condition === "archived") state.archivedAt = "2026-09-13T09:00:00.000Z";
257 if (condition === "disabled") state.inApp = false;
253 - await complete();
258 + await app.complete();
259 expect(state.add).not.toHaveBeenCalled();
260 },
261 );
@@ -262,22 +267,23 @@ describe("thread notifications", () => {
267 ["turnError", "Thread failed"],
268 ["limited", "Usage limit reached"],
269 ] as const)("uses the same %s event for in-app and desktop alerts", async (event, title) => {
270 + await using app = setup();
271 state.mode = "notifications-and-sound";
266 - await render();
272 + await app.render();
273 state[event] = true;
268 - await render();
269 - await render();
274 + await app.render();
275 + await app.render();
276 expect(state.add).toHaveBeenCalledTimes(1);
277 expect(state.add).toHaveBeenLastCalledWith(expect.objectContaining({ title }));
278 expect(state.sound).toHaveBeenCalledWith("input", expect.any(Function));
279 expect(state.notification).not.toHaveBeenCalled();
280
281 state[event] = false;
276 - await render();
282 + await app.render();
283 state.focused = false;
284 state[event] = true;
279 - await render();
280 - await render();
285 + await app.render();
286 + await app.render();
287 expect(state.add).toHaveBeenCalledTimes(1);
288 expect(state.notification).toHaveBeenCalledTimes(1);
289 expect(state.notification).toHaveBeenCalledWith(title, {
@@ -288,12 +294,13 @@ describe("thread notifications", () => {
294 });
295
296 it("alerts when only a dev server is left running, not while a monitor can wake the agent", async () => {
291 - await render();
297 + await using app = setup();
298 + await app.render();
299 state.background = [{ taskId: "watch", kind: "monitor" }];
293 - await complete();
300 + await app.complete();
301 expect(state.add).not.toHaveBeenCalled();
302 state.background = [{ taskId: "dev", kind: "command" }];
296 - await render();
303 + await app.render();
304 expect(state.add).toHaveBeenCalledTimes(1);
305 expect(state.add).toHaveBeenLastCalledWith(
306 expect.objectContaining({ title: "Thread completed" }),
@@ -301,57 +308,63 @@ describe("thread notifications", () => {
308 });
309
310 it("keeps background desktop alerts when in-app notifications are disabled", async () => {
311 + await using app = setup();
312 state.focused = false;
313 state.inApp = false;
314 state.mode = "notifications";
307 - await render();
308 - await complete();
315 + await app.render();
316 + await app.complete();
317 expect(state.add).not.toHaveBeenCalled();
318 expect(state.notification).toHaveBeenCalledTimes(1);
319 state.inApp = true;
312 - await render();
320 + await app.render();
321 expect(state.add).not.toHaveBeenCalled();
322 });
323
324 it("does not replay a completion when opting in from all alerts off", async () => {
325 + await using app = setup();
326 state.inApp = false;
318 - await render();
319 - await complete();
327 + await app.render();
328 + await app.complete();
329 state.inApp = true;
321 - await render();
330 + await app.render();
331 expect(state.add).not.toHaveBeenCalled();
332 });
333
334 it("compares the environment as well as the thread", async () => {
335 + await using app = setup();
336 state.active = { environmentId: "env-2", threadId: "thread-1" };
327 - await render();
328 - await complete();
337 + await app.render();
338 + await app.complete();
339 expect(state.add).toHaveBeenCalledTimes(1);
340 });
341
342 it("does not replay completed threads on first load or reconnect", async () => {
333 - await complete();
343 + await using app = setup();
344 + await app.complete();
345 state.live = false;
335 - await render();
346 + await app.render();
347 state.live = true;
337 - await render();
348 + await app.render();
349 expect(state.add).not.toHaveBeenCalled();
350 });
351
352 it("keeps sound but replaces the system popup when showing a toast", async () => {
353 + await using app = setup();
354 state.mode = "notifications-and-sound";
343 - await render();
344 - await complete();
355 + await app.render();
356 + await app.complete();
357 expect(state.sound).toHaveBeenCalledWith("completion", expect.any(Function));
358 expect(state.add).toHaveBeenCalledTimes(1);
359 expect(state.notification).not.toHaveBeenCalled();
360 });
361
362 it("keeps system alerts when the app is in the background", async () => {
363 + await using app = setup();
364 state.mode = "notifications";
365 state.focused = false;
353 - await render();
354 - await complete();
366 + await app.render();
367 + await app.complete();
368 expect(state.add).not.toHaveBeenCalled();
369 expect(state.notification).toHaveBeenCalledWith("Thread completed", {
370 body: "Fix the login form",
@@ -361,12 +374,13 @@ describe("thread notifications", () => {
374 });
375
376 it("reveals the desktop window and opens the thread when a system alert is clicked", async () => {
377 + await using app = setup();
378 const revealWindow = vi.fn(() => Promise.resolve());
365 - vi.stubGlobal("desktopBridge", { revealWindow });
379 + using _bridge = stubGlobal("desktopBridge", { revealWindow });
380 state.mode = "notifications";
381 state.focused = false;
368 - await render();
369 - await complete();
382 + await app.render();
383 + await app.complete();
384 const notification: EventTarget = state.notification.mock.results[0]?.value;
385 notification.dispatchEvent(new Event("click"));
386 expect(revealWindow).toHaveBeenCalledTimes(1);
apps/web/src/components/ThreadStatusIndicators.subscriptions.browser.test.tsx
+85 -109
@@ -4,14 +4,14 @@ import {
4 type ThreadPullRequestLink,
5 type VcsStatusResult,
6 } from "@t3tools/contracts";
7 -import { act, type MouseEvent } from "react";
8 -import { createRoot } from "react-dom/client";
9 -import { afterEach, expect, it, vi } from "vite-plus/test";
7 +import type { MouseEvent } from "react";
8 +import { expect, it, vi } from "vite-plus/test";
9 import { page, userEvent } from "vite-plus/test/browser";
10
11 import "../index.css";
12 import { Button } from "./ui/button";
13
14 +import { act, render } from "../../test/render";
15 import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
16 import { makeThreadFixture } from "../test-fixtures";
17
@@ -86,17 +86,12 @@ vi.mock(import("../state/pullRequests"), async (importOriginal) => {
86 });
87 import { ThreadPullRequestBadgeControl, ThreadRowLeadingStatus } from "./ThreadStatusIndicators";
88
89 -afterEach(() => {
90 - vi.unstubAllGlobals();
91 -});
92 -
89 // The lease overscans 160px around a 20px viewport, a 340px band. With 45px rows the band
90 // covers exactly 8 rows at each scroll position below.
91 const ROW_HEIGHT = 45;
92 const SPACER = 1000;
93
94 it("leases only visible palette results while retaining observed and cached PR badges", async () => {
99 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
95 const threads = Array.from({ length: 128 }, (_, index) =>
96 makeThreadFixture({
97 id: ThreadId.make(`palette-thread-${index}`),
@@ -113,12 +108,9 @@ it("leases only visible palette results while retaining observed and cached PR b
108 },
109 }),
110 );
116 - const container = document.createElement("div");
117 - document.body.append(container);
118 - const root = createRoot(container);
111 state.queries.length = 0;
112 const viewport = () =>
121 - container.querySelector<HTMLElement>('[data-slot="scroll-area-viewport"]')!;
113 + screen.container.querySelector<HTMLElement>('[data-slot="scroll-area-viewport"]')!;
114 const scrollTo = async (top: number) => {
115 await act(async () => {
116 viewport().scrollTop = top;
@@ -126,68 +118,63 @@ it("leases only visible palette results while retaining observed and cached PR b
118 });
119 };
120 const badgeCount = () =>
129 - [...container.querySelectorAll("[aria-label]")].filter((node) =>
121 + [...screen.container.querySelectorAll("[aria-label]")].filter((node) =>
122 node.getAttribute("aria-label")!.startsWith("PR #"),
123 ).length;
132 - try {
133 - await act(async () =>
134 - root.render(
135 - <AppAtomRegistryProvider>
136 - <div data-slot="scroll-area-viewport" style={{ height: 20, overflowY: "auto" }}>
137 - <div style={{ height: SPACER }} />
138 - {threads.map((thread, index) => (
139 - <div key={thread.id} style={{ height: ROW_HEIGHT, overflow: "hidden" }}>
140 - <ThreadRowLeadingStatus
141 - thread={thread}
142 - snapshot={
143 - index === 126
144 - ? {
145 - branch: "feature/test",
146 - sourceControlProvider: undefined,
147 - pr: {
148 - number: 126,
149 - title: "Cached badge",
150 - url: "https://github.com/example/repo/pull/126",
151 - baseRef: "main",
152 - headRef: "feature/test",
153 - state: "open",
154 - },
155 - }
156 - : undefined
157 - }
158 - />
159 - {thread.title}
160 - </div>
161 - ))}
124 + await using screen = await render(
125 + <AppAtomRegistryProvider>
126 + <div data-slot="scroll-area-viewport" style={{ height: 20, overflowY: "auto" }}>
127 + <div style={{ height: SPACER }} />
128 + {threads.map((thread, index) => (
129 + <div key={thread.id} style={{ height: ROW_HEIGHT, overflow: "hidden" }}>
130 + <ThreadRowLeadingStatus
131 + thread={thread}
132 + snapshot={
133 + index === 126
134 + ? {
135 + branch: "feature/test",
136 + sourceControlProvider: undefined,
137 + pr: {
138 + number: 126,
139 + title: "Cached badge",
140 + url: "https://github.com/example/repo/pull/126",
141 + baseRef: "main",
142 + headRef: "feature/test",
143 + state: "open",
144 + },
145 + }
146 + : undefined
147 + }
148 + />
149 + {thread.title}
150 </div>
163 - </AppAtomRegistryProvider>,
164 - ),
165 - );
166 - await scrollTo(0);
167 - expect(state.queries).toEqual([]);
168 - expect(badgeCount()).toBe(1);
151 + ))}
152 + </div>
153 + </AppAtomRegistryProvider>,
154 + );
155 + await scrollTo(0);
156 + expect(state.queries).toEqual([]);
157 + expect(badgeCount()).toBe(1);
158
170 - // Band [1000, 1340]: rows 0..7.
171 - await scrollTo(SPACER + 160);
172 - expect(state.queries).toHaveLength(8);
173 - expect(state.queries.filter((key) => key.startsWith("vcs:"))).toHaveLength(4);
174 - expect(state.queries.filter((key) => key.startsWith("pr:"))).toHaveLength(4);
175 - expect(badgeCount()).toBe(9);
159 + // Band [1000, 1340]: rows 0..7.
160 + await scrollTo(SPACER + 160);
161 + expect(state.queries).toHaveLength(8);
162 + expect(state.queries.filter((key) => key.startsWith("vcs:"))).toHaveLength(4);
163 + expect(state.queries.filter((key) => key.startsWith("pr:"))).toHaveLength(4);
164 + expect(badgeCount()).toBe(9);
165
177 - // Band [1370, 1710]: rows 8..15.
178 - await scrollTo(SPACER + 8 * ROW_HEIGHT + 10 + 160);
179 - expect(state.queries).toHaveLength(16);
180 - expect(badgeCount()).toBe(17);
181 - } finally {
182 - await act(async () => root.unmount());
183 - container.remove();
184 - }
166 + // Band [1370, 1710]: rows 8..15.
167 + await scrollTo(SPACER + 8 * ROW_HEIGHT + 10 + 160);
168 + expect(state.queries).toHaveLength(16);
169 + expect(badgeCount()).toBe(17);
170 });
171
172 it("keeps a long PR hover list in the viewport and lets the last row be selected", async () => {
188 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
173 const previousViewport = { width: window.innerWidth, height: window.innerHeight };
174 await page.viewport(800, 480);
175 + await using _viewport = {
176 + [Symbol.asyncDispose]: () => page.viewport(previousViewport.width, previousViewport.height),
177 + };
178 const pullRequests = Array.from({ length: 40 }, (_, index): ThreadPullRequestLink => ({
179 host: "github.com",
180 repository: "example/repo",
@@ -199,50 +186,39 @@ it("keeps a long PR hover list in the viewport and lets the last row be selected
186 stack: null,
187 }));
188 const onOpenPullRequest = vi.fn((event: MouseEvent<HTMLElement>) => event.preventDefault());
202 - const container = document.createElement("div");
203 - document.body.append(container);
204 - const root = createRoot(container);
205 - try {
206 - await act(async () =>
207 - root.render(
208 - <div style={{ position: "fixed", top: 220, left: 300 }}>
209 - <ThreadPullRequestBadgeControl
210 - render={<Button size="xs" />}
211 - badge={{ kind: "pull-request", others: 39, state: "open" }}
212 - pullRequests={pullRequests}
213 - number={1}
214 - url={pullRequests[0]!.url}
215 - status={null}
216 - onOpenList={() => {}}
217 - onOpenPullRequest={onOpenPullRequest}
218 - />
219 - </div>,
220 - ),
221 - );
222 - await act(() => userEvent.hover(container.querySelector("button")!));
223 - const popup = () => document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]')!;
224 - await expect.poll(() => popup()?.querySelectorAll("a").length).toBe(40);
225 - await expect.poll(() => popup().getBoundingClientRect().top).toBeGreaterThanOrEqual(0);
226 - await expect
227 - .poll(() => popup().getBoundingClientRect().bottom)
228 - .toBeLessThanOrEqual(window.innerHeight);
189 + await using screen = await render(
190 + <div style={{ position: "fixed", top: 220, left: 300 }}>
191 + <ThreadPullRequestBadgeControl
192 + render={<Button size="xs" />}
193 + badge={{ kind: "pull-request", others: 39, state: "open" }}
194 + pullRequests={pullRequests}
195 + number={1}
196 + url={pullRequests[0]!.url}
197 + status={null}
198 + onOpenList={() => {}}
199 + onOpenPullRequest={onOpenPullRequest}
200 + />
201 + </div>,
202 + );
203 + await act(() => userEvent.hover(screen.container.querySelector("button")!));
204 + const popup = () => document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]')!;
205 + await expect.poll(() => popup()?.querySelectorAll("a").length).toBe(40);
206 + await expect.poll(() => popup().getBoundingClientRect().top).toBeGreaterThanOrEqual(0);
207 + await expect
208 + .poll(() => popup().getBoundingClientRect().bottom)
209 + .toBeLessThanOrEqual(window.innerHeight);
210
230 - const lastRow = popup().querySelector<HTMLAnchorElement>("li:last-child a")!;
231 - expect(lastRow.getBoundingClientRect().top).toBeGreaterThan(
232 - popup().getBoundingClientRect().bottom,
233 - );
234 - await act(() => userEvent.wheel(popup(), { delta: { y: 10_000 } }));
235 - await expect
236 - .poll(() => lastRow.getBoundingClientRect().bottom)
237 - .toBeLessThanOrEqual(popup().getBoundingClientRect().bottom);
238 - expect(lastRow.getBoundingClientRect().top).toBeGreaterThanOrEqual(
239 - popup().getBoundingClientRect().top,
240 - );
241 - await act(() => userEvent.click(lastRow));
242 - expect(onOpenPullRequest).toHaveBeenCalledExactlyOnceWith(expect.anything(), lastRow.href);
243 - } finally {
244 - await act(async () => root.unmount());
245 - container.remove();
246 - await page.viewport(previousViewport.width, previousViewport.height);
247 - }
211 + const lastRow = popup().querySelector<HTMLAnchorElement>("li:last-child a")!;
212 + expect(lastRow.getBoundingClientRect().top).toBeGreaterThan(
213 + popup().getBoundingClientRect().bottom,
214 + );
215 + await act(() => userEvent.wheel(popup(), { delta: { y: 10_000 } }));
216 + await expect
217 + .poll(() => lastRow.getBoundingClientRect().bottom)
218 + .toBeLessThanOrEqual(popup().getBoundingClientRect().bottom);
219 + expect(lastRow.getBoundingClientRect().top).toBeGreaterThanOrEqual(
220 + popup().getBoundingClientRect().top,
221 + );
222 + await act(() => userEvent.click(lastRow));
223 + expect(onOpenPullRequest).toHaveBeenCalledExactlyOnceWith(expect.anything(), lastRow.href);
224 });
apps/web/src/components/ThreadTerminalDrawer.permissions.browser.test.tsx
+92 -105
@@ -7,9 +7,7 @@ import {
7 import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
8 import { nextTerminalAttachSeedState } from "@t3tools/client-runtime/state/terminal";
9 import { AsyncResult } from "effect/reactivity";
10 -import { act } from "react";
11 -import { createRoot, type Root } from "react-dom/client";
12 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
10 +import { expect, it, vi } from "vite-plus/test";
11 import type {
12 GhosttyTerminalSurface,
13 GhosttyTerminalSurfaceOptions,
@@ -82,6 +80,7 @@ vi.mock(import("../state/session"), async (original) => {
80 };
81 });
82
83 +import { act, render } from "../../test/render";
84 import ThreadTerminalDrawer, { TerminalViewport } from "./ThreadTerminalDrawer";
85
86 const threadRef = {
@@ -89,10 +88,8 @@ const threadRef = {
88 threadId: ThreadId.make("thread"),
89 };
90 const session = { ...nextTerminalAttachSeedState(), status: "running" as const, version: 1 };
92 -let root: Root;
93 -let container: HTMLDivElement;
94 -
95 -beforeEach(() => {
91 +// The mocked modules read `state`, so every test starts by resetting all of it.
92 +function setup() {
93 state.allowed = true;
94 state.listeners.clear();
95 state.resize.mockReset().mockResolvedValue(AsyncResult.success(undefined));
@@ -100,38 +97,26 @@ beforeEach(() => {
97 // A surface can report its initial grid while asynchronous WASM setup is
98 // pending. Keep that unrelated setup pending while exercising its callback.
99 state.createSurface.mockReset().mockReturnValue(new Promise(() => undefined));
103 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
104 - container = document.createElement("div");
105 - document.body.append(container);
106 - root = createRoot(container);
107 -});
108 -
109 -afterEach(async () => {
110 - await act(async () => root.unmount());
111 - container.remove();
112 - vi.unstubAllGlobals();
113 - vi.restoreAllMocks();
114 -});
100 +}
101
102 it("rechecks the target terminal grant when a retained surface callback reports a resize", async () => {
117 - await act(async () =>
118 - root.render(
119 - <TerminalViewport
120 - advancedTypography={false}
121 - threadRef={threadRef}
122 - threadId={threadRef.threadId}
123 - terminalId="terminal-1"
124 - terminalLabel="Terminal 1"
125 - cwd="/repo"
126 - onSessionExited={state.otherCommand}
127 - focusRequestId={0}
128 - autoFocus={false}
129 - visible={true}
130 - resizeEpoch={0}
131 - drawerHeight={200}
132 - keybindings={[]}
133 - />,
134 - ),
103 + setup();
104 + await using _screen = await render(
105 + <TerminalViewport
106 + advancedTypography={false}
107 + threadRef={threadRef}
108 + threadId={threadRef.threadId}
109 + terminalId="terminal-1"
110 + terminalLabel="Terminal 1"
111 + cwd="/repo"
112 + onSessionExited={state.otherCommand}
113 + focusRequestId={0}
114 + autoFocus={false}
115 + visible={true}
116 + resizeEpoch={0}
117 + drawerHeight={200}
118 + keybindings={[]}
119 + />,
120 );
121 expect(state.createSurface).toHaveBeenCalledOnce();
122 const onResize = state.createSurface.mock.calls[0]![1].onResize;
@@ -157,6 +142,7 @@ it("rechecks the target terminal grant when a retained surface callback reports
142 });
143
144 it("keeps held Kitty keys and the original surface through split, focus, and unsplit", async () => {
145 + setup();
146 const { GhosttyTerminalSurface } = await vi.importActual<
147 typeof import("~/terminal/ghostty/surface")
148 >("~/terminal/ghostty/surface");
@@ -180,78 +166,79 @@ it("keeps held Kitty keys and the original surface through split, focus, and uns
166 };
167 // ChatView installs its capture listener before the terminal mounts.
168 window.addEventListener("keydown", consumeShortcut, { capture: true });
169 + using _shortcut = {
170 + [Symbol.dispose]: () =>
171 + window.removeEventListener("keydown", consumeShortcut, { capture: true }),
172 + };
173 const composer = document.createElement("textarea");
174 document.body.append(composer);
185 - const render = async (terminalIds: string[]) => {
186 - await act(async () =>
187 - root.render(
188 - <ThreadTerminalDrawer
189 - threadRef={threadRef}
190 - threadId={threadRef.threadId}
191 - cwd="/repo"
192 - height={280}
193 - terminalIds={terminalIds}
194 - activeTerminalId="original"
195 - terminalGroups={[{ id: "group", terminalIds }]}
196 - activeTerminalGroupId="group"
197 - focusRequestId={0}
198 - onSplitTerminal={state.otherCommand}
199 - onSplitTerminalVertical={state.otherCommand}
200 - onNewTerminal={state.otherCommand}
201 - onActiveTerminalChange={state.otherCommand}
202 - onCloseTerminal={state.otherCommand}
203 - onHeightChange={state.otherCommand}
204 - onAddTerminalContext={state.otherCommand}
205 - keybindings={[]}
206 - />,
207 - ),
208 - );
209 - await act(async () => {
175 + using _composer = { [Symbol.dispose]: () => composer.remove() };
176 + const drawer = (terminalIds: string[]) => (
177 + <ThreadTerminalDrawer
178 + threadRef={threadRef}
179 + threadId={threadRef.threadId}
180 + cwd="/repo"
181 + height={280}
182 + terminalIds={terminalIds}
183 + activeTerminalId="original"
184 + terminalGroups={[{ id: "group", terminalIds }]}
185 + activeTerminalGroupId="group"
186 + focusRequestId={0}
187 + onSplitTerminal={state.otherCommand}
188 + onSplitTerminalVertical={state.otherCommand}
189 + onNewTerminal={state.otherCommand}
190 + onActiveTerminalChange={state.otherCommand}
191 + onCloseTerminal={state.otherCommand}
192 + onHeightChange={state.otherCommand}
193 + onAddTerminalContext={state.otherCommand}
194 + keybindings={[]}
195 + />
196 + );
197 + const surfacesCreated = () =>
198 + act(async () => {
199 await Promise.all(state.createSurface.mock.results.map((result) => result.value));
200 });
212 - };
213 - try {
214 - await render(["original"]);
215 - const original = await state.createSurface.mock.results[0]!.value;
216 - const disposeOriginal = vi.spyOn(original, "dispose");
217 - original.write("\x1b[>11u");
218 - const key = (type: "keydown" | "keyup", init: KeyboardEventInit) =>
219 - original.input.dispatchEvent(
220 - new KeyboardEvent(type, { bubbles: true, cancelable: true, ...init }),
221 - );
222 - original.focus();
223 - key("keydown", { key: "Control", code: "ControlLeft", ctrlKey: true });
224 - key("keydown", { key: "d", code: "KeyD", ctrlKey: true });
225 - await render(["original", "split"]);
226 - expect(state.createSurface).toHaveBeenCalledTimes(2);
227 - expect(container.querySelector("textarea")).toBe(original.input);
228 - expect(disposeOriginal).not.toHaveBeenCalled();
229 - const split = await state.createSurface.mock.results[1]!.value;
230 - const disposeSplit = vi.spyOn(split, "dispose");
231 - original.focus();
232 - key("keyup", { key: "d", code: "KeyD", ctrlKey: true });
233 - key("keyup", { key: "Control", code: "ControlLeft" });
201 + await using screen = await render(drawer(["original"]));
202 + const { container } = screen;
203 + await surfacesCreated();
204 + const original = await state.createSurface.mock.results[0]!.value;
205 + const disposeOriginal = vi.spyOn(original, "dispose");
206 + original.write("\x1b[>11u");
207 + const key = (type: "keydown" | "keyup", init: KeyboardEventInit) =>
208 + original.input.dispatchEvent(
209 + new KeyboardEvent(type, { bubbles: true, cancelable: true, ...init }),
210 + );
211 + original.focus();
212 + key("keydown", { key: "Control", code: "ControlLeft", ctrlKey: true });
213 + key("keydown", { key: "d", code: "KeyD", ctrlKey: true });
214 + await screen.rerender(drawer(["original", "split"]));
215 + await surfacesCreated();
216 + expect(state.createSurface).toHaveBeenCalledTimes(2);
217 + expect(container.querySelector("textarea")).toBe(original.input);
218 + expect(disposeOriginal).not.toHaveBeenCalled();
219 + const split = await state.createSurface.mock.results[1]!.value;
220 + const disposeSplit = vi.spyOn(split, "dispose");
221 + original.focus();
222 + key("keyup", { key: "d", code: "KeyD", ctrlKey: true });
223 + key("keyup", { key: "Control", code: "ControlLeft" });
224
235 - key("keydown", { key: "b", code: "KeyB" });
236 - composer.focus();
237 - original.focus();
238 - key("keydown", { key: "b", code: "KeyB", repeat: true });
239 - key("keyup", { key: "b", code: "KeyB" });
225 + key("keydown", { key: "b", code: "KeyB" });
226 + composer.focus();
227 + original.focus();
228 + key("keydown", { key: "b", code: "KeyB", repeat: true });
229 + key("keyup", { key: "b", code: "KeyB" });
230
241 - key("keydown", { key: "c", code: "KeyC" });
242 - await render(["original"]);
243 - expect(state.createSurface).toHaveBeenCalledTimes(2);
244 - expect(container.querySelector("textarea")).toBe(original.input);
245 - expect(disposeOriginal).not.toHaveBeenCalled();
246 - expect(disposeSplit).toHaveBeenCalledOnce();
247 - original.focus();
248 - key("keyup", { key: "c", code: "KeyC" });
249 - expect(output).toEqual([
250 - ["\x1b[57442;5u", "\x1b[57442;1:3u", "\x1b[98u", "\x1b[98;1:3u", "\x1b[99u", "\x1b[99;1:3u"],
251 - [],
252 - ]);
253 - } finally {
254 - window.removeEventListener("keydown", consumeShortcut, { capture: true });
255 - composer.remove();
256 - }
231 + key("keydown", { key: "c", code: "KeyC" });
232 + await screen.rerender(drawer(["original"]));
233 + await surfacesCreated();
234 + expect(state.createSurface).toHaveBeenCalledTimes(2);
235 + expect(container.querySelector("textarea")).toBe(original.input);
236 + expect(disposeOriginal).not.toHaveBeenCalled();
237 + expect(disposeSplit).toHaveBeenCalledOnce();
238 + original.focus();
239 + key("keyup", { key: "c", code: "KeyC" });
240 + expect(output).toEqual([
241 + ["\x1b[57442;5u", "\x1b[57442;1:3u", "\x1b[98u", "\x1b[98;1:3u", "\x1b[99u", "\x1b[99;1:3u"],
242 + [],
243 + ]);
244 });
apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx
+29 -34
@@ -4,11 +4,11 @@ import {
4 MessageId,
5 ThreadId,
6 } from "@t3tools/contracts";
7 -import { act, useState, type ReactNode } from "react";
8 -import { createRoot, type Root } from "react-dom/client";
9 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
7 +import { useState, type ReactNode } from "react";
8 +import { describe, expect, it, vi } from "vite-plus/test";
9
10 import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
11 +import { act, render } from "../../../test/render";
12
13 const mocks = vi.hoisted(() => ({ observeSource: vi.fn(), dispose: vi.fn() }));
14 vi.mock(import("./AssistantCitationSource"), async (importOriginal) => ({
@@ -35,11 +35,20 @@ const citation = {
35 suffix: "",
36 };
37
38 -let root: Root;
39 -let container: HTMLDivElement;
40 -let sourceAnchor: AssistantCitationSourceAnchor;
38 +// The mocked source observer is shared, so every test starts by resetting it.
39 +function setup() {
40 + mocks.observeSource.mockReset().mockReturnValue(mocks.dispose);
41 + mocks.dispose.mockClear();
42 + const source = document.createElement("p");
43 + source.textContent = "hello";
44 + document.body.append(source);
45 + const range = document.createRange();
46 + range.selectNodeContents(source);
47 + const sourceAnchor = { source, range, viewport: document.body } as AssistantCitationSourceAnchor;
48 + return { sourceAnchor, [Symbol.dispose]: () => source.remove() };
49 +}
50
42 -async function mount(onSave = vi.fn(() => true)) {
51 +function mount(sourceAnchor: AssistantCitationSourceAnchor, onSave: () => boolean) {
52 function Composer() {
53 const [open, setOpen] = useState(true);
54 return (
@@ -50,8 +59,7 @@ async function mount(onSave = vi.fn(() => true)) {
59 />
60 );
61 }
53 - await act(async () => root.render(<Composer />));
54 - return onSave;
62 + return render(<Composer />);
63 }
64
65 const textarea = () =>
@@ -81,30 +89,11 @@ async function clickButton(label: string) {
89 await act(async () => button!.click());
90 }
91
84 -beforeEach(() => {
85 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
86 - mocks.observeSource.mockReset().mockReturnValue(mocks.dispose);
87 - mocks.dispose.mockClear();
88 - const source = document.createElement("p");
89 - source.textContent = "hello";
90 - document.body.append(source);
91 - const range = document.createRange();
92 - range.selectNodeContents(source);
93 - sourceAnchor = { source, range, viewport: document.body } as AssistantCitationSourceAnchor;
94 - container = document.createElement("div");
95 - document.body.append(container);
96 - root = createRoot(container);
97 -});
98 -
99 -afterEach(async () => {
100 - await act(async () => root.unmount());
101 - document.body.replaceChildren();
102 - vi.unstubAllGlobals();
103 -});
104 -
92 describe("citation comment source disappearance", () => {
93 it("preserves an over-length draft at the composer until it can be shortened and saved", async () => {
107 - const onSave = await mount();
94 + using source = setup();
95 + const onSave = vi.fn(() => true);
96 + await using _screen = await mount(source.sourceAnchor, onSave);
97 const draft = "x".repeat(ASSISTANT_CITATION_MAX_COMMENT_LENGTH + 1);
98 await typeComment(draft);
99 await removeSource();
@@ -122,7 +111,9 @@ describe("citation comment source disappearance", () => {
111 });
112
113 it("preserves a rejected save and allows a later retry", async () => {
125 - const onSave = await mount(vi.fn(() => false));
114 + using source = setup();
115 + const onSave = vi.fn(() => false);
116 + await using _screen = await mount(source.sourceAnchor, onSave);
117 await typeComment("keep this draft");
118 await removeSource();
119
@@ -135,7 +126,9 @@ describe("citation comment source disappearance", () => {
126 });
127
128 it("still allows explicit cancellation after source disappearance", async () => {
138 - const onSave = await mount(vi.fn(() => false));
129 + using source = setup();
130 + const onSave = vi.fn(() => false);
131 + await using _screen = await mount(source.sourceAnchor, onSave);
132 await typeComment("discard this draft");
133 await removeSource();
134 onSave.mockClear();
@@ -145,7 +138,9 @@ describe("citation comment source disappearance", () => {
138 });
139
140 it("saves and closes when the source disappears with a valid draft", async () => {
148 - const onSave = await mount();
141 + using source = setup();
142 + const onSave = vi.fn(() => true);
143 + await using _screen = await mount(source.sourceAnchor, onSave);
144 await typeComment("saved comment");
145 await removeSource();
146 expect(onSave).toHaveBeenCalledWith("saved comment");
apps/web/src/components/chat/ChangedFilesTree.browser.test.tsx
+70 -81
@@ -2,40 +2,20 @@ import "~/index.css";
2
3 import { RunId } from "@t3tools/contracts";
4 import { LegendList } from "@legendapp/list/react";
5 -import { act, type ReactNode, useState } from "react";
6 -import { createRoot, type Root } from "react-dom/client";
7 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5 +import { useState } from "react";
6 +import { describe, expect, it, vi } from "vite-plus/test";
7
8 +import { act, render } from "../../../test/render";
9 import type { TurnDiffFileChange } from "../../types";
10 import { ChangedFilesCard, ChangedFilesTree } from "./ChangedFilesTree";
11
12 -let root: Root;
13 -let container: HTMLDivElement;
14 -
15 -beforeEach(() => {
16 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
17 - container = document.createElement("div");
18 - document.body.append(container);
19 - root = createRoot(container);
20 -});
21 -
22 -afterEach(async () => {
23 - await act(async () => root.unmount());
24 - container.remove();
25 - vi.unstubAllGlobals();
26 -});
27 -
28 -async function render(node: ReactNode) {
29 - await act(async () => root.render(node));
30 -}
31 -
12 function file(path: string, additions = 1, deletions = 0): TurnDiffFileChange {
13 return { path, kind: "modified", additions, deletions };
14 }
15
36 -const text = () => container.textContent ?? "";
16 +const text = (container: HTMLElement) => container.textContent ?? "";
17
38 -function buttonWithText(label: string) {
18 +function buttonWithText(container: HTMLElement, label: string) {
19 const button = [...container.querySelectorAll("button")].find((element) =>
20 element.textContent?.includes(label),
21 );
@@ -53,7 +33,7 @@ async function scrollTo(element: HTMLElement, top: number) {
33
34 describe("ChangedFilesCard", () => {
35 it("summarizes a single file with a singular label", async () => {
56 - await render(
36 + await using screen = await render(
37 <ChangedFilesCard
38 runId={RunId.make("run-1")}
39 files={[file("README.md", 2, 1)]}
@@ -63,14 +43,15 @@ describe("ChangedFilesCard", () => {
43 onOpenTurnDiff={() => {}}
44 />,
45 );
46 + const { container } = screen;
47
67 - expect(text()).toContain("1 changed file");
68 - expect(text()).not.toContain("1 changed files");
48 + expect(text(container)).toContain("1 changed file");
49 + expect(text(container)).not.toContain("1 changed files");
50 });
51
52 it("shows collapsed folders and root files together, and opens a folder on click", async () => {
53 const onOpenTurnDiff = vi.fn();
73 - await render(
54 + await using screen = await render(
55 <ChangedFilesCard
56 runId={RunId.make("run-1")}
57 files={[
@@ -85,19 +66,20 @@ describe("ChangedFilesCard", () => {
66 onOpenTurnDiff={onOpenTurnDiff}
67 />,
68 );
69 + const { container } = screen;
70
89 - expect(text()).toContain("apps/web/src");
90 - expect(text()).toContain("packages/shared/src");
91 - expect(text()).toContain("README.md");
92 - expect(text()).not.toContain("App.tsx");
93 - expect(text()).not.toContain("git.ts");
71 + expect(text(container)).toContain("apps/web/src");
72 + expect(text(container)).toContain("packages/shared/src");
73 + expect(text(container)).toContain("README.md");
74 + expect(text(container)).not.toContain("App.tsx");
75 + expect(text(container)).not.toContain("git.ts");
76
95 - await act(async () => buttonWithText("apps/web/src").click());
96 - expect(text()).toContain("App.tsx");
97 - expect(text()).toContain("App.test.tsx");
98 - expect(text()).not.toContain("git.ts");
77 + await act(async () => buttonWithText(container, "apps/web/src").click());
78 + expect(text(container)).toContain("App.tsx");
79 + expect(text(container)).toContain("App.test.tsx");
80 + expect(text(container)).not.toContain("git.ts");
81
100 - await act(async () => buttonWithText("App.test.tsx").click());
82 + await act(async () => buttonWithText(container, "App.test.tsx").click());
83 expect(onOpenTurnDiff).toHaveBeenCalledWith(RunId.make("run-1"), "apps/web/src/App.test.tsx");
84 });
85 });
@@ -108,7 +90,7 @@ describe("ChangedFilesTree", () => {
90 );
91
92 it("virtualizes above 250 visible rows and disables it when folders collapse below that count", async () => {
111 - await render(
93 + await using screen = await render(
94 <div style={{ height: 280, overflowY: "auto" }}>
95 <ChangedFilesTree
96 runId={RunId.make("run-1")}
@@ -119,21 +101,22 @@ describe("ChangedFilesTree", () => {
101 />
102 </div>,
103 );
104 + const { container } = screen;
105 expect(container.querySelectorAll("button").length).toBe(2);
106
124 - await act(async () => buttonWithText("src").click());
107 + await act(async () => buttonWithText(container, "src").click());
108 expect(container.querySelectorAll("button").length).toBe(250);
126 - expect(text()).toContain("file-00247.ts");
127 - expect(text()).not.toContain("overflow.ts");
109 + expect(text(container)).toContain("file-00247.ts");
110 + expect(text(container)).not.toContain("overflow.ts");
111
129 - await act(async () => buttonWithText("extra").click());
112 + await act(async () => buttonWithText(container, "extra").click());
113 expect(container.querySelectorAll("button").length).toBeLessThan(60);
131 - expect(text()).not.toContain("file-00247.ts");
114 + expect(text(container)).not.toContain("file-00247.ts");
115
133 - await act(async () => buttonWithText("extra").click());
116 + await act(async () => buttonWithText(container, "extra").click());
117 expect(container.querySelectorAll("button").length).toBe(250);
135 - expect(text()).toContain("file-00247.ts");
136 - expect(text()).not.toContain("overflow.ts");
118 + expect(text(container)).toContain("file-00247.ts");
119 + expect(text(container)).not.toContain("overflow.ts");
120 });
121
122 it("keeps 1,000 collapsed folders virtualized and reachable after scrolling", async () => {
@@ -151,21 +134,22 @@ describe("ChangedFilesTree", () => {
134 />
135 </div>
136 );
154 - await render(content(true));
137 + await using screen = await render(content(true));
138 + const { container } = screen;
139 expect(container.querySelectorAll("button").length).toBeLessThan(60);
140
157 - await render(content(false));
141 + await screen.rerender(content(false));
142 expect(container.querySelectorAll("button").length).toBeLessThan(60);
159 - expect(text()).toContain("folder-0000");
160 - expect(text()).not.toContain("index.ts");
161 - expect(text()).not.toContain("folder-0999");
143 + expect(text(container)).toContain("folder-0000");
144 + expect(text(container)).not.toContain("index.ts");
145 + expect(text(container)).not.toContain("folder-0999");
146
147 const viewport = container.firstElementChild as HTMLElement;
148 await scrollTo(viewport, viewport.scrollHeight);
165 - expect(text()).toContain("folder-0999");
149 + expect(text(container)).toContain("folder-0999");
150 expect(container.querySelectorAll("button").length).toBeLessThan(60);
167 - await act(async () => buttonWithText("folder-0999").click());
168 - expect(text()).toContain("index.ts");
151 + await act(async () => buttonWithText(container, "folder-0999").click());
152 + expect(text(container)).toContain("index.ts");
153 });
154
155 it("keeps expand-all bounded and opens files after scrolling the surrounding viewport", async () => {
@@ -185,12 +169,13 @@ describe("ChangedFilesTree", () => {
169 />
170 );
171 }
188 - await render(
172 + await using screen = await render(
173 <div style={{ height: 280, overflowY: "auto" }}>
174 <div style={{ height: 420 }} />
175 <Card />
176 </div>,
177 );
178 + const { container } = screen;
179 const viewport = container.firstElementChild as HTMLElement;
180 await scrollTo(viewport, 420);
181 const collapsedHeight = viewport.scrollHeight;
@@ -200,20 +185,20 @@ describe("ChangedFilesTree", () => {
185
186 expect(container.querySelectorAll("button").length).toBeLessThan(60);
187 expect(viewport.scrollHeight).toBeGreaterThan(collapsedHeight + 400_000);
203 - expect(text()).toContain("file-00000.ts");
204 - expect(text()).not.toContain("file-08000.ts");
188 + expect(text(container)).toContain("file-00000.ts");
189 + expect(text(container)).not.toContain("file-08000.ts");
190
191 await scrollTo(viewport, 420 + 8_001 * 28);
207 - expect(text()).toContain("file-08000.ts");
208 - expect(text()).not.toContain("file-00000.ts");
192 + expect(text(container)).toContain("file-08000.ts");
193 + expect(text(container)).not.toContain("file-00000.ts");
194 expect(container.querySelectorAll("button").length).toBeLessThan(60);
195
196 await scrollTo(viewport, viewport.scrollHeight);
212 - expect(text()).toContain("file-16184.ts");
213 - await act(async () => buttonWithText("file-16184.ts").click());
197 + expect(text(container)).toContain("file-16184.ts");
198 + await act(async () => buttonWithText(container, "file-16184.ts").click());
199 expect(onOpenTurnDiff).toHaveBeenCalledWith(RunId.make("run-1"), "src/file-16184.ts");
200 await act(async () =>
216 - buttonWithText("file-16184.ts").dispatchEvent(
201 + buttonWithText(container, "file-16184.ts").dispatchEvent(
202 new MouseEvent("contextmenu", { bubbles: true, cancelable: true }),
203 ),
204 );
@@ -223,11 +208,11 @@ describe("ChangedFilesTree", () => {
208 container.querySelector<HTMLButtonElement>('[aria-label="Collapse all folders"]')!.click(),
209 );
210 expect(viewport.scrollHeight).toBe(collapsedHeight);
226 - expect(text()).not.toContain("file-16184.ts");
211 + expect(text(container)).not.toContain("file-16184.ts");
212 });
213
214 it("virtualizes a single expanded folder inside a LegendList timeline item", async () => {
230 - await render(
215 + await using screen = await render(
216 <LegendList
217 data={["message", "files"]}
218 keyExtractor={(item) => item}
@@ -248,25 +233,26 @@ describe("ChangedFilesTree", () => {
233 }
234 />,
235 );
236 + const { container } = screen;
237 const viewport = container.firstElementChild as HTMLElement;
238 await scrollTo(viewport, 420);
253 - await act(async () => buttonWithText("src").click());
239 + await act(async () => buttonWithText(container, "src").click());
240 expect(container.querySelectorAll("button").length).toBeLessThan(60);
241
242 await scrollTo(viewport, 420 + 8_001 * 28);
257 - expect(text()).toContain("file-08000.ts");
243 + expect(text(container)).toContain("file-08000.ts");
244 expect(container.querySelectorAll("button").length).toBeLessThan(60);
245
246 await scrollTo(viewport, viewport.scrollHeight);
261 - expect(text()).toContain("file-16184.ts");
247 + expect(text(container)).toContain("file-16184.ts");
248 await scrollTo(viewport, 420);
263 - await act(async () => buttonWithText("src").click());
264 - expect(text()).not.toContain("file-00000.ts");
249 + await act(async () => buttonWithText(container, "src").click());
250 + expect(text(container)).not.toContain("file-00000.ts");
251 expect(container.querySelectorAll("button").length).toBe(1);
252 });
253
254 it("keeps a focused file mounted when scrolling it out of view", async () => {
269 - await render(
255 + await using screen = await render(
256 <div style={{ height: 280, overflowY: "auto" }}>
257 <ChangedFilesTree
258 runId={RunId.make("run-1")}
@@ -277,16 +263,17 @@ describe("ChangedFilesTree", () => {
263 />
264 </div>,
265 );
266 + const { container } = screen;
267 const viewport = container.firstElementChild as HTMLElement;
281 - const focusedFile = buttonWithText("file-00000.ts");
268 + const focusedFile = buttonWithText(container, "file-00000.ts");
269 await act(async () => focusedFile.focus());
270 await scrollTo(viewport, 8_001 * 28);
284 - expect(text()).toContain("file-08000.ts");
271 + expect(text(container)).toContain("file-08000.ts");
272 expect(document.activeElement).toBe(focusedFile);
273 expect(container.querySelectorAll("button").length).toBeLessThan(60);
274
275 await act(async () => focusedFile.blur());
289 - expect(text()).not.toContain("file-00000.ts");
276 + expect(text(container)).not.toContain("file-00000.ts");
277 });
278
279 it("remeasures the visible rows when the viewport or preceding content resizes", async () => {
@@ -304,15 +291,16 @@ describe("ChangedFilesTree", () => {
291 </div>
292 </div>
293 );
307 - await render(content(140, 0));
294 + await using screen = await render(content(140, 0));
295 + const { container } = screen;
296 const viewport = container.firstElementChild as HTMLElement;
297 await scrollTo(viewport, 8_001 * 28);
298 const beforeResize = container.querySelectorAll("button").length;
311 - await render(content(560, 560));
299 + await screen.rerender(content(560, 560));
300 await expect
301 .poll(() => container.querySelectorAll("button").length)
302 .toBeGreaterThan(beforeResize);
315 - expect(text()).toContain("file-07980.ts");
303 + expect(text(container)).toContain("file-07980.ts");
304 expect(container.querySelectorAll("button").length).toBeLessThan(60);
305 });
306
@@ -369,7 +357,8 @@ describe("ChangedFilesTree", () => {
357 onOpenTurnDiff={() => {}}
358 />
359 );
372 - await render(tree(false));
360 + await using screen = await render(tree(false));
361 + const { container } = screen;
362 const visibleWhenCollapsed = [...container.querySelectorAll("button")].map((button) =>
363 button.textContent?.trim(),
364 );
@@ -379,8 +368,8 @@ describe("ChangedFilesTree", () => {
368 );
369 }
370
382 - await render(tree(true));
383 - for (const label of expanded) expect(text()).toContain(label);
371 + await screen.rerender(tree(true));
372 + for (const label of expanded) expect(text(container)).toContain(label);
373 },
374 );
375 });
apps/web/src/components/chat/ChatCanvas.browser.test.tsx
+47 -53
@@ -1,6 +1,7 @@
1 -import { act, useLayoutEffect } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
1 +import { useLayoutEffect } from "react";
2 +import { expect, it, vi } from "vite-plus/test";
3 +
4 +import { act, render } from "../../../test/render";
5 import { ChatCanvas } from "./ChatCanvas";
6 import { useChatCanvas } from "./ChatCanvasContext";
7
@@ -12,8 +13,6 @@ vi.mock("../../lib/observeResize", () => ({
13 },
14 }));
15
15 -let root: Root;
16 -let container: HTMLDivElement;
16 let fontSize = 16;
17 let canvas: ReturnType<typeof useChatCanvas>;
18
@@ -35,76 +34,71 @@ function Preview({ x }: { x: number }) {
34 return null;
35 }
36
38 -beforeEach(() => {
39 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
37 +function mockLayout() {
38 + const stack = new DisposableStack();
39 fontSize = 16;
41 - vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(1800);
42 - vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(1000);
43 - vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (
44 - this: HTMLElement,
45 - ) {
46 - if (this.hasAttribute("data-thread-find-bar")) {
47 - const gap = 0.75 * fontSize;
48 - return new DOMRect(
49 - 200 + 1800 - gap - 17.5 * fontSize,
50 - 100 + gap,
51 - 17.5 * fontSize,
52 - 2.25 * fontSize,
53 - );
54 - }
55 - return new DOMRect(200, 100, 1800, 1000);
56 - });
57 - vi.spyOn(window, "getComputedStyle").mockReturnValue({
58 - paddingLeft: "48px",
59 - width: "736px",
60 - minWidth: "640px",
61 - } as CSSStyleDeclaration);
62 - container = document.createElement("div");
63 - document.body.append(container);
64 - root = createRoot(container);
65 -});
66 -
67 -afterEach(async () => {
68 - await act(() => root.unmount());
69 - container.remove();
70 - resize.callbacks.clear();
71 - vi.restoreAllMocks();
72 - vi.unstubAllGlobals();
73 -});
40 + stack.use(vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(1800));
41 + stack.use(vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(1000));
42 + stack.use(
43 + vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (
44 + this: HTMLElement,
45 + ) {
46 + if (this.hasAttribute("data-thread-find-bar")) {
47 + const gap = 0.75 * fontSize;
48 + return new DOMRect(
49 + 200 + 1800 - gap - 17.5 * fontSize,
50 + 100 + gap,
51 + 17.5 * fontSize,
52 + 2.25 * fontSize,
53 + );
54 + }
55 + return new DOMRect(200, 100, 1800, 1000);
56 + }),
57 + );
58 + stack.use(
59 + vi.spyOn(window, "getComputedStyle").mockReturnValue({
60 + paddingLeft: "48px",
61 + width: "736px",
62 + minWidth: "640px",
63 + } as CSSStyleDeclaration),
64 + );
65 + stack.defer(() => resize.callbacks.clear());
66 + return stack;
67 +}
68
75 -async function renderFind(open: boolean, previewX = 1548) {
76 - await act(() =>
77 - root.render(
78 - <ChatCanvas composerOverlayElement={null} detailsCardTopInset={open ? 48 : 0}>
79 - {open ? <div data-thread-find-bar /> : null}
80 - <Preview x={previewX} />
81 - </ChatCanvas>,
82 - ),
69 +function find(open: boolean, previewX = 1548) {
70 + return (
71 + <ChatCanvas composerOverlayElement={null} detailsCardTopInset={open ? 48 : 0}>
72 + {open ? <div data-thread-find-bar /> : null}
73 + <Preview x={previewX} />
74 + </ChatCanvas>
75 );
76 }
77
78 it.each([16, 24])(
79 "keeps a preview below Find and releases its space on close at a %spx root font",
80 async (size) => {
81 + using _layout = mockLayout();
82 fontSize = size;
90 - await renderFind(false);
83 + await using screen = await render(find(false));
84 expect(canvas?.layout.frame?.y).toBe(12);
85
93 - await renderFind(true);
86 + await screen.rerender(find(true));
87 expect(canvas?.detailsCardTopInset).toBe(3 * size);
88 expect(canvas?.layout.frame?.y).toBe(3 * size + 12);
89
97 - await renderFind(false);
90 + await screen.rerender(find(false));
91 expect(canvas?.detailsCardTopInset).toBe(0);
92 expect(canvas?.layout.frame?.y).toBe(12);
93
101 - await renderFind(true);
94 + await screen.rerender(find(true));
95 expect(canvas?.layout.frame?.y).toBe(3 * size + 12);
96 },
97 );
98
99 it("remeasures the open bar when its font size changes without resizing the canvas", async () => {
107 - await renderFind(true, 1200);
100 + using _layout = mockLayout();
101 + await using _screen = await render(find(true, 1200));
102 expect(canvas?.layout.frame?.y).toBe(12);
103
104 fontSize = 24;
apps/web/src/components/chat/ChatOverlayHosts.browser.test.tsx
+4 -21
@@ -1,27 +1,10 @@
1 import { MessageId } from "@t3tools/contracts";
2 -import { act } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3
4 import { AppAtomRegistryProvider } from "~/rpc/atomRegistry";
5 +import { act, render } from "../../../test/render";
6 import { openRevertConfirm, RevertConfirmHost } from "./ChatOverlayHosts";
7
9 -let root: Root;
10 -let container: HTMLDivElement;
11 -
12 -beforeEach(() => {
13 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
14 - container = document.createElement("div");
15 - document.body.append(container);
16 - root = createRoot(container);
17 -});
18 -
19 -afterEach(async () => {
20 - await act(() => root.unmount());
21 - container.remove();
22 - vi.unstubAllGlobals();
23 -});
24 -
8 const messageId = MessageId.make("message-1");
9 const dialog = () => document.querySelector('[role="alertdialog"]');
10
@@ -33,7 +16,7 @@ describe("RevertConfirmHost", () => {
16 <RevertConfirmHost threadKey={threadKey} onConfirm={onConfirm} />
17 </AppAtomRegistryProvider>
18 );
36 - await act(() => root.render(host("env:a")));
19 + await using screen = await render(host("env:a"));
20
21 await act(() => openRevertConfirm("env:b", { turnCount: 2, messageId }));
22 expect(dialog()).toBeNull();
@@ -48,7 +31,7 @@ describe("RevertConfirmHost", () => {
31
32 await act(() => openRevertConfirm("env:a", { turnCount: 3, messageId }));
33 expect(dialog()).not.toBeNull();
51 - await act(() => root.render(host("env:b")));
34 + await screen.rerender(host("env:b"));
35 await vi.waitFor(() => expect(dialog()).toBeNull());
36 });
37 });
apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx
+55 -72
@@ -1,57 +1,43 @@
1 import "../../index.css";
2
3 -import { act } from "react";
4 -import { createRoot, type Root } from "react-dom/client";
5 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
3 +import { expect, it } from "vite-plus/test";
4 import { page, userEvent } from "vite-plus/test/browser";
5
6 +import { act, render } from "../../../test/render";
7 import { ComposerBannerStack } from "./ComposerBannerStack";
8
10 -let root: Root;
11 -let container: HTMLDivElement;
12 -
13 -beforeEach(() => {
14 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
15 - container = document.createElement("div");
16 - document.body.append(container);
17 - root = createRoot(container);
18 -});
19 -
20 -afterEach(async () => {
21 - await act(async () => root.unmount());
22 - container.remove();
23 - vi.unstubAllGlobals();
24 -});
9 +function sized(width: number) {
10 + const container = document.createElement("div");
11 + container.style.width = `${width}px`;
12 + return container;
13 +}
14
15 const nextFrame = () =>
16 act(() => new Promise<void>((resolve) => requestAnimationFrame(() => setTimeout(resolve, 0))));
17
29 -async function render(width: number, description: string) {
30 - container.style.width = `${width}px`;
31 - await act(async () =>
32 - root.render(
33 - <ComposerBannerStack
34 - items={[{ id: "usage", variant: "info", icon: null, title: "Usage limits", description }]}
35 - />,
36 - ),
37 - );
38 - await nextFrame();
39 -}
40 -
41 -const hasDetails = () => container.querySelector('[aria-label="Show notice details"]') !== null;
18 +const usage = (description: string) => (
19 + <ComposerBannerStack
20 + items={[{ id: "usage", variant: "info", icon: null, title: "Usage limits", description }]}
21 + />
22 +);
23
24 it("only offers notice details when the description cannot fit", async () => {
44 - await render(700, "OpenCode");
25 + await using screen = await render(usage("OpenCode"), { container: sized(700) });
26 + const { container } = screen;
27 + const hasDetails = () => container.querySelector('[aria-label="Show notice details"]') !== null;
28 + await nextFrame();
29 expect(hasDetails()).toBe(false);
30
47 - await render(700, "OpenCode ".repeat(40));
31 + await screen.rerender(usage("OpenCode ".repeat(40)));
32 + await nextFrame();
33 expect(hasDetails()).toBe(true);
34
35 container.style.width = "4000px";
36 await nextFrame();
37 expect(hasDetails()).toBe(false);
38
54 - await render(4000, "OpenCode");
39 + await screen.rerender(usage("OpenCode"));
40 + await nextFrame();
41 expect(hasDetails()).toBe(false);
42
43 // A narrow composer hides the description entirely, so details are the only way to read it.
@@ -61,29 +47,28 @@ it("only offers notice details when the description cannot fit", async () => {
47 });
48
49 it("keeps only the usage limit attached while an active goal waits in the collapsible stack", async () => {
64 - await act(async () =>
65 - root.render(
66 - <ComposerBannerStack
67 - items={[
68 - {
69 - id: "goal",
70 - variant: "default",
71 - priority: "activity",
72 - icon: null,
73 - title: "Goal active",
74 - description: "Finish the banner fix",
75 - },
76 - {
77 - id: "limit",
78 - variant: "default",
79 - priority: "urgent",
80 - icon: null,
81 - title: "Usage limit reached",
82 - },
83 - ]}
84 - />,
85 - ),
50 + await using screen = await render(
51 + <ComposerBannerStack
52 + items={[
53 + {
54 + id: "goal",
55 + variant: "default",
56 + priority: "activity",
57 + icon: null,
58 + title: "Goal active",
59 + description: "Finish the banner fix",
60 + },
61 + {
62 + id: "limit",
63 + variant: "default",
64 + priority: "urgent",
65 + icon: null,
66 + title: "Usage limit reached",
67 + },
68 + ]}
69 + />,
70 );
71 + const { container } = screen;
72
73 const visibleBanners = () =>
74 Array.from(container.querySelectorAll('[data-slot="composer-banner"]')).filter((banner) =>
@@ -113,21 +98,19 @@ it("keeps only the usage limit attached while an active goal waits in the collap
98 it("reveals the full running command only while its title is clipped", async () => {
99 const command =
100 "Running: /usr/bin/zsh -lc 'sleep 600 > /tmp/t3-background-command-with-a-long-log-filename-for-truncation.log 2>&1'";
116 - container.style.width = "240px";
117 - await act(async () =>
118 - root.render(
119 - <ComposerBannerStack
120 - items={[
121 - {
122 - id: "background-work",
123 - variant: "default",
124 - priority: "activity",
125 - icon: null,
126 - title: command,
127 - },
128 - ]}
129 - />,
130 - ),
101 + await using screen = await render(
102 + <ComposerBannerStack
103 + items={[
104 + {
105 + id: "background-work",
106 + variant: "default",
107 + priority: "activity",
108 + icon: null,
109 + title: command,
110 + },
111 + ]}
112 + />,
113 + { container: sized(240) },
114 );
115
116 const details = page.getByRole("button", { name: "Show title details", exact: true });
@@ -137,7 +120,7 @@ it("reveals the full running command only while its title is clipped", async ()
120 await expect.element(popup).toBeVisible();
121 await expect.element(popup).toHaveTextContent(command);
122
140 - container.style.width = "4000px";
123 + screen.container.style.width = "4000px";
124 await expect.element(details).not.toBeInTheDocument();
125 await expect.element(popup).not.toBeInTheDocument();
126 });
apps/web/src/components/chat/ComposerPendingApprovalActions.browser.test.tsx
+25 -41
@@ -1,48 +1,30 @@
1 import { RuntimeRequestId, type ProviderApprovalOption } from "@t3tools/contracts";
2 -import { act } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3
4 +import { act, render } from "../../../test/render";
5 import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions";
6
8 -let root: Root;
9 -let container: HTMLDivElement;
10 -const onRespond = vi.fn(async () => undefined);
11 -
12 -beforeEach(() => {
13 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
14 - onRespond.mockClear();
15 - container = document.createElement("div");
16 - document.body.append(container);
17 - root = createRoot(container);
18 -});
19 -
20 -afterEach(async () => {
21 - await act(async () => root.unmount());
22 - document.body.replaceChildren();
23 - vi.unstubAllGlobals();
24 -});
25 -
26 -async function render(options?: ReadonlyArray<ProviderApprovalOption>) {
27 - await act(async () =>
28 - root.render(
29 - <ComposerPendingApprovalActions
30 - requestId={RuntimeRequestId.make("approval-1")}
31 - canRespond
32 - isResponding={false}
33 - options={options}
34 - onRespondToApproval={onRespond}
35 - />,
36 - ),
7 +function renderActions(
8 + onRespond: () => Promise<undefined>,
9 + options?: ReadonlyArray<ProviderApprovalOption>,
10 +) {
11 + return render(
12 + <ComposerPendingApprovalActions
13 + requestId={RuntimeRequestId.make("approval-1")}
14 + canRespond
15 + isResponding={false}
16 + options={options}
17 + onRespondToApproval={onRespond}
18 + />,
19 );
20 }
21
40 -const rowLabels = () =>
22 +const rowLabels = (container: HTMLElement) =>
23 [...container.querySelectorAll("button")]
24 .map((button) => button.textContent?.trim())
25 .filter(Boolean);
26
45 -async function openMore() {
27 +async function openMore(container: HTMLElement) {
28 await act(async () =>
29 container.querySelector<HTMLElement>('[aria-label="More approval options"]')!.click(),
30 );
@@ -51,10 +33,11 @@ async function openMore() {
33
34 describe("ComposerPendingApprovalActions", () => {
35 it("keeps the main decisions in the row and sends a secondary decision from the menu", async () => {
54 - await render();
55 - expect(rowLabels()).toEqual(["Decline", "Approve"]);
36 + const onRespond = vi.fn(async () => undefined);
37 + await using screen = await renderActions(onRespond);
38 + expect(rowLabels(screen.container)).toEqual(["Decline", "Approve"]);
39
57 - const items = await openMore();
40 + const items = await openMore(screen.container);
41 expect(items.map((item) => item.textContent?.trim())).toEqual([
42 "Cancel",
43 "Always allow this session",
@@ -64,18 +47,19 @@ describe("ComposerPendingApprovalActions", () => {
47 });
48
49 it("keeps provider labels, including secondary ones, where the user can find them", async () => {
67 - await render([
50 + const onRespond = vi.fn(async () => undefined);
51 + await using screen = await renderActions(onRespond, [
52 { decision: "decline", label: "Deny" },
53 { decision: "acceptAlways", label: "Always allow Safari" },
54 { decision: "accept", label: "Allow once" },
55 ]);
72 - expect(rowLabels()).toEqual(["Deny", "Allow once"]);
73 - expect((await openMore()).map((item) => item.textContent?.trim())).toEqual([
56 + expect(rowLabels(screen.container)).toEqual(["Deny", "Allow once"]);
57 + expect((await openMore(screen.container)).map((item) => item.textContent?.trim())).toEqual([
58 "Always allow Safari",
59 ]);
60
61 await act(async () =>
78 - [...container.querySelectorAll("button")]
62 + [...screen.container.querySelectorAll("button")]
63 .find((button) => button.textContent?.trim() === "Allow once")!
64 .click(),
65 );
apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx
+23 -40
@@ -6,9 +6,8 @@ import {
6 TurnItemId,
7 type OrchestrationV2ThreadProjection,
8 } from "@t3tools/contracts";
9 -import { act, useLayoutEffect, useRef, useState, type ComponentProps } from "react";
10 -import { createRoot, type Root } from "react-dom/client";
11 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
9 +import { useLayoutEffect, useRef, useState, type ComponentProps } from "react";
10 +import { expect, it, vi } from "vite-plus/test";
11
12 import {
13 togglePendingUserInputOptionSelection,
@@ -20,6 +19,7 @@ vi.mock(import("../ChatMarkdown"), async (importOriginal) => ({
19 default: (({ text }: { text: string }) => <p>{text}</p>) as never,
20 }));
21
22 +import { act, fakeTimers, render } from "../../../test/render";
23 import { makeThreadProjectionFixture } from "../../test-fixtures";
24 import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
25 import { usePendingThreadRequests } from "./usePendingThreadRequests";
@@ -75,22 +75,6 @@ function Questions({ initialIndex = 0 }: { initialIndex?: number }) {
75 );
76 }
77
78 -let root: Root;
79 -let container: HTMLDivElement;
80 -beforeEach(() => {
81 - vi.useFakeTimers();
82 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
83 - container = document.createElement("div");
84 - document.body.append(container);
85 - root = createRoot(container);
86 -});
87 -afterEach(async () => {
88 - await act(async () => root.unmount());
89 - container.remove();
90 - vi.unstubAllGlobals();
91 - vi.useRealTimers();
92 -});
93 -
78 function buttonWithText(text: string) {
79 const button = [...document.querySelectorAll("button")].find((element) =>
80 element.textContent?.includes(text),
@@ -108,11 +92,12 @@ async function navigate(label: string) {
92 }
93
94 function activeIndex() {
111 - return container.querySelector("output")!.textContent;
95 + return document.querySelector("output")!.textContent;
96 }
97
98 it("does not skip the next unanswered question after manual advance", async () => {
115 - await act(async () => root.render(<Questions />));
99 + using _timers = fakeTimers();
100 + await using _screen = await render(<Questions />);
101 await chooseOption();
102 await navigate("Next");
103 expect(activeIndex()).toBe("1");
@@ -125,7 +110,8 @@ it("does not skip the next unanswered question after manual advance", async () =
110 });
111
112 it("does not undo previous-question navigation with a stale timer", async () => {
128 - await act(async () => root.render(<Questions initialIndex={1} />));
113 + using _timers = fakeTimers();
114 + await using _screen = await render(<Questions initialIndex={1} />);
115 await chooseOption();
116 await navigate("Previous");
117 await act(async () => vi.advanceTimersByTime(200));
@@ -133,7 +119,8 @@ it("does not undo previous-question navigation with a stale timer", async () =>
119 });
120
121 it("still auto-advances once after the answer draft rerenders the same question", async () => {
136 - await act(async () => root.render(<Questions />));
122 + using _timers = fakeTimers();
123 + await using _screen = await render(<Questions />);
124 await chooseOption();
125 await act(async () => vi.advanceTimersByTime(200));
126 expect(activeIndex()).toBe("1");
@@ -211,19 +198,13 @@ function PendingRequestsProbe({
198 }
199
200 it("retains answers, selections and question position after leaving chat, including while the projection reloads", async () => {
201 + using _timers = fakeTimers();
202 const environmentId = EnvironmentId.make("remount-environment");
203 const projection = questionProjection(threadRef.threadId);
216 - const render = (loading = false) =>
217 - act(() =>
218 - root.render(
219 - <PendingRequestsProbe
220 - environmentId={environmentId}
221 - projection={projection}
222 - loading={loading}
223 - />,
224 - ),
225 - );
226 - await render();
204 + const probe = (loading = false) => (
205 + <PendingRequestsProbe environmentId={environmentId} projection={projection} loading={loading} />
206 + );
207 + await using screen = await render(probe());
208 await act(() =>
209 requests.onChangeActivePendingUserInputCustomAnswer("question-0", "Keep my text"),
210 );
@@ -240,18 +221,19 @@ it("retains answers, selections and question position after leaving chat, includ
221 expect(requests).toMatchObject(expected);
222
223 // New thread and Settings both unmount the chat that owns this hook.
243 - await act(() => root.render(null));
244 - await render();
224 + await screen.rerender(null);
225 + await screen.rerender(probe());
226 expect(requests).toMatchObject(expected);
227
247 - await act(() => root.render(null));
248 - await render(true);
228 + await screen.rerender(null);
229 + await screen.rerender(probe(true));
230 expect(requests.activePendingUserInput).toBeNull();
250 - await render();
231 + await screen.rerender(probe());
232 expect(requests).toMatchObject(expected);
233 });
234
235 it("isolates drafts by environment, thread and request and discards only resolved requests", async () => {
236 + using _timers = fakeTimers();
237 const environmentId = EnvironmentId.make("scope-environment");
238 const projection = questionProjection(threadRef.threadId);
239 const scopes = [
@@ -260,8 +242,9 @@ it("isolates drafts by environment, thread and request and discards only resolve
242 { environmentId, projection: questionProjection(ThreadId.make("other-thread")) },
243 { environmentId, projection: questionProjection(threadRef.threadId, ["second", "first"]) },
244 ];
245 + await using screen = await render(null);
246 const show = (scope: ComponentProps<typeof PendingRequestsProbe>) =>
264 - act(() => root.render(<PendingRequestsProbe {...scope} />));
247 + screen.rerender(<PendingRequestsProbe {...scope} />);
248 for (const [index, scope] of scopes.entries()) {
249 await show(scope);
250 expect(requests.activePendingQuestionIndex).toBe(0);
apps/web/src/components/chat/ComposerPendingUserInputPanel.permissions.browser.test.tsx
+21 -33
@@ -1,6 +1,4 @@
1 import { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
2 -import { act } from "react";
3 -import { createRoot } from "react-dom/client";
2 import { expect, it, vi } from "vite-plus/test";
3
4 vi.mock(import("../ChatMarkdown"), async (importOriginal) => ({
@@ -8,13 +6,13 @@ vi.mock(import("../ChatMarkdown"), async (importOriginal) => ({
6 default: (({ text }: { text: string }) => <p>{text}</p>) as never,
7 }));
8
9 +import { act, fakeTimers, render } from "../../../test/render";
10 import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
11
12 const threadRef = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") };
13
14 it("cancels an answer's pending auto-submit on revocation and resumes after a new grant", async () => {
16 - vi.useFakeTimers();
17 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
15 + using _timers = fakeTimers();
16 const onToggleOption = vi.fn();
17 const onAdvance = vi.fn();
18 const onDismiss = vi.fn();
@@ -47,39 +45,29 @@ it("cancels an answer's pending auto-submit on revocation and resumes after a ne
45 onDismiss={onDismiss}
46 />
47 );
50 - const container = document.createElement("div");
51 - document.body.append(container);
52 - const root = createRoot(container);
48 + await using screen = await render(panel(false));
49 // A disabled button swallows the click, as it would for a user.
50 const chooseOption = () =>
55 - [...container.querySelectorAll("button")]
51 + [...screen.container.querySelectorAll("button")]
52 .find((button) => button.textContent?.includes("Incremental"))!
53 .click();
58 - try {
59 - await act(async () => root.render(panel(false)));
60 - await act(async () => chooseOption());
61 - expect(onToggleOption).toHaveBeenCalledWith("approach", "Incremental");
62 - expect(onAdvance).not.toHaveBeenCalled();
54 + await act(async () => chooseOption());
55 + expect(onToggleOption).toHaveBeenCalledWith("approach", "Incremental");
56 + expect(onAdvance).not.toHaveBeenCalled();
57
64 - await act(async () => root.render(panel(true)));
65 - await act(async () => {
66 - chooseOption();
67 - vi.runAllTimers();
68 - });
69 - expect(onToggleOption).toHaveBeenCalledTimes(1);
70 - expect(onAdvance).not.toHaveBeenCalled();
58 + await screen.rerender(panel(true));
59 + await act(async () => {
60 + chooseOption();
61 + vi.runAllTimers();
62 + });
63 + expect(onToggleOption).toHaveBeenCalledTimes(1);
64 + expect(onAdvance).not.toHaveBeenCalled();
65
72 - await act(async () => root.render(panel(false)));
73 - await act(async () => {
74 - chooseOption();
75 - vi.runAllTimers();
76 - });
77 - expect(onToggleOption).toHaveBeenCalledTimes(2);
78 - expect(onAdvance).toHaveBeenCalledTimes(1);
79 - } finally {
80 - await act(async () => root.unmount());
81 - container.remove();
82 - vi.unstubAllGlobals();
83 - vi.useRealTimers();
84 - }
66 + await screen.rerender(panel(false));
67 + await act(async () => {
68 + chooseOption();
69 + vi.runAllTimers();
70 + });
71 + expect(onToggleOption).toHaveBeenCalledTimes(2);
72 + expect(onAdvance).toHaveBeenCalledTimes(1);
73 });
apps/web/src/components/chat/ComposerPrimaryActions.browser.test.tsx
+27 -45
@@ -1,7 +1,5 @@
1 import "~/index.css";
2
3 -import { act } from "react";
4 -import { createRoot } from "react-dom/client";
3 import { expect, it, vi } from "vite-plus/test";
4 import { page, userEvent } from "vite-plus/test/browser";
5
@@ -13,52 +11,36 @@ vi.mock("../SidebarStageBackdrop", () => ({
11 useSidebarStageBackdropVariant: () => null,
12 }));
13
14 +import { render } from "../../../test/render";
15 import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
16
17 it("opens implementation actions with a mouse while the composer is resting", async () => {
19 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
20 - const container = document.createElement("div");
21 - document.body.append(container);
22 - const root = createRoot(container);
18 const onImplementPlanInNewThread = vi.fn();
19 + await using _screen = await render(
20 + <ComposerPrimaryActions
21 + compact={false}
22 + canOperateThread
23 + pendingAction={null}
24 + isRunning={false}
25 + canInterrupt={false}
26 + showPlanFollowUpPrompt
27 + promptHasText={false}
28 + isSendBusy={false}
29 + sendDisabledReason={null}
30 + isConnecting={false}
31 + isEnvironmentUnavailable={false}
32 + isPreparingWorktree={false}
33 + hasSendableContent={false}
34 + preserveComposerFocusOnPointerDown
35 + onPreviousPendingQuestion={() => {}}
36 + onInterrupt={() => {}}
37 + onImplementPlanInNewThread={onImplementPlanInNewThread}
38 + />,
39 + );
40
25 - try {
26 - await act(async () => {
27 - root.render(
28 - <ComposerPrimaryActions
29 - compact={false}
30 - canOperateThread
31 - pendingAction={null}
32 - isRunning={false}
33 - canInterrupt={false}
34 - showPlanFollowUpPrompt
35 - promptHasText={false}
36 - isSendBusy={false}
37 - sendDisabledReason={null}
38 - isConnecting={false}
39 - isEnvironmentUnavailable={false}
40 - isPreparingWorktree={false}
41 - hasSendableContent={false}
42 - preserveComposerFocusOnPointerDown
43 - onPreviousPendingQuestion={() => {}}
44 - onInterrupt={() => {}}
45 - onImplementPlanInNewThread={onImplementPlanInNewThread}
46 - />,
47 - );
48 - });
49 -
50 - await act(async () => {
51 - await userEvent.click(page.getByRole("button", { name: "Implementation actions" }));
52 - });
53 - const item = page.getByRole("menuitem", { name: "Implement in a new thread" });
54 - await expect.element(item).toBeVisible();
55 - await act(async () => {
56 - await userEvent.click(item);
57 - });
58 - expect(onImplementPlanInNewThread).toHaveBeenCalledTimes(1);
59 - } finally {
60 - await act(async () => root.unmount());
61 - container.remove();
62 - vi.unstubAllGlobals();
63 - }
41 + await userEvent.click(page.getByRole("button", { name: "Implementation actions" }));
42 + const item = page.getByRole("menuitem", { name: "Implement in a new thread" });
43 + await expect.element(item).toBeVisible();
44 + await userEvent.click(item);
45 + expect(onImplementPlanInNewThread).toHaveBeenCalledTimes(1);
46 });
apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx
+5 -21
@@ -1,8 +1,8 @@
1 -import { act, useRef, useState } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
1 +import { useRef, useState } from "react";
2 +import { expect, it } from "vite-plus/test";
3 import { page, userEvent } from "vite-plus/test/browser";
4
5 +import { act, render } from "../../../test/render";
6 import { Dialog, DialogPopup } from "../ui/dialog";
7 import { ComposerStashMenu } from "./ComposerStashMenu";
8
@@ -62,22 +62,6 @@ function Composer({ dialog = false }: { dialog?: boolean }) {
62 );
63 }
64
65 -let root: Root;
66 -let container: HTMLDivElement;
67 -
68 -beforeEach(() => {
69 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
70 - container = document.createElement("div");
71 - document.body.append(container);
72 - root = createRoot(container);
73 -});
74 -
75 -afterEach(async () => {
76 - await act(async () => root.unmount());
77 - container.remove();
78 - vi.unstubAllGlobals();
79 -});
80 -
65 const editor = () => page.getByRole("textbox", { name: "Message" });
66 const stash = () => page.getByRole("list", { name: "Stashed prompts" });
67 const restore = (prompt: string) =>
@@ -86,7 +70,7 @@ const press = (keys: string) => act(async () => userEvent.keyboard(keys));
70 const focus = (element: Element) => act(async () => (element as HTMLElement).focus());
71
72 it("leaves dialog, unrelated input and question button shortcuts alone while the stash is open", async () => {
89 - await act(async () => root.render(<Composer dialog />));
73 + await using _screen = await render(<Composer dialog />);
74 const input = page.getByRole("textbox", { name: "Search commands" }).element();
75 await focus(input);
76
@@ -128,7 +112,7 @@ it("leaves dialog, unrelated input and question button shortcuts alone while the
112 });
113
114 it("navigates, deletes and restores stashed prompts from the composer and drawer", async () => {
131 - await act(async () => root.render(<Composer />));
115 + await using _screen = await render(<Composer />);
116 await focus(restore("first prompt").element());
117 await press("{ArrowDown}");
118 await expect.element(restore("second prompt")).toHaveFocus();
apps/web/src/components/chat/ComposerSurface.browser.test.tsx
+11 -25
@@ -1,33 +1,19 @@
1 import "~/index.css";
2
3 -import { act } from "react";
4 -import { createRoot } from "react-dom/client";
5 -import { expect, it, vi } from "vite-plus/test";
3 +import { expect, it } from "vite-plus/test";
4
5 +import { render } from "../../../test/render";
6 import { ComposerSurface } from "./ComposerSurface";
7
8 it("masks the toolbar overlap and reveals its surface one pixel before the input edge", async () => {
10 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
11 - const container = document.createElement("div");
12 - document.body.append(container);
13 - const root = createRoot(container);
9 + await using screen = await render(
10 + <ComposerSurface.Shell contextStrip>
11 + <ComposerSurface.Host>Message</ComposerSurface.Host>
12 + <ComposerSurface.ContextStrip>Workspace</ComposerSurface.ContextStrip>
13 + </ComposerSurface.Shell>,
14 + );
15
15 - try {
16 - await act(async () => {
17 - root.render(
18 - <ComposerSurface.Shell contextStrip>
19 - <ComposerSurface.Host>Message</ComposerSurface.Host>
20 - <ComposerSurface.ContextStrip>Workspace</ComposerSurface.ContextStrip>
21 - </ComposerSurface.Shell>,
22 - );
23 - });
24 -
25 - const strip = container.querySelector('[data-slot="composer-context-strip"]')!;
26 - const mask = getComputedStyle(strip, "::before").maskImage;
27 - expect(mask).toContain("rgba(0, 0, 0, 0) 15px, rgb(0, 0, 0) 15px");
28 - } finally {
29 - await act(async () => root.unmount());
30 - container.remove();
31 - vi.unstubAllGlobals();
32 - }
16 + const strip = screen.container.querySelector('[data-slot="composer-context-strip"]')!;
17 + const mask = getComputedStyle(strip, "::before").maskImage;
18 + expect(mask).toContain("rgba(0, 0, 0, 0) 15px, rgb(0, 0, 0) 15px");
19 });
apps/web/src/components/chat/DraftProjectName.browser.test.tsx
+70 -56
@@ -1,77 +1,81 @@
1 import "~/index.css";
2
3 -import { act } from "react";
4 -import { createRoot, type Root } from "react-dom/client";
5 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
3 +import { expect, it } from "vite-plus/test";
4 import { page } from "vite-plus/test/browser";
5
6 +import { act, render as renderUi } from "../../../test/render";
7 import { InlineButton } from "../ui/button";
8 import { DraftHeroProjectHeading } from "./DraftHeroProjectHeading";
9 import { DraftProjectName } from "./DraftProjectName";
10
12 -let root: Root;
13 -let host: HTMLDivElement;
14 -
15 -beforeEach(() => {
16 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
17 - host = document.body.appendChild(document.createElement("div"));
11 +async function setup() {
12 + await using stack = new AsyncDisposableStack();
13 + const screen = stack.use(await renderUi(null));
14 + const container = screen.container;
15 + const host = container;
16 host.style.width = "700px";
17 host.style.maxWidth = "100%";
20 - root = createRoot(host);
21 -});
22 -
23 -afterEach(async () => {
24 - await act(async () => root.unmount());
25 - host.remove();
26 - vi.unstubAllGlobals();
27 -});
28 -
29 -async function render(value: string, placement: "headline" | "row" = "headline") {
30 - await act(async () => {
31 - root.render(
32 - placement === "headline" ? (
33 - <div data-testid="composer" className="relative mt-64 h-32 w-full">
34 - <div className="absolute inset-x-0 bottom-full pb-4">
35 - <DraftHeroProjectHeading projectName={value}>
36 - <InlineButton tone="picker" className="min-w-0 max-w-full align-baseline">
37 - <DraftProjectName value={value} singleLine />
38 - </InlineButton>
39 - </DraftHeroProjectHeading>
18 + async function render(value: string, placement: "headline" | "row" = "headline") {
19 + await act(async () => {
20 + await screen.rerender(
21 + placement === "headline" ? (
22 + <div data-testid="composer" className="relative mt-64 h-32 w-full">
23 + <div className="absolute inset-x-0 bottom-full pb-4">
24 + <DraftHeroProjectHeading projectName={value}>
25 + <InlineButton tone="picker" className="min-w-0 max-w-full align-baseline">
26 + <DraftProjectName value={value} singleLine />
27 + </InlineButton>
28 + </DraftHeroProjectHeading>
29 + </div>
30 </div>
41 - </div>
42 - ) : (
43 - <div className="flex w-full items-center gap-2 text-sm font-medium">
44 - <span className="size-4 shrink-0" />
45 - <span className="min-w-0 flex-1">
46 - <DraftProjectName value={value} />
47 - </span>
48 - </div>
49 - ),
50 - );
51 - });
52 -}
31 + ) : (
32 + <div className="flex w-full items-center gap-2 text-sm font-medium">
33 + <span className="size-4 shrink-0" />
34 + <span className="min-w-0 flex-1">
35 + <DraftProjectName value={value} />
36 + </span>
37 + </div>
38 + ),
39 + );
40 + });
41 + }
42
54 -const label = () => host.querySelector<HTMLSpanElement>("span[aria-label]")!;
55 -const title = () => host.querySelector<HTMLSpanElement>("h1 > span")!;
43 + const label = () => host.querySelector<HTMLSpanElement>("span[aria-label]")!;
44 + const title = () => host.querySelector<HTMLSpanElement>("h1 > span")!;
45
57 -function expectWithinHost(element: Element) {
58 - const bounds = element.getBoundingClientRect();
59 - const hostBounds = host.getBoundingClientRect();
60 - expect(bounds.left).toBeGreaterThanOrEqual(hostBounds.left);
61 - expect(bounds.right).toBeLessThanOrEqual(hostBounds.right);
62 -}
46 + function expectWithinHost(element: Element) {
47 + const bounds = element.getBoundingClientRect();
48 + const hostBounds = host.getBoundingClientRect();
49 + expect(bounds.left).toBeGreaterThanOrEqual(hostBounds.left);
50 + expect(bounds.right).toBeLessThanOrEqual(hostBounds.right);
51 + }
52
64 -function expectAboveComposer() {
65 - const heading = host.querySelector("h1")!;
66 - const composer = host.querySelector('[data-testid="composer"]')!;
67 - expectWithinHost(heading);
68 - expectWithinHost(label());
69 - expect(heading.getBoundingClientRect().bottom).toBeLessThan(composer.getBoundingClientRect().top);
70 -}
53 + function expectAboveComposer() {
54 + const heading = host.querySelector("h1")!;
55 + const composer = host.querySelector('[data-testid="composer"]')!;
56 + expectWithinHost(heading);
57 + expectWithinHost(label());
58 + expect(heading.getBoundingClientRect().bottom).toBeLessThan(
59 + composer.getBoundingClientRect().top,
60 + );
61 + }
62
63 + const environment = stack.move();
64 + return {
65 + host,
66 + render,
67 + label,
68 + title,
69 + expectAboveComposer,
70 + expectWithinHost,
71 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
72 + };
73 +}
74 it.each([320, 390, 822])(
75 "places the full short project name below the title in smaller text at %ipx",
76 async (width) => {
77 + await using fixture = await setup();
78 + const { host, render, label, title, expectAboveComposer } = fixture;
79 await page.viewport(width, 800);
80 host.style.width = `${width - 32}px`;
81 for (const value of ["t3code", "obsidian-arr", "No project"]) {
@@ -92,6 +96,8 @@ it.each([320, 390, 822])(
96 );
97
98 it("uses the inline heading only when the viewport and chat lane both have room", async () => {
99 + await using fixture = await setup();
100 + const { host, render, label, title, expectAboveComposer } = fixture;
101 await page.viewport(1440, 900);
102 await render("obsidian-arr");
103 expect(title().innerText).toBe("What should we build in");
@@ -109,6 +115,8 @@ it("uses the inline heading only when the viewport and chat lane both have room"
115 it.each([390, 1440])(
116 "uses a single smaller row and truncates only its remaining overflow at %ipx",
117 async (width) => {
118 + await using fixture = await setup();
119 + const { host, render, label, title, expectAboveComposer } = fixture;
120 await page.viewport(width, 900);
121 host.style.width = `${Math.min(width - 32, 700)}px`;
122 const value = "ExampleCompany-CustomerPortal-Production-".repeat(5);
@@ -131,6 +139,8 @@ it.each([390, 1440])(
139 );
140
141 it("keeps short picker rows intact and bounds long rows at fractional zoom", async () => {
142 + await using fixture = await setup();
143 + const { host, render, label, expectWithinHost } = fixture;
144 await page.viewport(1280, 800);
145 host.style.width = "240px";
146 host.style.zoom = "1.31";
@@ -145,6 +155,8 @@ it("keeps short picker rows intact and bounds long rows at fractional zoom", asy
155 });
156
157 it("moves a name below the heading when it stops fitting and returns it inline when space recovers", async () => {
158 + await using fixture = await setup();
159 + const { host, render, label, title, expectAboveComposer } = fixture;
160 await page.viewport(1440, 900);
161 host.style.width = "900px";
162 const value = "CustomerPortal-Production";
@@ -169,6 +181,8 @@ it("moves a name below the heading when it stops fitting and returns it inline w
181 });
182
183 it("rechecks inline fit when the selected project changes", async () => {
184 + await using fixture = await setup();
185 + const { render, label, title, expectAboveComposer } = fixture;
186 await page.viewport(1440, 900);
187 await render("ExampleCompany-CustomerPortal-Production-Environment");
188 expect(title().innerText).toBe("What should we build?");
apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx
+6 -23
@@ -1,13 +1,9 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { describe, expect, it, vi } from "vite-plus/test";
2
3 import { AppAtomRegistryProvider } from "~/rpc/atomRegistry";
4 +import { act, render as renderUi } from "../../../test/render";
5 import { ExpandedImageDialogHost, openExpandedImagePreview } from "./ExpandedImageDialog";
6
8 -let root: Root;
9 -let container: HTMLDivElement;
10 -
7 const preview = {
8 images: [
9 { src: "data:image/gif;base64,R0lGODlhAQABAAAAACw=", name: "one.png" },
@@ -16,19 +12,6 @@ const preview = {
12 index: 0,
13 };
14
19 -beforeEach(() => {
20 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
21 - container = document.createElement("div");
22 - document.body.append(container);
23 - root = createRoot(container);
24 -});
25 -
26 -afterEach(async () => {
27 - await act(() => root.unmount());
28 - container.remove();
29 - vi.unstubAllGlobals();
30 -});
31 -
15 const host = (threadKey: string) => (
16 <AppAtomRegistryProvider>
17 <ExpandedImageDialogHost threadKey={threadKey} />
@@ -41,7 +24,8 @@ describe("ExpandedImageDialogHost", () => {
24 it("opens for its thread, steps with arrows, and closes on Escape with focus back on the opener", async () => {
25 const opener = document.createElement("button");
26 document.body.append(opener);
44 - await act(() => root.render(host("env:a")));
27 + using _opener = { [Symbol.dispose]: () => opener.remove() };
28 + await using _screen = await renderUi(host("env:a"));
29 opener.focus();
30
31 await act(() => openExpandedImagePreview("env:a", preview));
@@ -57,18 +41,17 @@ describe("ExpandedImageDialogHost", () => {
41 });
42 await vi.waitFor(() => expect(dialog()).toBeNull());
43 expect(document.activeElement).toBe(opener);
60 - opener.remove();
44 });
45
46 it("ignores another thread's preview and drops its own when the thread changes", async () => {
64 - await act(() => root.render(host("env:a")));
47 + await using screen = await renderUi(host("env:a"));
48 await act(() => openExpandedImagePreview("env:b", preview));
49 expect(dialog()).toBeNull();
50
51 await act(() => openExpandedImagePreview("env:a", preview));
52 expect(dialog()).not.toBeNull();
53
71 - await act(() => root.render(host("env:b")));
54 + await screen.rerender(host("env:b"));
55 await vi.waitFor(() => expect(dialog()).toBeNull());
56 });
57 });
apps/web/src/components/chat/HighlightedCodeLines.browser.test.tsx
+5 -12
@@ -1,16 +1,11 @@
1 import { getSharedHighlighter } from "@pierre/diffs";
2 import { toHtml } from "hast-util-to-html";
3 -import { act } from "react";
4 -import { createRoot } from "react-dom/client";
5 -import { afterEach, expect, it, vi } from "vite-plus/test";
3 +import { expect, it } from "vite-plus/test";
4
5 +import { render as renderUi } from "../../../test/render";
6 import { createIncrementalHighlightedDocument } from "../../lib/incrementalHighlighting";
7 import { HighlightedCodeLines } from "./HighlightedCodeLines";
8
10 -afterEach(() => {
11 - vi.unstubAllGlobals();
12 -});
13 -
9 // React writes inline styles through CSSOM, so normalize Shiki's style strings the same way.
10 function normalizedHtml(html: string) {
11 const host = document.createElement("div");
@@ -26,7 +21,6 @@ function normalizedHtml(html: string) {
21 }
22
23 it("streams Shiki HTML into the DOM, keeping finished lines mounted", async () => {
29 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
24 const highlighter = await getSharedHighlighter({
25 langs: ["typescript"],
26 themes: ["pierre-dark", "pierre-light"],
@@ -36,12 +30,12 @@ it("streams Shiki HTML into the DOM, keeping finished lines mounted", async () =
30 'const html = "<img src=x onerror=alert(1)>";\n\n/* multi\nline */\n\tconst x = 1;\n';
31 for (const theme of ["pierre-dark", "pierre-light"] as const) {
32 const highlight = createIncrementalHighlightedDocument(highlighter, "typescript", theme);
39 - const container = document.createElement("div");
40 - const root = createRoot(container);
33 + await using screen = await renderUi(null);
34 + const { container } = screen;
35 let firstLine: Element | null = null;
36 for (let end = 0; end <= code.length; end++) {
37 const tree = highlight(code.slice(0, end));
44 - await act(async () => root.render(<HighlightedCodeLines root={tree} />));
38 + await screen.rerender(<HighlightedCodeLines root={tree} />);
39 expect(normalizedHtml(container.innerHTML)).toBe(normalizedHtml(toHtml(tree)));
40 if (end > code.indexOf("\n")) {
41 firstLine ??= container.querySelector("code > .line");
@@ -49,6 +43,5 @@ it("streams Shiki HTML into the DOM, keeping finished lines mounted", async () =
43 }
44 }
45 expect(container.querySelector("img")).toBeNull();
52 - await act(async () => root.unmount());
46 }
47 });
apps/web/src/components/chat/HtmlRenderDialog.browser.test.tsx
+33 -40
@@ -1,6 +1,4 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
1 +import { expect, it, vi } from "vite-plus/test";
2 import { page, userEvent } from "vite-plus/test/browser";
3 import { htmlRenderTheme, HTML_RENDER_DEFAULT_FONTS } from "@t3tools/shared/htmlRender";
4 import { T3_CODE_DARK_THEME_COLORS } from "@t3tools/shared/themePalettes";
@@ -8,6 +6,7 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts";
6
7 import "~/index.css";
8
9 +import { act, render as renderUi } from "../../../test/render";
10 import { HtmlRenderDialog } from "./HtmlRenderDialog";
11 import { HtmlRenderFrame } from "./HtmlRenderFrame";
12
@@ -45,35 +44,22 @@ vi.mock(import("~/hooks/useHtmlRenderTheme"), async (original) => ({
44 htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark", HTML_RENDER_DEFAULT_FONTS),
45 }));
46
48 -let root: Root;
49 -let container: HTMLDivElement;
47 const onClose = vi.fn();
48
52 -beforeEach(async () => {
49 +function setup() {
50 refresh.mockReset();
51 cachedUrl.lifeMs = 60 * 60_000;
52 openLink.mockReset().mockResolvedValue(undefined);
53 openChangeRequestLink.mockReset().mockReturnValue(false);
54 showError.mockClear();
55 onClose.mockClear();
59 - container = document.createElement("div");
60 - document.body.append(container);
61 - root = createRoot(container);
62 - await act(() =>
63 - root.render(
64 - <HtmlRenderDialog
65 - src="https://environment.test/page.html"
66 - title="Diagram"
67 - onClose={onClose}
68 - />,
69 - ),
70 - );
71 -});
56 +}
57
73 -afterEach(async () => {
74 - await act(() => root.unmount());
75 - container.remove();
76 -});
58 +function renderDialog() {
59 + return renderUi(
60 + <HtmlRenderDialog src="https://environment.test/page.html" title="Diagram" onClose={onClose} />,
61 + );
62 +}
63
64 function button(label: string) {
65 return page.getByRole("button", { name: label, exact: true });
@@ -85,6 +71,8 @@ async function click(label: string) {
71 }
72
73 it("zooms the loaded page within bounds and resets without reloading it", async () => {
74 + setup();
75 + await using _screen = await renderDialog();
76 const frame = document.querySelector("iframe")!;
77 const src = frame.src;
78 for (let step = 0; step < 4; step += 1) await click("Zoom in");
@@ -101,6 +89,8 @@ it("zooms the loaded page within bounds and resets without reloading it", async
89 });
90
91 it("closes with the close button or Escape", async () => {
92 + setup();
93 + await using _screen = await renderDialog();
94 await click("Close");
95 expect(onClose).toHaveBeenCalledOnce();
96 onClose.mockClear();
@@ -109,23 +99,21 @@ it("closes with the close button or Escape", async () => {
99 });
100
101 async function renderInline() {
112 - // Async so a URL minted at mount lands inside act.
113 - await act(async () =>
114 - root.render(
115 - <HtmlRenderFrame
116 - environmentId={EnvironmentId.make("environment")}
117 - htmlRender={{ attachmentId: "html", title: "Diagram", height: 400 }}
118 - threadRef={{
119 - environmentId: EnvironmentId.make("environment"),
120 - threadId: ThreadId.make("thread"),
121 - }}
122 - />,
123 - ),
102 + return renderUi(
103 + <HtmlRenderFrame
104 + environmentId={EnvironmentId.make("environment")}
105 + htmlRender={{ attachmentId: "html", title: "Diagram", height: 400 }}
106 + threadRef={{
107 + environmentId: EnvironmentId.make("environment"),
108 + threadId: ThreadId.make("thread"),
109 + }}
110 + />,
111 );
112 }
113
114 it("offers only full screen and opens with the inline URL while keeping the inline page loaded", async () => {
128 - await renderInline();
115 + setup();
116 + await using _screen = await renderInline();
117 expect(document.querySelector('[aria-label="Open in panel"]')).toBeNull();
118 const inlineFrame = document.querySelector("iframe")!;
119 const originalSrc = inlineFrame.src;
@@ -148,12 +136,15 @@ it("offers only full screen and opens with the inline URL while keeping the inli
136 async function renderInlineNearExpiry() {
137 cachedUrl.lifeMs = 60_000;
138 refresh.mockResolvedValueOnce("https://environment.test/inline.html");
151 - await renderInline();
139 + await using stack = new AsyncDisposableStack();
140 + stack.use(await renderInline());
141 expect(refresh).toHaveBeenCalledOnce();
142 + return stack.move();
143 }
144
145 it("opens full screen with a fresh URL when the inline one is near expiry", async () => {
156 - await renderInlineNearExpiry();
146 + setup();
147 + await using _screen = await renderInlineNearExpiry();
148 refresh.mockResolvedValue("https://environment.test/renewed.html");
149 await click("Open full screen");
150 expect(refresh).toHaveBeenCalledTimes(2);
@@ -163,7 +154,8 @@ it("opens full screen with a fresh URL when the inline one is near expiry", asyn
154 });
155
156 it("routes links from the expanded page through its thread", async () => {
166 - await renderInline();
157 + setup();
158 + await using _screen = await renderInline();
159 openChangeRequestLink.mockReturnValue(true);
160 await click("Open full screen");
161 const frame = document.querySelector<HTMLIFrameElement>('[role="dialog"] iframe')!;
@@ -189,7 +181,8 @@ it("routes links from the expanded page through its thread", async () => {
181 it.each([null, new Error("Disconnected")])(
182 "reports an unavailable URL instead of opening a blank page: %s",
183 async (failure) => {
192 - await renderInlineNearExpiry();
184 + setup();
185 + await using _screen = await renderInlineNearExpiry();
186 if (failure === null) refresh.mockResolvedValue(null);
187 else refresh.mockRejectedValue(failure);
188 await click("Open full screen");
apps/web/src/components/chat/HtmlRenderFrame.browser.test.tsx
+14 -22
@@ -1,6 +1,4 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, expect, it, vi } from "vite-plus/test";
1 +import { expect, it, vi } from "vite-plus/test";
2 import { EnvironmentId } from "@t3tools/contracts";
3 import {
4 htmlRenderTheme,
@@ -11,6 +9,7 @@ import { T3_CODE_DARK_THEME_COLORS } from "@t3tools/shared/themePalettes";
9
10 import "~/index.css";
11
12 +import { render as renderUi } from "../../../test/render";
13 import { HtmlRenderFrame } from "./HtmlRenderFrame";
14
15 const page = vi.hoisted(() => ({ url: "" }));
@@ -29,33 +28,26 @@ vi.mock(import("~/hooks/useHtmlRenderTheme"), async (original) => ({
28 htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark", HTML_RENDER_DEFAULT_FONTS),
29 }));
30
32 -let root: Root | undefined;
33 -let container: HTMLDivElement | undefined;
34 -
35 -afterEach(async () => {
36 - await act(() => root?.unmount());
37 - container?.remove();
38 - URL.revokeObjectURL(page.url);
39 -});
31 +function setup() {
32 + page.url = "";
33 +}
34
35 it("grows past the agent's height to fit the page the client lays out", async () => {
36 + setup();
37 page.url = URL.createObjectURL(
38 new Blob([injectHtmlRenderBootstrap('<div style="height:2345px"></div>')], {
39 type: "text/html",
40 }),
41 );
47 - container = document.createElement("div");
48 - document.body.append(container);
49 - root = createRoot(container);
50 - await act(() =>
51 - root!.render(
52 - <HtmlRenderFrame
53 - environmentId={EnvironmentId.make("environment-1")}
54 - htmlRender={{ attachmentId: "html", title: "Tall page", height: 400 }}
55 - threadRef={undefined}
56 - />,
57 - ),
42 + using _url = { [Symbol.dispose]: () => URL.revokeObjectURL(page.url) };
43 + await using screen = await renderUi(
44 + <HtmlRenderFrame
45 + environmentId={EnvironmentId.make("environment-1")}
46 + htmlRender={{ attachmentId: "html", title: "Tall page", height: 400 }}
47 + threadRef={undefined}
48 + />,
49 );
50 + const { container } = screen;
51
52 const box = container.firstElementChild as HTMLElement;
53 await expect.poll(() => box.style.height).toBe("2345px");
apps/web/src/components/chat/McpAppFrame.browser.test.tsx
+71 -58
@@ -1,7 +1,5 @@
1 import { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
2 -import { act } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
2 +import { expect, it, vi } from "vite-plus/test";
3 import { page, userEvent } from "vite-plus/test/browser";
4
5 import "~/index.css";
@@ -75,55 +73,38 @@ vi.mock(import("../../hooks/useHtmlRenderTheme"), async (original) => ({
73 useHtmlRenderTheme: (() => ({ appearance: "light", variables: {} })) as never,
74 }));
75
76 +import { render as renderUi } from "../../../test/render";
77 import { McpAppFrame } from "./McpAppFrame";
78
80 -let root: Root | undefined;
81 -let skew = 0;
82 -let answers: string[] = [];
83 -let answered: (() => void) | undefined;
84 -const onProbe = (event: MessageEvent) => {
85 - const probe = (event.data as { readonly probe?: unknown } | null)?.probe;
86 - if (typeof probe !== "string") return;
87 - answers.push(probe);
88 - answered?.();
89 -};
90 -const nextAnswer = async (action: () => Promise<unknown>) => {
91 - const seen = answers.length;
92 - const answer = new Promise<string>((resolve) => {
93 - answered = () => {
94 - if (answers.length > seen) resolve(answers[seen]!);
95 - };
96 - });
97 - await action();
98 - return answer;
99 -};
100 -
101 -beforeEach(() => {
102 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
103 - answers = [];
104 - answered = undefined;
105 - skew = 0;
79 +function setup() {
80 + let skew = 0;
81 // Advance the host cooldown without manufacturing browser user activation.
82 const now = performance.now.bind(performance);
108 - vi.spyOn(performance, "now").mockImplementation(() => now() + skew);
83 + const clock = vi.spyOn(performance, "now").mockImplementation(() => now() + skew);
84 + const answers: string[] = [];
85 + let answered: (() => void) | undefined;
86 + const onProbe = (event: MessageEvent) => {
87 + const probe = (event.data as { readonly probe?: unknown } | null)?.probe;
88 + if (typeof probe !== "string") return;
89 + answers.push(probe);
90 + answered?.();
91 + };
92 window.addEventListener("message", onProbe);
110 -});
111 -afterEach(async () => {
112 - window.removeEventListener("message", onProbe);
113 - if (root !== undefined) await act(async () => root?.unmount());
114 - root = undefined;
115 - document.body.replaceChildren();
116 - vi.restoreAllMocks();
117 - vi.unstubAllGlobals();
118 -});
93 + const nextAnswer = async (action: () => Promise<unknown>) => {
94 + const seen = answers.length;
95 + const answer = new Promise<string>((resolve) => {
96 + answered = () => {
97 + if (answers.length > seen) resolve(answers[seen]!);
98 + };
99 + });
100 + await action();
101 + return answer;
102 + };
103
120 -const isFullscreen = () => document.querySelector("[data-mcp-app-fullscreen]") !== null;
104 + const isFullscreen = () => document.querySelector("[data-mcp-app-fullscreen]") !== null;
105
122 -const renderApp = async () => {
123 - const container = document.body.appendChild(document.createElement("div"));
124 - root = createRoot(container);
125 - await act(async () =>
126 - root?.render(
106 + const renderApp = async () => {
107 + return renderUi(
108 <McpAppFrame
109 environmentId={EnvironmentId.make("env")}
110 threadId={ThreadId.make("thread")}
@@ -133,25 +114,53 @@ const renderApp = async () => {
114 app={{ attachmentId: "app", server: "srv", tool: "show", resourceUri: "ui://srv/app" }}
115 onSendMessage={undefined}
116 />,
136 - ),
137 - );
138 -};
117 + );
118 + };
119
140 -const retry = () =>
141 - nextAnswer(async () => {
142 - document.querySelector("iframe")!.contentWindow!.postMessage("retry", "*");
143 - });
120 + const retry = () =>
121 + nextAnswer(async () => {
122 + document.querySelector("iframe")!.contentWindow!.postMessage("retry", "*");
123 + });
124 +
125 + return {
126 + renderApp,
127 + nextAnswer,
128 + retry,
129 + isFullscreen,
130 + advance: (ms: number) => {
131 + skew += ms;
132 + },
133 + [Symbol.dispose]() {
134 + window.removeEventListener("message", onProbe);
135 + clock.mockRestore();
136 + },
137 + };
138 +}
139
140 it("keeps load and idle retries inline even after the page-input cooldown", async () => {
146 - expect(await nextAnswer(renderApp)).toBe("load:inline");
147 - skew += 5_000;
141 + using fixture = setup();
142 + await using screens = new AsyncDisposableStack();
143 + const { renderApp, nextAnswer, retry, isFullscreen, advance } = fixture;
144 + expect(
145 + await nextAnswer(async () => {
146 + screens.use(await renderApp());
147 + }),
148 + ).toBe("load:inline");
149 + advance(5_000);
150 expect(await retry()).toBe("retry:inline");
151 expect(await retry()).toBe("retry:inline");
152 expect(isFullscreen()).toBe(false);
153 });
154
155 it("allows an app click immediately after loading on an idle page", async () => {
154 - expect(await nextAnswer(renderApp)).toBe("load:inline");
156 + using fixture = setup();
157 + await using screens = new AsyncDisposableStack();
158 + const { renderApp, nextAnswer, isFullscreen } = fixture;
159 + expect(
160 + await nextAnswer(async () => {
161 + screens.use(await renderApp());
162 + }),
163 + ).toBe("load:inline");
164 const appButton = page
165 .frameLocator(page.getByTitle("srv app"))
166 .getByRole("button", { name: "Open full screen" });
@@ -160,13 +169,17 @@ it("allows an app click immediately after loading on an idle page", async () =>
169 });
170
171 it("opens full screen only from a tap in the app, never from activation the page got elsewhere", async () => {
172 + using fixture = setup();
173 + await using screens = new AsyncDisposableStack();
174 + const { renderApp, nextAnswer, isFullscreen, advance } = fixture;
175 const appButton = page
176 .frameLocator(page.getByTitle("srv app"))
177 .getByRole("button", { name: "Open full screen" });
178 const elsewhere = document.body.appendChild(document.createElement("button"));
179 + using _elsewhere = { [Symbol.dispose]: () => elsewhere.remove() };
180 elsewhere.textContent = "Elsewhere";
181 const tapApp = async () => {
169 - skew += 5_000;
182 + advance(5_000);
183 expect(await nextAnswer(() => userEvent.click(appButton))).toBe("tap:fullscreen");
184 expect(isFullscreen()).toBe(true);
185 };
@@ -174,7 +187,7 @@ it("opens full screen only from a tap in the app, never from activation the page
187 // The click that opens a thread still activates the page as its app loads.
188 const load = nextAnswer(async () => {
189 await userEvent.click(elsewhere);
177 - await renderApp();
190 + screens.use(await renderApp());
191 });
192 expect(await load).toBe("load:inline");
193 expect(isFullscreen()).toBe(false);
@@ -184,7 +197,7 @@ it("opens full screen only from a tap in the app, never from activation the page
197 expect(await nextAnswer(() => userEvent.click(exit))).toBe("exit:inline");
198 expect(isFullscreen()).toBe(false);
199
187 - skew += 5_000;
200 + advance(5_000);
201 expect(await nextAnswer(() => userEvent.click(elsewhere))).toBe("blur:inline");
202 expect(isFullscreen()).toBe(false);
203
apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+329 -322
@@ -14,9 +14,8 @@ import {
14 decodeComposerContextFragment,
15 } from "@t3tools/shared/composerContextClipboard";
16 import type { LegendListRef } from "@legendapp/list/react";
17 -import { act, createRef, Profiler, useState, type ComponentProps, type ReactElement } from "react";
18 -import { createRoot, type Root } from "react-dom/client";
19 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
17 +import { createRef, Profiler, useState, type ComponentProps, type ReactElement } from "react";
18 +import { describe, expect, it, vi } from "vite-plus/test";
19 import { userEvent } from "vite-plus/test/browser";
20
21 import "~/index.css";
@@ -24,6 +23,7 @@ import "~/index.css";
23 import { serverEnvironment } from "../../state/server";
24 import { PullRequestLinkPreview } from "../pullRequest/PullRequestLinkPreview";
25 import { Tooltip, TooltipPopup, TooltipScrollDismissArea, TooltipTrigger } from "../ui/tooltip";
26 +import { act, render } from "../../../test/render";
27 import { MessagesTimeline, remarkThoughtPreview } from "./MessagesTimeline";
28 import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
29 import { readTimelinePosition } from "./timelineScrollAnchoring";
@@ -51,10 +51,7 @@ type Entry = TimelineProps["timelineEntries"][number];
51
52 // The timeline remembers scroll position and open disclosures per thread key,
53 // so every render gets a fresh thread.
54 -let threadCount = 0;
55 -
54 function baseProps(): Omit<TimelineProps, "timelineEntries"> {
57 - threadCount += 1;
55 return {
56 isWorking: false,
57 activeTurnInProgress: false,
@@ -62,7 +59,7 @@ function baseProps(): Omit<TimelineProps, "timelineEntries"> {
59 latestRun: null,
60 turnDiffSummaries: [],
61 runs: [],
65 - routeThreadKey: `environment-local:thread-${threadCount}`,
62 + routeThreadKey: `environment-local:thread-${Math.random().toString(36).slice(2)}`,
63 onOpenTurnDiff: () => {},
64 onOpenThread: () => {},
65 onForkFromRun: async () => {},
@@ -152,27 +149,24 @@ function longText(tail = "deep hidden detail only after expand") {
149 ).join("\n");
150 }
151
155 -const roots: Root[] = [];
156 -let container: HTMLDivElement;
157 -
158 -beforeEach(() => {
159 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
160 -});
161 -
162 -afterEach(async () => {
163 - for (const root of roots.splice(0)) await act(async () => root.unmount());
164 - window.getSelection()?.removeAllRanges();
165 - document.body.replaceChildren();
166 - vi.unstubAllGlobals();
167 -});
168 -
152 async function renderElement(element: ReactElement) {
170 - container = document.body.appendChild(document.createElement("div"));
153 + const container = document.createElement("div");
154 container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
172 - const root = createRoot(container);
173 - roots.push(root);
174 - await act(async () => root.render(element));
175 - return container;
155 + const screen = await render(element, { container });
156 + const buttons = (name: string | RegExp) =>
157 + [...container.querySelectorAll<HTMLElement>("button, [role=button]")].filter((button) => {
158 + const label = button.getAttribute("aria-label") ?? button.textContent ?? "";
159 + return typeof name === "string" ? label === name : name.test(label);
160 + });
161 + return Object.assign(screen, {
162 + text: () => container.textContent ?? "",
163 + buttons,
164 + button: (name: string | RegExp) => {
165 + const [match] = buttons(name);
166 + if (!match) throw new Error(`Missing button: ${String(name)}`);
167 + return match;
168 + },
169 + });
170 }
171
172 function renderTimeline(entries: ReadonlyArray<Entry>, props: Partial<TimelineProps> = {}) {
@@ -197,23 +191,6 @@ async function copyRange(range: Range) {
191 }
192 }
193
200 -function text() {
201 - return container.textContent ?? "";
202 -}
203 -
204 -function buttons(name: string | RegExp) {
205 - return [...container.querySelectorAll<HTMLElement>("button, [role=button]")].filter((button) => {
206 - const label = button.getAttribute("aria-label") ?? button.textContent ?? "";
207 - return typeof name === "string" ? label === name : name.test(label);
208 - });
209 -}
210 -
211 -function button(name: string | RegExp) {
212 - const [match] = buttons(name);
213 - if (!match) throw new Error(`Missing button: ${String(name)}`);
214 - return match;
215 -}
216 -
194 async function click(element: HTMLElement) {
195 await act(async () => element.click());
196 }
@@ -224,7 +201,7 @@ describe("MessagesTimeline work rows", () => {
201 ["Space", " "],
202 ])("opens a nested diff with %s without collapsing the tool row", async (_name, key) => {
203 const onOpenTurnDiff = vi.fn();
227 - await renderTimeline(
204 + await using screen = await renderTimeline(
205 [
206 work("file-change-1", {
207 label: "Updated src/index.ts",
@@ -236,7 +213,7 @@ describe("MessagesTimeline work rows", () => {
213 ],
214 { onOpenTurnDiff },
215 );
239 - const row = container.querySelector<HTMLElement>('[data-v2-item-type="file_change"]')!;
216 + const row = screen.container.querySelector<HTMLElement>('[data-v2-item-type="file_change"]')!;
217 const press = async (target: HTMLElement) => {
218 await act(async () => {
219 target.focus();
@@ -246,7 +223,7 @@ describe("MessagesTimeline work rows", () => {
223 expect(row.getAttribute("aria-expanded")).toBe("false");
224 await press(row);
225 expect(row.getAttribute("aria-expanded")).toBe("true");
249 - const openDiff = button("Open diff");
226 + const openDiff = screen.button("Open diff");
227 await press(openDiff);
228 expect(onOpenTurnDiff).toHaveBeenCalledWith("run-1", "src/index.ts");
229 expect(onOpenTurnDiff).toHaveBeenCalledTimes(1);
@@ -256,7 +233,7 @@ describe("MessagesTimeline work rows", () => {
233 });
234
235 it("shows dynamic tool input without cached output when the row is expanded", async () => {
259 - await renderTimeline([
236 + await using screen = await renderTimeline([
237 work("tool-with-cached-output", {
238 label: "Example tool",
239 toolTitle: "Example tool",
@@ -269,15 +246,15 @@ describe("MessagesTimeline work rows", () => {
246 },
247 }),
248 ]);
272 - await click(button("Example tool"));
273 - expect(text()).toContain("KEEP_TOOL_INPUT");
274 - expect(text()).not.toContain("RAW_CACHED_TOOL_OUTPUT");
275 - await click(button("Example tool"));
276 - await vi.waitFor(() => expect(text()).not.toContain("KEEP_TOOL_INPUT"));
249 + await click(screen.button("Example tool"));
250 + expect(screen.text()).toContain("KEEP_TOOL_INPUT");
251 + expect(screen.text()).not.toContain("RAW_CACHED_TOOL_OUTPUT");
252 + await click(screen.button("Example tool"));
253 + await vi.waitFor(() => expect(screen.text()).not.toContain("KEEP_TOOL_INPUT"));
254 });
255
256 it("expands and collapses a tool call through its header", async () => {
280 - await renderTimeline([
257 + await using screen = await renderTimeline([
258 work("work-standalone", {
259 toolCallId: "call-standalone",
260 label: "Run lint",
@@ -287,7 +264,7 @@ describe("MessagesTimeline work rows", () => {
264 toolLifecycleStatus: "completed",
265 }),
266 ]);
290 - const header = () => container.querySelector<HTMLElement>("[aria-expanded]")!;
267 + const header = () => screen.container.querySelector<HTMLElement>("[aria-expanded]")!;
268 expect(header().getAttribute("aria-expanded")).toBe("false");
269 await click(header());
270 expect(header().getAttribute("aria-expanded")).toBe("true");
@@ -296,7 +273,7 @@ describe("MessagesTimeline work rows", () => {
273 });
274
275 it("leads an unanswered question row with the question text", async () => {
299 - await renderTimeline([
276 + await using screen = await renderTimeline([
277 work("question-work", {
278 label: "User input requested",
279 tone: "tool",
@@ -308,16 +285,16 @@ describe("MessagesTimeline work rows", () => {
285 },
286 }),
287 ]);
311 - const toggle = button("Which repository?");
288 + const toggle = screen.button("Which repository?");
289 expect(toggle.getAttribute("aria-expanded")).toBe("false");
313 - const before = text().match(/Which repository\?/g)?.length ?? 0;
290 + const before = screen.text().match(/Which repository\?/g)?.length ?? 0;
291 expect(before).toBeGreaterThan(0);
292 await click(toggle);
316 - expect(text().match(/Which repository\?/g)?.length).toBe(before + 1);
293 + expect(screen.text().match(/Which repository\?/g)?.length).toBe(before + 1);
294 });
295
296 it("collapses settled tool runs behind a generated summary and names a failure", async () => {
320 - await renderTimeline([
297 + await using screen = await renderTimeline([
298 work("work-1", {
299 label: "Ran command",
300 command: "vp lint",
@@ -333,15 +310,15 @@ describe("MessagesTimeline work rows", () => {
310 toolLifecycleStatus: "failed",
311 }),
312 ]);
336 - const summary = button(/^Ran 2 commands/);
313 + const summary = screen.button(/^Ran 2 commands/);
314 expect(summary.getAttribute("aria-label")).toContain("tool call failed");
338 - expect(text()).not.toContain("vp lint");
315 + expect(screen.text()).not.toContain("vp lint");
316 await click(summary);
340 - await vi.waitFor(() => expect(text()).toContain("vp lint"));
317 + await vi.waitFor(() => expect(screen.text()).toContain("vp lint"));
318 });
319
320 it("keeps mixed work logs neutral after a later tool call succeeds", async () => {
344 - await renderTimeline([
321 + await using screen = await renderTimeline([
322 work("work-failed", {
323 label: "Run search",
324 tone: "tool",
@@ -356,11 +333,11 @@ describe("MessagesTimeline work rows", () => {
333 toolLifecycleStatus: "completed",
334 }),
335 ]);
359 - expect(button("Ran 2 commands and received 1 update")).toBeDefined();
336 + expect(screen.button("Ran 2 commands and received 1 update")).toBeDefined();
337 });
338
339 it("marks a failed tool inside an expanded work log", async () => {
363 - await renderTimeline([
340 + await using screen = await renderTimeline([
341 work("work-info", { label: "Status updated", tone: "info" }),
342 work("work-1", {
343 label: "Glob",
@@ -369,19 +346,21 @@ describe("MessagesTimeline work rows", () => {
346 detail: "No files found",
347 }),
348 ]);
372 - await click(button(/^Received 1 update/));
349 + await click(screen.button(/^Received 1 update/));
350 await vi.waitFor(() =>
374 - expect(container.querySelector('[aria-label="Tool call failed"]')).not.toBeNull(),
351 + expect(screen.container.querySelector('[aria-label="Tool call failed"]')).not.toBeNull(),
352 );
353 });
354
355 it("renders context compaction entries in the normal work log", async () => {
379 - await renderTimeline([work("work-1", { label: "Context compacted", tone: "info" })]);
380 - expect(text()).toContain("Context compacted");
356 + await using screen = await renderTimeline([
357 + work("work-1", { label: "Context compacted", tone: "info" }),
358 + ]);
359 + expect(screen.text()).toContain("Context compacted");
360 });
361
362 it("formats changed file paths from the workspace root", async () => {
384 - await renderTimeline(
363 + await using screen = await renderTimeline(
364 [
365 work("context-info", { label: "Session started", tone: "info" }),
366 work("work-1", {
@@ -394,9 +373,11 @@ describe("MessagesTimeline work rows", () => {
373 ],
374 { workspaceRoot: "C:/Users/mike/dev-stuff/t3code" },
375 );
397 - await click(button(/^Received 1 update/));
398 - await vi.waitFor(() => expect(text()).toContain("t3code/apps/web/src/session-logic.ts"));
399 - expect(text()).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
376 + await click(screen.button(/^Received 1 update/));
377 + await vi.waitFor(() => expect(screen.text()).toContain("t3code/apps/web/src/session-logic.ts"));
378 + expect(screen.text()).not.toContain(
379 + "C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts",
380 + );
381 });
382
383 it("renders T3 MCP dynamic tools with their pretty name", async () => {
@@ -407,7 +388,7 @@ describe("MessagesTimeline work rows", () => {
388 input: { threadId: "thread-child" },
389 output: { messages: [] },
390 };
410 - await renderTimeline([
391 + await using screen = await renderTimeline([
392 work("context-info", { label: "Session started", tone: "info" }),
393 work(item.id, {
394 runId: null,
@@ -421,9 +402,9 @@ describe("MessagesTimeline work rows", () => {
402 projectedItem: v2Item("dynamic_tool", item),
403 }),
404 ]);
424 - await click(button(/^Received 1 update/));
425 - await vi.waitFor(() => expect(text()).toContain("Read a T3 thread"));
426 - expect(text()).not.toContain("mcp__t3-code__t3_thread_read");
405 + await click(screen.button(/^Received 1 update/));
406 + await vi.waitFor(() => expect(screen.text()).toContain("Read a T3 thread"));
407 + expect(screen.text()).not.toContain("mcp__t3-code__t3_thread_read");
408 });
409
410 it("keeps a provider retry collapsed in the work log", async () => {
@@ -439,7 +420,7 @@ describe("MessagesTimeline work rows", () => {
420 },
421 retry: { attempt: 2, maxAttempts: 5, retryDelayMs: null },
422 };
442 - await renderTimeline(
423 + await using screen = await renderTimeline(
424 [
425 work("provider-error", {
426 runId: "run-1",
@@ -462,8 +443,8 @@ describe("MessagesTimeline work rows", () => {
443 },
444 },
445 );
465 - expect(text()).toContain("Retrying provider (2/5)");
466 - expect(text()).not.toContain("Structured details");
446 + expect(screen.text()).toContain("Retrying provider (2/5)");
447 + expect(screen.text()).not.toContain("Structured details");
448 });
449
450 it.each([
@@ -481,7 +462,7 @@ describe("MessagesTimeline work rows", () => {
462 ] as const)(
463 "shows plain text for a V2 reasoning preview: %s",
464 async (markdown, expected, strongCount) => {
484 - await renderTimeline([
465 + await using screen = await renderTimeline([
466 work("reasoning-preview", {
467 label: markdown,
468 detail: markdown,
@@ -490,15 +471,16 @@ describe("MessagesTimeline work rows", () => {
471 toolLifecycleStatus: "completed",
472 }),
473 ]);
493 - const row = () => container.querySelector<HTMLElement>("[role=button][aria-expanded]")!;
474 + const row = () =>
475 + screen.container.querySelector<HTMLElement>("[role=button][aria-expanded]")!;
476 const preview = () => row().textContent!.replace(/\s+/g, " ");
477 expect(preview()).toContain(expected);
496 - expect(container.querySelectorAll("strong")).toHaveLength(0);
478 + expect(screen.container.querySelectorAll("strong")).toHaveLength(0);
479 await click(row());
498 - expect(container.querySelectorAll("strong")).toHaveLength(strongCount);
480 + expect(screen.container.querySelectorAll("strong")).toHaveLength(strongCount);
481 await click(row());
482 expect(preview()).toContain(expected);
501 - await vi.waitFor(() => expect(container.querySelectorAll("strong")).toHaveLength(0));
483 + await vi.waitFor(() => expect(screen.container.querySelectorAll("strong")).toHaveLength(0));
484 },
485 );
486 });
@@ -515,12 +497,15 @@ describe("MessagesTimeline messages", () => {
497 async ({ role, selection, findExpanded }) => {
498 const code = "flowchart LR\n A[Select message] --> B[Copy Markdown]";
499 const source = `\`\`\`mermaid\n${code}\n\`\`\``;
518 - await renderTimeline([message(`Before diagram.\n\n${source}\n\nAfter diagram.`, { role })], {
519 - findExpanded,
520 - });
500 + await using screen = await renderTimeline(
501 + [message(`Before diagram.\n\n${source}\n\nAfter diagram.`, { role })],
502 + {
503 + findExpanded,
504 + },
505 + );
506 const diagram = await vi.waitFor(
507 () => {
523 - const svg = container.querySelector('[aria-label="Expand diagram"] svg');
508 + const svg = screen.container.querySelector('[aria-label="Expand diagram"] svg');
509 expect(svg).not.toBeNull();
510 return svg!;
511 },
@@ -529,7 +514,7 @@ describe("MessagesTimeline messages", () => {
514 const range = document.createRange();
515 let expected = source;
516 if (selection === "across") {
532 - const paragraphs = [...container.querySelectorAll("p")];
517 + const paragraphs = [...screen.container.querySelectorAll("p")];
518 const before = paragraphs.find((p) => p.textContent === "Before diagram.")!.firstChild!;
519 const after = paragraphs.find((p) => p.textContent === "After diagram.")!.firstChild!;
520 range.setStart(before, 2);
@@ -543,8 +528,8 @@ describe("MessagesTimeline messages", () => {
528 range.setStart(labelText, 2);
529 range.setEnd(labelText, 5);
530 } else {
546 - await click(button("Show code"));
547 - const code = container.querySelector("pre code")!;
531 + await click(screen.button("Show code"));
532 + const code = screen.container.querySelector("pre code")!;
533 const firstToken = document.createTreeWalker(code, NodeFilter.SHOW_TEXT).nextNode()!;
534 range.setStart(firstToken, 0);
535 range.setEnd(firstToken, 9);
@@ -575,7 +560,7 @@ describe("MessagesTimeline messages", () => {
560 const link = `[shot.png](t3-context://v1/image/${record.contextId})`;
561 const code = `flowchart LR\n A --> B\n%% ${link}`;
562 const source = `\`\`\`mermaid\n${code}\n\`\`\``;
578 - await renderTimeline([
563 + await using screen = await renderTimeline([
564 message(`Before\n\n${source}\n\nAfter\n\n${link}`, {
565 context: { version: 1, records: [record] },
566 attachments: [
@@ -590,13 +575,14 @@ describe("MessagesTimeline messages", () => {
575 }),
576 ]);
577 await vi.waitFor(
593 - () => expect(container.querySelector('[aria-label="Expand diagram"] svg')).not.toBeNull(),
578 + () =>
579 + expect(screen.container.querySelector('[aria-label="Expand diagram"] svg')).not.toBeNull(),
580 { timeout: 10_000 },
581 );
596 - const paragraphs = [...container.querySelectorAll("p")];
582 + const paragraphs = [...screen.container.querySelectorAll("p")];
583 const before = paragraphs.find((p) => p.textContent === "Before")!.firstChild!;
584 const after = paragraphs.find((p) => p.textContent === "After")!.firstChild!;
599 - const chip = button(/^Image attachment, shot\.png,/);
585 + const chip = screen.button(/^Image attachment, shot\.png,/);
586 const range = document.createRange();
587 range.setStart(before, 0);
588 range.setEnd(after, 5);
@@ -626,13 +612,13 @@ describe("MessagesTimeline messages", () => {
612 "</global-agent-instructions> in your context?",
613 "Comparison: 2 < 3 and 5 > 4.",
614 ];
629 - await renderTimeline([message(source.join("\n"))]);
630 - for (const line of source) expect(text()).toContain(line);
631 - expect(container.querySelector("global-agent-instructions, nested")).toBeNull();
615 + await using screen = await renderTimeline([message(source.join("\n"))]);
616 + for (const line of source) expect(screen.text()).toContain(line);
617 + expect(screen.container.querySelector("global-agent-instructions, nested")).toBeNull();
618 });
619
620 it("preserves XML-like source inside user code spans and fences", async () => {
635 - await renderTimeline([
621 + await using screen = await renderTimeline([
622 message(
623 [
624 'Inline `<tag attr="x">`',
@@ -643,32 +629,36 @@ describe("MessagesTimeline messages", () => {
629 ].join("\n"),
630 ),
631 ]);
646 - expect(container.querySelector("code[data-inline-code]")?.textContent).toBe('<tag attr="x">');
647 - expect(text()).toContain('<root><child enabled="true" /></root>');
632 + expect(screen.container.querySelector("code[data-inline-code]")?.textContent).toBe(
633 + '<tag attr="x">',
634 + );
635 + expect(screen.text()).toContain('<root><child enabled="true" /></root>');
636 });
637
638 it("does not show markdown titles in user messages", async () => {
651 - await renderTimeline([
639 + await using screen = await renderTimeline([
640 message(
641 '[link](https://example.com "link tip") ![image](https://example.com/image.png "image tip")',
642 ),
643 ]);
656 - expect(container.querySelector('a[href="https://example.com"]')).not.toBeNull();
657 - expect(container.querySelector('img[src="https://example.com/image.png"]')).not.toBeNull();
658 - expect(container.querySelector('[title="link tip"], [title="image tip"]')).toBeNull();
644 + expect(screen.container.querySelector('a[href="https://example.com"]')).not.toBeNull();
645 + expect(
646 + screen.container.querySelector('img[src="https://example.com/image.png"]'),
647 + ).not.toBeNull();
648 + expect(screen.container.querySelector('[title="link tip"], [title="image tip"]')).toBeNull();
649 });
650
651 it("renders unsafe user HTML as inert source text", async () => {
652 const source =
653 '<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">';
664 - await renderTimeline([message(source)]);
665 - expect(text()).toContain(source);
666 - expect(container.querySelector("script, img")).toBeNull();
654 + await using screen = await renderTimeline([message(source)]);
655 + expect(screen.text()).toContain(source);
656 + expect(screen.container.querySelector("script, img")).toBeNull();
657 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
658 });
659
660 it("renders sanitized raw HTML in assistant messages", async () => {
671 - await renderTimeline([
661 + await using screen = await renderTimeline([
662 message(
663 [
664 '<details onclick="globalThis.__t3Xss = 1">',
@@ -681,48 +671,53 @@ describe("MessagesTimeline messages", () => {
671 { role: "assistant" },
672 ),
673 ]);
684 - expect(container.querySelector("[data-markdown-details]")?.textContent).toContain(
674 + expect(screen.container.querySelector("[data-markdown-details]")?.textContent).toContain(
675 "Safe details",
676 );
687 - expect(text()).not.toContain("<details");
688 - expect(container.querySelector("script, [onclick], [onerror]")).toBeNull();
689 - expect(container.innerHTML).not.toContain("javascript:");
690 - await click(button("Safe details"));
677 + expect(screen.text()).not.toContain("<details");
678 + expect(screen.container.querySelector("script, [onclick], [onerror]")).toBeNull();
679 + expect(screen.container.innerHTML).not.toContain("javascript:");
680 + await click(screen.button("Safe details"));
681 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
682 });
683
684 it("collapses long user messages behind a toggle and keeps their copy button", async () => {
695 - await renderTimeline([message(longText())]);
696 - const toggle = button("Show full message");
685 + await using screen = await renderTimeline([message(longText())]);
686 + const toggle = screen.button("Show full message");
687 expect(toggle.getAttribute("aria-expanded")).toBe("false");
698 - expect(buttons("Copy message")).toHaveLength(1);
688 + expect(screen.buttons("Copy message")).toHaveLength(1);
689 await click(toggle);
700 - expect(button("Show less").getAttribute("aria-expanded")).toBe("true");
690 + expect(screen.button("Show less").getAttribute("aria-expanded")).toBe("true");
691 });
692
693 it("does not offer a collapse toggle for short user messages", async () => {
704 - await renderTimeline([message("Short prompt.")]);
705 - expect(buttons(/Show full message|Show less/)).toHaveLength(0);
694 + await using screen = await renderTimeline([message("Short prompt.")]);
695 + expect(screen.buttons(/Show full message|Show less/)).toHaveLength(0);
696 });
697
698 it("identifies user-role messages sent by another agent", async () => {
709 - await renderTimeline([
710 - message("Review this area", { createdBy: "agent", creationSource: "provider" }),
711 - ]);
712 - expect(text()).toContain("Sent by another agent");
713 - await act(async () => roots.pop()!.unmount());
714 - await renderTimeline([message("Review this area")]);
715 - expect(text()).not.toContain("Sent by another agent");
699 + {
700 + await using screen = await renderTimeline([
701 + message("Review this area", { createdBy: "agent", creationSource: "provider" }),
702 + ]);
703 + expect(screen.text()).toContain("Sent by another agent");
704 + }
705 + await using screen = await renderTimeline([message("Review this area")]);
706 + expect(screen.text()).not.toContain("Sent by another agent");
707 });
708
709 it("shows steer intent ahead of committed user messages", async () => {
719 - await renderTimeline([message("Adjust the current turn", { inputIntent: "steer" })]);
720 - expect(text().indexOf("Steer")).toBeGreaterThanOrEqual(0);
721 - expect(text().indexOf("Steer")).toBeLessThan(text().indexOf("Adjust the current turn"));
710 + await using screen = await renderTimeline([
711 + message("Adjust the current turn", { inputIntent: "steer" }),
712 + ]);
713 + expect(screen.text().indexOf("Steer")).toBeGreaterThanOrEqual(0);
714 + expect(screen.text().indexOf("Steer")).toBeLessThan(
715 + screen.text().indexOf("Adjust the current turn"),
716 + );
717 });
718
719 it("renders inline terminal labels as chips", async () => {
725 - await renderTimeline([
720 + await using screen = await renderTimeline([
721 message(
722 [
723 longText("yoo what's @terminal-1:1-5 mean"),
@@ -735,14 +730,14 @@ describe("MessagesTimeline messages", () => {
730 ].join("\n"),
731 ),
732 ]);
738 - expect(text()).toContain("Terminal 1 lines 1-5");
739 - expect(text()).toContain("yoo what's");
740 - expect(text()).not.toContain("terminal_context");
741 - expect(buttons("Show full message")).toHaveLength(1);
733 + expect(screen.text()).toContain("Terminal 1 lines 1-5");
734 + expect(screen.text()).toContain("yoo what's");
735 + expect(screen.text()).not.toContain("terminal_context");
736 + expect(screen.buttons("Show full message")).toHaveLength(1);
737 });
738
739 it("renders chips for standalone element-pick context messages", async () => {
745 - await renderTimeline([
740 + await using screen = await renderTimeline([
741 message(
742 [
743 "<element_context>",
@@ -756,12 +751,12 @@ describe("MessagesTimeline messages", () => {
751 ].join("\n"),
752 ),
753 ]);
759 - expect(text()).toContain("SubmitButton");
760 - expect(text()).not.toContain("element_context");
754 + expect(screen.text()).toContain("SubmitButton");
755 + expect(screen.text()).not.toContain("element_context");
756 });
757
758 it("renders review comment contexts as structured cards instead of raw tags", async () => {
764 - await renderTimeline([
759 + await using screen = await renderTimeline([
760 message(
761 [
762 '<review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="apps/web/src/lib/contextWindow.test.ts" startIndex="3" endIndex="14" rangeLabel="+47 to +58">',
@@ -775,12 +770,12 @@ describe("MessagesTimeline messages", () => {
770 ].join("\n"),
771 ),
772 ]);
778 - expect(text()).toContain("contextWindow.test.ts L47 to L58");
779 - expect(text()).not.toContain("review_comment");
773 + expect(screen.text()).toContain("contextWindow.test.ts L47 to L58");
774 + expect(screen.text()).not.toContain("review_comment");
775 });
776
777 it("renders file review comments as source code", async () => {
783 - await renderTimeline([
778 + await using screen = await renderTimeline([
779 message(
780 [
781 '<review_comment sectionId="file:docs/plan.md" sectionTitle="File comment" filePath="docs/plan.md" startIndex="0" endIndex="1" rangeLabel="L1 to L2">',
@@ -793,8 +788,8 @@ describe("MessagesTimeline messages", () => {
788 ].join("\n"),
789 ),
790 ]);
796 - expect(text()).toContain("plan.md L1 to L2");
797 - expect(text()).not.toContain("review_comment");
791 + expect(screen.text()).toContain("plan.md L1 to L2");
792 + expect(screen.text()).not.toContain("review_comment");
793 });
794
795 it("collapses superseded attempt output behind a disclosure", async () => {
@@ -808,7 +803,7 @@ describe("MessagesTimeline messages", () => {
803 status,
804 completedAt: null,
805 }) as never;
811 - await renderTimeline(
806 + await using screen = await renderTimeline(
807 [
808 {
809 ...message(
@@ -831,17 +826,17 @@ describe("MessagesTimeline messages", () => {
826 latestRun: { runId, status: "running", startedAt: CREATED_AT, completedAt: null },
827 },
828 );
834 - expect(text()).toContain("Current response remains visible");
835 - expect(text()).not.toContain("Partial response from the old attempt");
836 - const disclosure = button(/Superseded attempt/);
829 + expect(screen.text()).toContain("Current response remains visible");
830 + expect(screen.text()).not.toContain("Partial response from the old attempt");
831 + const disclosure = screen.button(/Superseded attempt/);
832 expect(disclosure.textContent).toContain("Cut off by a steer");
833 await click(disclosure);
839 - expect(text()).toContain("Partial response from the old attempt");
834 + expect(screen.text()).toContain("Partial response from the old attempt");
835 });
836
837 it("forks from a completed assistant response", async () => {
838 const onForkFromRun = vi.fn(async () => {});
844 - await renderTimeline(
839 + await using screen = await renderTimeline(
840 [
841 {
842 ...message("Done", { role: "assistant", runId: RunId.make("run-1") }, "assistant-1"),
@@ -855,7 +850,7 @@ describe("MessagesTimeline messages", () => {
850 ],
851 { onForkFromRun },
852 );
858 - await click(button("Fork from this response"));
853 + await click(screen.button("Fork from this response"));
854 expect(onForkFromRun).toHaveBeenCalledWith({ sourceThreadId: "thread-1", runId: "run-1" });
855 });
856
@@ -863,7 +858,7 @@ describe("MessagesTimeline messages", () => {
858 const assistantMessageId = MessageId.make("assistant-with-files");
859 const runId = RunId.make("run-with-files");
860 const onOpenTurnDiff = vi.fn();
866 - await renderTimeline(
861 + await using screen = await renderTimeline(
862 [message("Updated the fixture.", { role: "assistant", runId }, assistantMessageId)],
863 {
864 onOpenTurnDiff,
@@ -881,8 +876,8 @@ describe("MessagesTimeline messages", () => {
876 ],
877 },
878 );
884 - expect(text()).toContain("1 changed file");
885 - await click(button("Open diff"));
879 + expect(screen.text()).toContain("1 changed file");
880 + await click(screen.button("Open diff"));
881 expect(onOpenTurnDiff).toHaveBeenCalledWith(runId, "README.md");
882 });
883 });
@@ -902,31 +897,33 @@ describe("MessagesTimeline attachments", () => {
897 });
898
899 it("offers preview and download actions for PDF attachments", async () => {
905 - await renderTimeline([
900 + await using screen = await renderTimeline([
901 withAttachment({
902 id: "attachment-report-pdf",
903 previewUrl: "https://environment.test/api/assets/report.pdf",
904 }),
905 ]);
911 - expect(buttons("Preview report.pdf")).toHaveLength(1);
912 - expect(buttons("Download report.pdf")).toHaveLength(1);
913 - expect(container.querySelector('img[alt="report.pdf"]')).toBeNull();
906 + expect(screen.buttons("Preview report.pdf")).toHaveLength(1);
907 + expect(screen.buttons("Download report.pdf")).toHaveLength(1);
908 + expect(screen.container.querySelector('img[alt="report.pdf"]')).toBeNull();
909 });
910
911 it("does not create a download URL before the download is requested", async () => {
917 - await renderTimeline([withAttachment({ id: "attachment-report-pdf" })]);
918 - expect(buttons("Download report.pdf")).toHaveLength(1);
919 - expect(container.querySelector("a[href]")).toBeNull();
912 + await using screen = await renderTimeline([withAttachment({ id: "attachment-report-pdf" })]);
913 + expect(screen.buttons("Download report.pdf")).toHaveLength(1);
914 + expect(screen.container.querySelector("a[href]")).toBeNull();
915 });
916
917 it("does not download an optimistic file before the server supplies its attachment ID", async () => {
923 - await renderTimeline([withAttachment({ id: "composer-local-report", downloadable: false })]);
924 - expect(text()).toContain("report.pdf");
925 - expect(buttons("Download report.pdf")).toHaveLength(0);
918 + await using screen = await renderTimeline([
919 + withAttachment({ id: "composer-local-report", downloadable: false }),
920 + ]);
921 + expect(screen.text()).toContain("report.pdf");
922 + expect(screen.buttons("Download report.pdf")).toHaveLength(0);
923 });
924
925 it("renders unknown attachment types as inert rows instead of crashing", async () => {
929 - await renderTimeline([
926 + await using screen = await renderTimeline([
927 withAttachment({
928 type: "recording",
929 id: "attachment-voice-memo",
@@ -934,9 +931,9 @@ describe("MessagesTimeline attachments", () => {
931 mimeType: "audio/ogg",
932 }),
933 ]);
937 - expect(text()).toContain("voice-memo.ogg");
938 - expect(buttons("Download voice-memo.ogg")).toHaveLength(0);
939 - expect(container.querySelector("a[href], img")).toBeNull();
934 + expect(screen.text()).toContain("voice-memo.ogg");
935 + expect(screen.buttons("Download voice-memo.ogg")).toHaveLength(0);
936 + expect(screen.container.querySelector("a[href], img")).toBeNull();
937 });
938
939 it("shows SnapShot window details only after the preview resolves", async () => {
@@ -960,13 +957,14 @@ describe("MessagesTimeline attachments", () => {
957 },
958 ] as never,
959 });
963 - await renderTimeline([snapShot()]);
964 - expect(text()).toContain("screenshot.png");
965 - expect(text()).not.toContain("t3code — Tests");
966 - await act(async () => roots.pop()!.unmount());
967 - await renderTimeline([snapShot("data:image/png;base64,iVBORw0KGgo=")]);
968 - expect(text()).toContain("Terminal");
969 - expect(text()).toContain("t3code — Tests");
960 + {
961 + await using screen = await renderTimeline([snapShot()]);
962 + expect(screen.text()).toContain("screenshot.png");
963 + expect(screen.text()).not.toContain("t3code — Tests");
964 + }
965 + await using screen = await renderTimeline([snapShot("data:image/png;base64,iVBORw0KGgo=")]);
966 + expect(screen.text()).toContain("Terminal");
967 + expect(screen.text()).toContain("t3code — Tests");
968 });
969 });
970
@@ -984,33 +982,33 @@ describe("MessagesTimeline history and thread links", () => {
982 message("Investigation complete.", { role: "assistant", runId }, "citation-answer"),
983 ],
984 };
987 - await renderElement(<MessagesTimeline {...props} />);
985 + await using screen = await renderElement(<MessagesTimeline {...props} />);
986 const source = () =>
989 - container.querySelector<HTMLElement>('[data-assistant-citation-source="citation-source"]');
990 - await vi.waitFor(() => expect(text()).toContain("Investigation complete."));
991 - expect(buttons(/^Worked/)).toHaveLength(1);
987 + screen.container.querySelector<HTMLElement>(
988 + '[data-assistant-citation-source="citation-source"]',
989 + );
990 + await vi.waitFor(() => expect(screen.text()).toContain("Investigation complete."));
991 + expect(screen.buttons(/^Worked/)).toHaveLength(1);
992 expect(source()).toBeNull();
993
994 - await act(async () =>
995 - roots.at(-1)!.render(
996 - <MessagesTimeline
997 - {...props}
998 - citationRequest={{
999 - key: "open-citation",
1000 - citation: {
1001 - version: 1,
1002 - environmentId: ENVIRONMENT_ID,
1003 - threadId: ThreadId.make(`thread-${threadCount}`),
1004 - messageId: MessageId.make("citation-source"),
1005 - text: quote,
1006 - start: 0,
1007 - end: quote.length,
1008 - prefix: "",
1009 - suffix: "",
1010 - },
1011 - }}
1012 - />,
1013 - ),
994 + await screen.rerender(
995 + <MessagesTimeline
996 + {...props}
997 + citationRequest={{
998 + key: "open-citation",
999 + citation: {
1000 + version: 1,
1001 + environmentId: ENVIRONMENT_ID,
1002 + threadId: ThreadId.make(props.routeThreadKey.slice("environment-local:".length)),
1003 + messageId: MessageId.make("citation-source"),
1004 + text: quote,
1005 + start: 0,
1006 + end: quote.length,
1007 + prefix: "",
1008 + suffix: "",
1009 + },
1010 + }}
1011 + />,
1012 );
1013
1014 await vi.waitFor(() => {
@@ -1019,7 +1017,9 @@ describe("MessagesTimeline history and thread links", () => {
1017 expect(highlight).toBeDefined();
1018 const range = [...highlight!][0] as Range;
1019 expect(range.toString()).toBe(quote);
1022 - const viewport = container.querySelector<HTMLElement>("[data-assistant-citation-viewport]")!;
1020 + const viewport = screen.container.querySelector<HTMLElement>(
1021 + "[data-assistant-citation-viewport]",
1022 + )!;
1023 const bounds = range.getBoundingClientRect();
1024 expect(bounds.height).toBeGreaterThan(0);
1025 expect(bounds.top).toBeGreaterThanOrEqual(viewport.getBoundingClientRect().top);
@@ -1029,7 +1029,7 @@ describe("MessagesTimeline history and thread links", () => {
1029
1030 it("loads earlier turns from a control ahead of the bounded timeline", async () => {
1031 const onLoadEarlier = vi.fn();
1032 - await renderTimeline([message("Recent activity")], {
1032 + await using screen = await renderTimeline([message("Recent activity")], {
1033 historyControls: {
1034 hasMoreHistory: true,
1035 loading: false,
@@ -1037,14 +1037,16 @@ describe("MessagesTimeline history and thread links", () => {
1037 onLoadEarlier,
1038 },
1039 });
1040 - expect(text()).toContain("Earlier activity could not be loaded.");
1041 - expect(text().indexOf("Load earlier turns")).toBeLessThan(text().indexOf("Recent activity"));
1042 - await click(button("Load earlier turns"));
1040 + expect(screen.text()).toContain("Earlier activity could not be loaded.");
1041 + expect(screen.text().indexOf("Load earlier turns")).toBeLessThan(
1042 + screen.text().indexOf("Recent activity"),
1043 + );
1044 + await click(screen.button("Load earlier turns"));
1045 expect(onLoadEarlier).toHaveBeenCalledOnce();
1046 });
1047
1048 it("keeps an empty bounded timeline busy while earlier history loads", async () => {
1047 - await renderTimeline([], {
1049 + await using screen = await renderTimeline([], {
1050 historyControls: {
1051 hasMoreHistory: true,
1052 loading: true,
@@ -1052,21 +1054,21 @@ describe("MessagesTimeline history and thread links", () => {
1054 onLoadEarlier: () => {},
1055 },
1056 });
1055 - expect(text()).toContain("Loading earlier turns…");
1056 - expect(button("Load earlier turns")).toHaveProperty("disabled", true);
1057 - expect(text()).not.toContain("Send a message to start the conversation.");
1057 + expect(screen.text()).toContain("Loading earlier turns…");
1058 + expect(screen.button("Load earlier turns")).toHaveProperty("disabled", true);
1059 + expect(screen.text()).not.toContain("Send a message to start the conversation.");
1060 });
1061
1062 it("opens the parent thread from the top of an empty subagent timeline", async () => {
1063 const onOpenThread = vi.fn();
1062 - await renderTimeline([], {
1064 + await using screen = await renderTimeline([], {
1065 onOpenThread,
1066 parentThreadLink: { threadId: ThreadId.make("thread-parent"), title: "Architecture audit" },
1067 });
1066 - expect(text()).toContain("Subagent of");
1067 - expect(text()).toContain("Architecture audit");
1068 - expect(text()).not.toContain("Send a message to start the conversation");
1069 - await click(button("Open parent thread"));
1068 + expect(screen.text()).toContain("Subagent of");
1069 + expect(screen.text()).toContain("Architecture audit");
1070 + expect(screen.text()).not.toContain("Send a message to start the conversation");
1071 + await click(screen.button("Open parent thread"));
1072 expect(onOpenThread).toHaveBeenCalledWith("thread-parent");
1073 });
1074
@@ -1079,37 +1081,31 @@ describe("MessagesTimeline history and thread links", () => {
1081 `message-${index}`,
1082 ),
1083 );
1082 - await renderTimeline([], {
1084 + await using screen = await renderTimeline([], {
1085 ...props,
1086 routeThreadKey: `${props.routeThreadKey}-loading`,
1087 hideEmptyPlaceholder: true,
1088 });
1089
1090 // Each row is much taller than LegendList's estimate.
1089 - await act(async () =>
1090 - roots.at(-1)!.render(<MessagesTimeline {...props} timelineEntries={entries} />),
1091 - );
1091 + await screen.rerender(<MessagesTimeline {...props} timelineEntries={entries} />);
1092 const viewport = props.listRef.current!.getScrollableNode();
1093 await vi.waitFor(() => {
1094 expect(viewport.scrollHeight).toBeGreaterThan(viewport.clientHeight);
1095 - expect(text()).toContain("Paragraph 11.59");
1095 + expect(screen.text()).toContain("Paragraph 11.59");
1096 expect(
1097 viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop,
1098 ).toBeLessThanOrEqual(1);
1099 });
1100
1101 const otherThreadKey = `${props.routeThreadKey}-other`;
1102 - await act(async () =>
1103 - roots
1104 - .at(-1)!
1105 - .render(
1106 - <MessagesTimeline
1107 - {...props}
1108 - routeThreadKey={otherThreadKey}
1109 - timelineEntries={entries}
1110 - liveFollowEnabled={false}
1111 - />,
1112 - ),
1102 + await screen.rerender(
1103 + <MessagesTimeline
1104 + {...props}
1105 + routeThreadKey={otherThreadKey}
1106 + timelineEntries={entries}
1107 + liveFollowEnabled={false}
1108 + />,
1109 );
1110 await vi.waitFor(() =>
1111 expect(
@@ -1125,11 +1121,9 @@ describe("MessagesTimeline history and thread links", () => {
1121 );
1122 });
1123
1128 - await act(async () =>
1129 - roots.at(-1)!.render(<MessagesTimeline {...props} timelineEntries={entries} />),
1130 - );
1124 + await screen.rerender(<MessagesTimeline {...props} timelineEntries={entries} />);
1125 await vi.waitFor(() => {
1132 - expect(text()).toContain("Paragraph 11.59");
1126 + expect(screen.text()).toContain("Paragraph 11.59");
1127 expect(
1128 viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop,
1129 ).toBeLessThanOrEqual(1);
@@ -1137,7 +1131,7 @@ describe("MessagesTimeline history and thread links", () => {
1131 });
1132
1133 it("does not render the transient V2 interruption request", async () => {
1140 - await renderTimeline([
1134 + await using screen = await renderTimeline([
1135 {
1136 id: "interrupt-request",
1137 kind: "event",
@@ -1148,13 +1142,13 @@ describe("MessagesTimeline history and thread links", () => {
1142 }),
1143 } as Entry,
1144 ]);
1151 - expect(text()).not.toContain("Interrupt requested");
1152 - expect(text()).not.toContain("Waiting for the provider to stop.");
1145 + expect(screen.text()).not.toContain("Interrupt requested");
1146 + expect(screen.text()).not.toContain("Waiting for the provider to stop.");
1147 });
1148
1149 it("opens created threads from a lean row", async () => {
1150 const onOpenThread = vi.fn();
1157 - await renderTimeline(
1151 + await using screen = await renderTimeline(
1152 [
1153 {
1154 id: "thread-created",
@@ -1174,9 +1168,9 @@ describe("MessagesTimeline history and thread links", () => {
1168 ],
1169 { onOpenThread },
1170 );
1177 - expect(text()).toContain("Claude research thread");
1178 - expect(text()).not.toContain("Work Log");
1179 - await click(button("Open Claude research thread"));
1171 + expect(screen.text()).toContain("Claude research thread");
1172 + expect(screen.text()).not.toContain("Work Log");
1173 + await click(screen.button("Open Claude research thread"));
1174 expect(onOpenThread).toHaveBeenCalledWith("thread-2");
1175 });
1176
@@ -1217,50 +1211,52 @@ describe("MessagesTimeline history and thread links", () => {
1211 ...fields,
1212 }),
1213 }) as Entry;
1220 - const show = async (entry: Entry, props: Partial<TimelineProps> = {}) => {
1221 - for (const root of roots.splice(0)) await act(async () => root.unmount());
1222 - await renderElement(
1214 + const show = (entry: Entry, props: Partial<TimelineProps> = {}) =>
1215 + renderElement(
1216 <RegistryProvider
1217 initialValues={[[serverEnvironment.providersValueAtom(ENVIRONMENT_ID), providers]]}
1218 >
1219 <MessagesTimeline {...baseProps()} timelineEntries={[entry]} {...props} />
1220 </RegistryProvider>,
1221 );
1229 - };
1222
1231 - await show(
1232 - handoff({
1233 - fromModelSelections: [{ instanceId: "codex_personal", model: "gpt-5.6-sol" }],
1234 - toModel: "claude-fable-5",
1235 - }),
1236 - );
1237 - expect(text()).toContain("Context handoff");
1238 - expect(text()).toContain("GPT 5.6 Sol");
1239 - expect(text()).toContain("Claude Fable 5");
1240 - expect(text()).not.toContain("Full conversation context");
1223 + {
1224 + await using screen = await show(
1225 + handoff({
1226 + fromModelSelections: [{ instanceId: "codex_personal", model: "gpt-5.6-sol" }],
1227 + toModel: "claude-fable-5",
1228 + }),
1229 + );
1230 + expect(screen.text()).toContain("Context handoff");
1231 + expect(screen.text()).toContain("GPT 5.6 Sol");
1232 + expect(screen.text()).toContain("Claude Fable 5");
1233 + expect(screen.text()).not.toContain("Full conversation context");
1234 + }
1235
1242 - await show(handoff({}), {
1243 - runs: [
1244 - {
1245 - id: "run-1",
1246 - ordinal: 1,
1247 - providerInstanceId: "codex_personal",
1248 - modelSelection: { instanceId: "codex_personal", model: "gpt-5.6-sol" },
1249 - },
1250 - {
1251 - id: "run-2",
1252 - ordinal: 2,
1253 - providerInstanceId: "claudeAgent",
1254 - modelSelection: { instanceId: "claudeAgent", model: "claude-fable-5" },
1255 - },
1256 - ] as never,
1257 - });
1258 - expect(text()).toContain("GPT 5.6 Sol");
1259 - expect(text()).toContain("Claude Fable 5");
1236 + {
1237 + await using screen = await show(handoff({}), {
1238 + runs: [
1239 + {
1240 + id: "run-1",
1241 + ordinal: 1,
1242 + providerInstanceId: "codex_personal",
1243 + modelSelection: { instanceId: "codex_personal", model: "gpt-5.6-sol" },
1244 + },
1245 + {
1246 + id: "run-2",
1247 + ordinal: 2,
1248 + providerInstanceId: "claudeAgent",
1249 + modelSelection: { instanceId: "claudeAgent", model: "claude-fable-5" },
1250 + },
1251 + ] as never,
1252 + });
1253 + expect(screen.text()).toContain("GPT 5.6 Sol");
1254 + expect(screen.text()).toContain("Claude Fable 5");
1255 + }
1256
1261 - await show(handoff({}));
1262 - expect(text()).toContain("Codex Personal");
1263 - expect(text()).not.toContain("Full conversation context");
1257 + await using screen = await show(handoff({}));
1258 + expect(screen.text()).toContain("Codex Personal");
1259 + expect(screen.text()).not.toContain("Full conversation context");
1260 });
1261 });
1262
@@ -1310,7 +1306,7 @@ describe("MessagesTimeline subagents", () => {
1306 "shows $count $status subagents with '$preview', grouping only multiple agents",
1307 async ({ status, progress, result, preview, count }) => {
1308 const onOpenThread = vi.fn();
1313 - await renderTimeline(
1309 + await using screen = await renderTimeline(
1310 Array.from(
1311 { length: count },
1312 (_, index) =>
@@ -1339,25 +1335,25 @@ describe("MessagesTimeline subagents", () => {
1335 ),
1336 { onOpenThread },
1337 );
1342 - const children = () => buttons("Open Package audit");
1338 + const children = () => screen.buttons("Open Package audit");
1339 // A settled run folds its work behind a "Worked for" summary.
1344 - const fold = buttons(/^Worked for/)[0];
1340 + const fold = screen.buttons(/^Worked for/)[0];
1341 if (fold) await click(fold);
1342 if (count > 1) {
1343 expect(children()).toHaveLength(0);
1348 - await click(button(`${count} subagents`));
1344 + await click(screen.button(`${count} subagents`));
1345 } else {
1350 - expect(buttons(`${count} subagents`)).toHaveLength(0);
1346 + expect(screen.buttons(`${count} subagents`)).toHaveLength(0);
1347 }
1348 expect(children()).toHaveLength(count);
1353 - expect(text()).toContain(preview);
1354 - expect(text()).not.toContain("Inspect the package");
1355 - if (result?.trim() && result !== preview) expect(text()).not.toContain(result);
1356 - if (progress && progress !== preview) expect(text()).not.toContain(progress);
1349 + expect(screen.text()).toContain(preview);
1350 + expect(screen.text()).not.toContain("Inspect the package");
1351 + if (result?.trim() && result !== preview) expect(screen.text()).not.toContain(result);
1352 + if (progress && progress !== preview) expect(screen.text()).not.toContain(progress);
1353 await click(children()[0]!);
1354 expect(onOpenThread).toHaveBeenCalledWith("thread-subagent-1");
1355 if (count > 1) {
1360 - await click(button(`${count} subagents`));
1356 + await click(screen.button(`${count} subagents`));
1357 await vi.waitFor(() => expect(children()).toHaveLength(0));
1358 }
1359 },
@@ -1384,7 +1380,7 @@ describe("timeline tooltip scroll dismissal", () => {
1380 <TooltipPopup>https://example.com</TooltipPopup>
1381 </Tooltip>
1382 );
1387 - await renderElement(
1383 + const screen = await renderElement(
1384 <>
1385 <TooltipScrollDismissArea>
1386 <div data-testid="scrollable" className="h-[100px] overflow-auto">
@@ -1395,10 +1391,10 @@ describe("timeline tooltip scroll dismissal", () => {
1391 {outside ? tooltip : null}
1392 </>,
1393 );
1398 - return {
1399 - trigger: container.querySelector<HTMLButtonElement>("button")!,
1400 - scrollable: container.querySelector<HTMLElement>('[data-testid="scrollable"]')!,
1401 - };
1394 + return Object.assign(screen, {
1395 + trigger: screen.container.querySelector<HTMLButtonElement>("button")!,
1396 + scrollable: screen.container.querySelector<HTMLElement>('[data-testid="scrollable"]')!,
1397 + });
1398 }
1399
1400 async function scroll(scrollable: HTMLElement) {
@@ -1411,7 +1407,8 @@ describe("timeline tooltip scroll dismissal", () => {
1407 it.each([false, true])(
1408 "closes a hovered tooltip on scroll but keeps a focused one (pull request=%s)",
1409 async (pullRequest) => {
1414 - const { trigger, scrollable } = await renderTooltip(pullRequest, false);
1410 + await using screen = await renderTooltip(pullRequest, false);
1411 + const { trigger, scrollable } = screen;
1412 await userEvent.hover(trigger);
1413 await vi.waitFor(() => expect(openPopup()).toBe("https://example.com"));
1414 await scroll(scrollable);
@@ -1428,7 +1425,8 @@ describe("timeline tooltip scroll dismissal", () => {
1425 );
1426
1427 it("leaves tooltips outside the timeline open when it scrolls", async () => {
1431 - const { trigger, scrollable } = await renderTooltip(false, true);
1428 + await using screen = await renderTooltip(false, true);
1429 + const { trigger, scrollable } = screen;
1430 await userEvent.hover(trigger);
1431 await vi.waitFor(() => expect(openPopup()).toBe("https://example.com"));
1432 await scroll(scrollable);
@@ -1436,7 +1434,8 @@ describe("timeline tooltip scroll dismissal", () => {
1434 });
1435
1436 it("keeps a hovered tooltip open on a wheel that does not scroll", async () => {
1439 - const { trigger, scrollable } = await renderTooltip(false, false);
1437 + await using screen = await renderTooltip(false, false);
1438 + const { trigger, scrollable } = screen;
1439 await userEvent.hover(trigger);
1440 await vi.waitFor(() => expect(openPopup()).toBe("https://example.com"));
1441 await act(async () => {
@@ -1486,7 +1485,7 @@ describe("MessagesTimeline scroll position", () => {
1485 <MessagesTimeline {...props} timelineEntries={entries} />
1486 </Profiler>
1487 );
1489 - await renderElement(timeline(long));
1488 + await using screen = await renderElement(timeline(long));
1489 const viewport = await waitForList(props);
1490 await act(async () => {
1491 viewport.scrollTop = 0;
@@ -1494,13 +1493,13 @@ describe("MessagesTimeline scroll position", () => {
1493 });
1494
1495 maxNestedCommits = 0;
1497 - await act(async () => roots.at(-1)!.render(timeline([...short, ...long])));
1496 + await screen.rerender(timeline([...short, ...long]));
1497 await vi.waitFor(async () => {
1498 await act(async () => {
1499 viewport.scrollTop = 0;
1500 viewport.dispatchEvent(new Event("scroll"));
1501 });
1503 - expect(text()).toContain("Short reply 0");
1502 + expect(screen.text()).toContain("Short reply 0");
1503 });
1504 expect(maxNestedCommits).toBeLessThan(8);
1505 });
@@ -1520,14 +1519,16 @@ describe("MessagesTimeline scroll position", () => {
1519 </div>
1520 );
1521 }
1523 - await renderElement(<Chat />);
1524 - const viewport = await waitForList(props);
1525 - await vi.waitFor(() => expect(readTimelinePosition(props.routeThreadKey)?.atEnd).toBe(true));
1526 -
1527 - await userEvent.wheel(viewport, { delta: { y: -600 } });
1528 - await vi.waitFor(() => expect(readTimelinePosition(props.routeThreadKey)?.atEnd).toBe(false));
1529 - const offset = viewport.scrollTop;
1530 - await act(async () => roots.pop()!.unmount());
1522 + let offset: number;
1523 + {
1524 + await using _chat = await renderElement(<Chat />);
1525 + const viewport = await waitForList(props);
1526 + await vi.waitFor(() => expect(readTimelinePosition(props.routeThreadKey)?.atEnd).toBe(true));
1527 +
1528 + await userEvent.wheel(viewport, { delta: { y: -600 } });
1529 + await vi.waitFor(() => expect(readTimelinePosition(props.routeThreadKey)?.atEnd).toBe(false));
1530 + offset = viewport.scrollTop;
1531 + }
1532 expect(readTimelinePosition(props.routeThreadKey)).toMatchObject({
1533 atEnd: false,
1534 scrollOffset: offset,
@@ -1536,19 +1537,19 @@ describe("MessagesTimeline scroll position", () => {
1537 const timeline = (routeThreadKey: string) => (
1538 <MessagesTimeline {...props} routeThreadKey={routeThreadKey} timelineEntries={tallEntries} />
1539 );
1539 - await renderElement(timeline(props.routeThreadKey));
1540 + await using screen = await renderElement(timeline(props.routeThreadKey));
1541 const reopenedViewport = await waitForList(props);
1542 await vi.waitFor(() =>
1543 expect(Math.abs(reopenedViewport.scrollTop - offset)).toBeLessThanOrEqual(1),
1544 );
1545
1545 - await act(async () => roots.at(-1)!.render(timeline(`${props.routeThreadKey}-other`)));
1546 + await screen.rerender(timeline(`${props.routeThreadKey}-other`));
1547 await vi.waitFor(() =>
1548 expect(
1549 reopenedViewport.scrollHeight - reopenedViewport.clientHeight - reopenedViewport.scrollTop,
1550 ).toBeLessThanOrEqual(1),
1551 );
1551 - await act(async () => roots.at(-1)!.render(timeline(props.routeThreadKey)));
1552 + await screen.rerender(timeline(props.routeThreadKey));
1553 await vi.waitFor(() =>
1554 expect(Math.abs(reopenedViewport.scrollTop - offset)).toBeLessThanOrEqual(1),
1555 );
@@ -1578,16 +1579,16 @@ describe("MessagesTimeline scroll position", () => {
1579 </>
1580 );
1581 }
1581 - await renderElement(<Thread />);
1582 - const composerState = () => container.querySelector("output")!.textContent;
1582 + await using screen = await renderElement(<Thread />);
1583 + const composerState = () => screen.container.querySelector("output")!.textContent;
1584 const viewport = await waitForList(props);
1584 - await click(button("Collapse"));
1585 - const toggle = () => button("Command output");
1585 + await click(screen.button("Collapse"));
1586 + const toggle = () => screen.button("Command output");
1587 await click(toggle());
1588 await click(toggle());
1589 await vi.waitFor(() => expect(composerState()).toBe("resting"));
1590
1590 - await click(button("Collapse"));
1591 + await click(screen.button("Collapse"));
1592 await userEvent.wheel(viewport, { delta: { y: -2000 } });
1593 await click(toggle());
1594 await click(toggle());
@@ -1600,11 +1601,14 @@ describe("MessagesTimeline send anchor", () => {
1601 it("reports the anchored sent message once it is laid out", async () => {
1602 const onAnchorReady = vi.fn();
1603 const sent = message("Newest prompt.", {}, "message-2");
1603 - await renderTimeline([message("Earlier reply.", { role: "assistant" }), sent], {
1604 - anchorMessageId: MessageId.make("message-2"),
1605 - onAnchorReady,
1606 - contentInsetEndAdjustment: 144,
1607 - });
1604 + await using _screen = await renderTimeline(
1605 + [message("Earlier reply.", { role: "assistant" }), sent],
1606 + {
1607 + anchorMessageId: MessageId.make("message-2"),
1608 + onAnchorReady,
1609 + contentInsetEndAdjustment: 144,
1610 + },
1611 + );
1612 await vi.waitFor(() =>
1613 expect(onAnchorReady).toHaveBeenCalledWith(MessageId.make("message-2"), 1),
1614 );
@@ -1612,10 +1616,13 @@ describe("MessagesTimeline send anchor", () => {
1616
1617 it("does not anchor a follow-up user message that is not the newest turn", async () => {
1618 const onAnchorReady = vi.fn();
1615 - await renderTimeline([message("First prompt."), message("Newest prompt.", {}, "message-2")], {
1616 - anchorMessageId: MessageId.make("message-2"),
1617 - onAnchorReady,
1618 - });
1619 + await using _screen = await renderTimeline(
1620 + [message("First prompt."), message("Newest prompt.", {}, "message-2")],
1621 + {
1622 + anchorMessageId: MessageId.make("message-2"),
1623 + onAnchorReady,
1624 + },
1625 + );
1626 await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
1627 expect(onAnchorReady).not.toHaveBeenCalled();
1628 });
apps/web/src/components/chat/OpenInPicker.browser.test.tsx
+94 -74
@@ -1,10 +1,9 @@
1 import { AuthOrchestrationOperateScope, EnvironmentId, type EditorId } from "@t3tools/contracts";
2 import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
3 import { AsyncResult } from "effect/reactivity";
4 -import { act } from "react";
5 -import { createRoot, type Root } from "react-dom/client";
6 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4 +import { describe, expect, it, vi } from "vite-plus/test";
5
6 +import { act, render as renderUi } from "../../../test/render";
7 import type { RemoteOpenState } from "../../remoteOpen";
8
9 const state = vi.hoisted(() => ({
@@ -71,10 +70,8 @@ import { useOpenFavoriteEditorShortcut } from "./OpenInPickerShortcut";
70 const primary = EnvironmentId.make("primary");
71 const selected = EnvironmentId.make("selected");
72 const editors: readonly EditorId[] = ["vscode"];
74 -let root: Root;
75 -let container: HTMLDivElement;
73
77 -beforeEach(() => {
74 +async function setup() {
75 state.allowed.clear();
76 state.remote = { mode: "local-exec" };
77 state.clientEditors = editors;
@@ -84,94 +81,103 @@ beforeEach(() => {
81 state.markHintSeen.mockReset();
82 state.listeners.clear();
83 window.localStorage.clear();
87 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
88 - vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
89 - container = document.createElement("div");
90 - document.body.append(container);
91 - root = createRoot(container);
92 -});
84
94 -afterEach(async () => {
95 - await act(async () => root.unmount());
96 - document.body.replaceChildren();
97 - window.localStorage.clear();
98 - vi.restoreAllMocks();
99 - vi.unstubAllGlobals();
100 -});
85 + await using stack = new AsyncDisposableStack();
86 + const _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
87 + stack.use(_platform);
88 + const _storage = { [Symbol.dispose]: () => window.localStorage.clear() };
89 + stack.use(_storage);
90 + const screen = stack.use(await renderUi(null));
91 + async function renderPicker(
92 + availableEditors: readonly EditorId[] = editors,
93 + panel = false,
94 + { openInCwd = "/work/project", revealFileManager = false } = {},
95 + ) {
96 + await act(async () => {
97 + for (const listener of state.listeners) listener();
98 + const node = (
99 + <OpenInPicker
100 + environmentId={selected}
101 + keybindings={DEFAULT_RESOLVED_KEYBINDINGS}
102 + availableEditors={availableEditors}
103 + openInCwd={openInCwd}
104 + revealFileManager={revealFileManager}
105 + displayMode={panel ? "panel" : "toolbar"}
106 + compact={!panel}
107 + />
108 + );
109 + await screen.rerender(node);
110 + });
111 + }
112
102 -async function renderPicker(
103 - availableEditors: readonly EditorId[] = editors,
104 - panel = false,
105 - { openInCwd = "/work/project", revealFileManager = false } = {},
106 -) {
107 - await act(async () => {
108 - for (const listener of state.listeners) listener();
109 - const node = (
110 - <OpenInPicker
111 - environmentId={selected}
112 - keybindings={DEFAULT_RESOLVED_KEYBINDINGS}
113 - availableEditors={availableEditors}
114 - openInCwd={openInCwd}
115 - revealFileManager={revealFileManager}
116 - displayMode={panel ? "panel" : "toolbar"}
117 - compact={!panel}
118 - />
119 - );
120 - root.render(node);
121 - });
122 -}
113 + function byLabel(label: string) {
114 + const element = document.querySelector<HTMLButtonElement>(`[aria-label="${label}"]`);
115 + expect(element, label).not.toBeNull();
116 + return element!;
117 + }
118
124 -function byLabel(label: string) {
125 - const element = document.querySelector<HTMLButtonElement>(`[aria-label="${label}"]`);
126 - expect(element, label).not.toBeNull();
127 - return element!;
128 -}
119 + const primaryButton = () => byLabel("Open file in preferred editor");
120 + const menuItems = () => [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];
121
130 -const primaryButton = () => byLabel("Open file in preferred editor");
131 -const menuItems = () => [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];
122 + async function click(element: HTMLElement) {
123 + await act(async () => element.click());
124 + }
125
133 -async function click(element: HTMLElement) {
134 - await act(async () => element.click());
135 -}
126 + async function pressOpenFavorite(mac = false) {
127 + const event = new KeyboardEvent("keydown", {
128 + key: "o",
129 + ctrlKey: !mac,
130 + metaKey: mac,
131 + bubbles: true,
132 + cancelable: true,
133 + });
134 + await act(async () => document.body.dispatchEvent(event));
135 + return event;
136 + }
137
137 -async function pressOpenFavorite(mac = false) {
138 - const event = new KeyboardEvent("keydown", {
139 - key: "o",
140 - ctrlKey: !mac,
141 - metaKey: mac,
142 - bubbles: true,
143 - cancelable: true,
144 - });
145 - await act(async () => document.body.dispatchEvent(event));
146 - return event;
147 -}
138 + function FavoriteEditorFallback() {
139 + useOpenFavoriteEditorShortcut({
140 + enabled: true,
141 + environmentId: selected,
142 + keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
143 + availableEditors: editors,
144 + openInCwd: "/work/project",
145 + });
146 + return null;
147 + }
148
149 -function FavoriteEditorFallback() {
150 - useOpenFavoriteEditorShortcut({
151 - enabled: true,
152 - environmentId: selected,
153 - keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
154 - availableEditors: editors,
155 - openInCwd: "/work/project",
156 - });
157 - return null;
149 + const environment = stack.move();
150 + return {
151 + screen,
152 + renderPicker,
153 + byLabel,
154 + primaryButton,
155 + menuItems,
156 + click,
157 + pressOpenFavorite,
158 + FavoriteEditorFallback,
159 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
160 + };
161 }
159 -
162 it.each(["local-exec", "remote-links"] as const)(
163 "opens exactly one %s target as the file preview and workspace pickers mount and unmount",
164 async (mode) => {
165 + await using fixture = await setup();
166 + const { screen, pressOpenFavorite, FavoriteEditorFallback } = fixture;
167 state.allowed.add(selected);
168 state.remote =
169 mode === "local-exec" ? { mode } : { mode, host: { kind: "ssh-alias", host: "test-host" } };
170 const mac = mode === "remote-links";
167 - vi.spyOn(navigator, "platform", "get").mockReturnValue(mac ? "MacIntel" : "Linux");
171 + using _platform = vi
172 + .spyOn(navigator, "platform", "get")
173 + .mockReturnValue(mac ? "MacIntel" : "Linux");
174 const surfaces = ["workspace", "file", "workspace"];
175 if (mode === "local-exec") surfaces.push("fallback");
176
177 for (const surface of surfaces) {
178 const previewVisible = surface === "file";
179 await act(async () => {
174 - root.render(
180 + await screen.rerender(
181 <>
182 {/* Mount the fallback first so picker priority cannot rely on listener order. */}
183 <FavoriteEditorFallback />
@@ -221,10 +227,12 @@ it.each(["local-exec", "remote-links"] as const)(
227 it.each(["remote-links", "remote-unavailable"] as const)(
228 "does not launch an editor from the %s fallback when no picker is mounted",
229 async (mode) => {
230 + await using fixture = await setup();
231 + const { screen, pressOpenFavorite, FavoriteEditorFallback } = fixture;
232 state.allowed.add(selected);
233 state.remote =
234 mode === "remote-links" ? { mode, host: { kind: "ssh-alias", host: "test-host" } } : { mode };
227 - await act(async () => root.render(<FavoriteEditorFallback />));
235 + await act(async () => screen.rerender(<FavoriteEditorFallback />));
236
237 await pressOpenFavorite();
238
@@ -236,6 +244,8 @@ it.each(["remote-links", "remote-unavailable"] as const)(
244 it.each(["local-exec", "remote-links"] as const)(
245 "selects the preferred editor without launching a %s workspace",
246 async (mode) => {
247 + await using fixture = await setup();
248 + const { renderPicker, byLabel, menuItems, click } = fixture;
249 state.allowed.add(selected);
250 state.clientEditors = ["cursor", "vscode"];
251 state.remote =
@@ -265,6 +275,8 @@ it.each(["local-exec", "remote-links"] as const)(
275
276 describe("host editor access", () => {
277 it("uses the selected grant for both the button and a retained shortcut", async () => {
278 + await using fixture = await setup();
279 + const { renderPicker, byLabel, primaryButton, click, pressOpenFavorite } = fixture;
280 state.allowed.add(selected);
281 await renderPicker();
282 // Revoke without rerendering: the mounted button and shortcut must re-check the grant.
@@ -283,6 +295,8 @@ describe("host editor access", () => {
295 });
296
297 it("closes an open picker on revocation and launches only after a fresh grant", async () => {
298 + await using fixture = await setup();
299 + const { renderPicker, byLabel, primaryButton, menuItems, click } = fixture;
300 state.allowed.add(selected);
301 await renderPicker();
302 await click(byLabel("Choose editor"));
@@ -303,6 +317,8 @@ describe("host editor access", () => {
317 });
318
319 it("reveals a file in the file manager instead of opening it", async () => {
320 + await using fixture = await setup();
321 + const { renderPicker, primaryButton, click } = fixture;
322 state.allowed.add(selected);
323 await renderPicker(["file-manager"], false, {
324 openInCwd: "/work/project/README.md",
@@ -317,6 +333,8 @@ it("reveals a file in the file manager instead of opening it", async () => {
333
334 describe("client editor links", () => {
335 it("opens an SSH editor URL without host operate permission", async () => {
336 + await using fixture = await setup();
337 + const { renderPicker, primaryButton, click } = fixture;
338 state.remote = { mode: "remote-links", host: { kind: "ssh-alias", host: "test-host" } };
339 await renderPicker();
340 expect(primaryButton().disabled).toBe(false);
@@ -330,6 +348,8 @@ describe("client editor links", () => {
348 });
349
350 it("does not change preferences when the client rejects the SSH URL", async () => {
351 + await using fixture = await setup();
352 + const { renderPicker, pressOpenFavorite } = fixture;
353 state.remote = { mode: "remote-links", host: { kind: "ssh-alias", host: "test-host" } };
354 state.openUrl.mockResolvedValue(false);
355 await renderPicker();
apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx
+13 -35
@@ -6,13 +6,13 @@ import {
6 } from "@t3tools/contracts";
7 import { RegistryContext, useAtomSet, useAtomValue } from "@effect/atom-react";
8 import { Atom, AtomRegistry } from "effect/reactivity";
9 -import { act, type ReactNode } from "react";
10 -import { createRoot, type Root } from "react-dom/client";
11 -import { afterEach, describe, expect, it, vi } from "vite-plus/test";
9 +import type { ReactNode } from "react";
10 +import { describe, expect, it, vi } from "vite-plus/test";
11 import { page, userEvent } from "vite-plus/test/browser";
12
13 import "~/index.css";
14
15 +import { act, render as renderUi } from "../../../test/render";
16 import { deriveProviderInstanceEntries } from "../../providerInstances";
17 import { ProviderModelPicker } from "./ProviderModelPicker";
18 import type { ModelEsque } from "./providerIconUtils";
@@ -37,14 +37,6 @@ vi.mock(import("~/hooks/useSettings"), async (original) => ({
37 },
38 }));
39
40 -vi.mock(import("@tanstack/react-router"), async (original) => ({
41 - ...(await original()),
42 - useNavigate: () => vi.fn(),
43 -}));
44 -
45 -let pickerRoot: Root | undefined;
46 -let pickerRegistry: AtomRegistry.AtomRegistry | undefined;
47 -
40 function providerEntry(instanceId: string, driver: string) {
41 const provider: ServerProvider = {
42 instanceId: ProviderInstanceId.make(instanceId),
@@ -62,25 +54,10 @@ function providerEntry(instanceId: string, driver: string) {
54 return deriveProviderInstanceEntries([provider])[0]!;
55 }
56
65 -afterEach(async () => {
66 - if (pickerRoot) await act(async () => pickerRoot!.unmount());
67 - pickerRoot = undefined;
68 - pickerRegistry?.dispose();
69 - pickerRegistry = undefined;
70 - document.body.replaceChildren();
71 - vi.unstubAllGlobals();
72 -});
73 -
57 // Returns the trigger's visible text, which is what the user reads before opening the picker.
58 async function triggerText(node: ReactNode) {
76 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
77 - const container = document.createElement("div");
78 - document.body.append(container);
79 - const root = createRoot(container);
80 - await act(async () => root.render(node));
81 - const text = container.querySelector("button")?.textContent ?? "";
82 - await act(async () => root.unmount());
83 - return text;
59 + await using screen = await renderUi(node);
60 + return screen.container.querySelector("button")?.textContent ?? "";
61 }
62
63 function renderPicker(input: {
@@ -112,16 +89,16 @@ async function click(target: Parameters<typeof userEvent.click>[0]) {
89 }
90
91 async function openLegacyPicker(activeModel: string) {
115 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
92 const entry = providerEntry("codex", "codex");
117 - pickerRegistry = AtomRegistry.make();
93 + await using stack = new AsyncDisposableStack();
94 + const pickerRegistry = AtomRegistry.make();
95 + stack.defer(() => pickerRegistry.dispose());
96 pickerRegistry.set(favoritesAtom, [
97 { provider: entry.instanceId, model: "current-favorite" },
98 { provider: entry.instanceId, model: "legacy-favorite" },
99 ]);
122 - pickerRoot = createRoot(document.body.appendChild(document.createElement("div")));
123 - await act(async () =>
124 - pickerRoot!.render(
100 + stack.use(
101 + await renderUi(
102 <RegistryContext.Provider value={pickerRegistry!}>
103 <ProviderModelPicker
104 environmentId={null}
@@ -149,11 +126,12 @@ async function openLegacyPicker(activeModel: string) {
126 );
127 await click(document.querySelector("button")!);
128 await click(page.getByRole("button", { name: entry.displayName, exact: true }));
129 + return stack.move();
130 }
131
132 describe("ProviderModelPicker", () => {
133 it("hoists legacy favorites in provider order and returns an unfavorited model to legacy", async () => {
156 - await openLegacyPicker("current");
134 + await using _screen = await openLegacyPicker("current");
135 const legacyFavorite = page.getByRole("option", { name: /Legacy favorite/ });
136 const currentFavorite = page.getByRole("option", { name: /Current favorite/ });
137 const current = page.getByRole("option", { name: /Current model/ });
@@ -183,7 +161,7 @@ describe("ProviderModelPicker", () => {
161 });
162
163 it("keeps unrelated legacy models collapsed when the active model is a favorite", async () => {
186 - await openLegacyPicker("legacy-favorite");
164 + await using _screen = await openLegacyPicker("legacy-favorite");
165
166 await expect.element(page.getByRole("option", { name: /Legacy favorite/ })).toBeVisible();
167 await expect
apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx
+32 -34
@@ -1,8 +1,7 @@
1 import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
2 import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
3 -import { act, type ComponentProps } from "react";
4 -import { createRoot, type Root } from "react-dom/client";
5 -import { afterEach, describe, expect, it, vi } from "vite-plus/test";
3 +import type { ComponentProps } from "react";
4 +import { describe, expect, it, vi } from "vite-plus/test";
5 import { page } from "vite-plus/test/browser";
6
7 const state = vi.hoisted(() => ({
@@ -31,17 +30,13 @@ vi.mock(import("../../assets/assetUrls"), async (importOriginal) => ({
30 resources.map((resource) => `https://assets.test/${resource.attachmentId}`)) as never,
31 }));
32
33 +import { act, render as renderUi } from "../../../test/render";
34 import { QueuedRunsControl } from "./QueuedRunsControl";
35
36 -const roots: Root[] = [];
37 -
38 -afterEach(async () => {
39 - await act(async () => {
40 - for (const root of roots.splice(0)) root.unmount();
41 - });
42 - document.body.replaceChildren();
43 - vi.unstubAllGlobals();
44 -});
36 +function setup() {
37 + state.projection = null;
38 + state.workflow = null;
39 +}
40
41 const baseProps = {
42 environmentId: "environment:test" as never,
@@ -52,14 +47,8 @@ const baseProps = {
47 onCancelEdit: () => undefined,
48 } satisfies ComponentProps<typeof QueuedRunsControl>;
49
55 -async function render(props: Partial<ComponentProps<typeof QueuedRunsControl>> = {}) {
56 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
57 - const container = document.createElement("div");
58 - document.body.append(container);
59 - const root = createRoot(container);
60 - roots.push(root);
61 - await act(async () => root.render(<QueuedRunsControl {...baseProps} {...props} />));
62 - return container;
50 +async function renderQueue(props: Partial<ComponentProps<typeof QueuedRunsControl>> = {}) {
51 + return renderUi(<QueuedRunsControl {...baseProps} {...props} />);
52 }
53
54 const labels = (container: HTMLElement) =>
@@ -69,6 +58,7 @@ const labels = (container: HTMLElement) =>
58
59 describe("QueuedRunsControl automatic completion delivery", () => {
60 it("does not render a queue control when only hidden delivery remains", async () => {
61 + setup();
62 state.projection = {
63 projection: {
64 messages: [
@@ -90,9 +80,9 @@ describe("QueuedRunsControl automatic completion delivery", () => {
80 queuedRuns: [],
81 };
82
93 - const view = await render();
83 + await using screen = await renderQueue();
84
95 - expect(view.childElementCount).toBe(0);
85 + expect(screen.container.childElementCount).toBe(0);
86 });
87 });
88
@@ -119,19 +109,25 @@ describe("QueuedRunsControl attachments and edit mode", () => {
109 });
110
111 it("renders an attachment thumbnail on the queued row", async () => {
112 + setup();
113 state.projection = { projection: { messages: [] } };
114 state.workflow = workflowWithAttachment();
115
125 - const view = await render();
126 -
127 - expect(view.querySelector("img")?.getAttribute("src")).toBe("https://assets.test/attachment-1");
128 - expect(view.textContent).toContain("Queued with a screenshot");
129 - expect(labels(view)).toContain("Edit queued message");
130 - expect(labels(view)).toContain("Reorder queued message (drag, or press the arrow keys)");
131 - expect(labels(view)).not.toContain("Move queued message up");
116 + await using screen = await renderQueue();
117 +
118 + expect(screen.container.querySelector("img")?.getAttribute("src")).toBe(
119 + "https://assets.test/attachment-1",
120 + );
121 + expect(screen.container.textContent).toContain("Queued with a screenshot");
122 + expect(labels(screen.container)).toContain("Edit queued message");
123 + expect(labels(screen.container)).toContain(
124 + "Reorder queued message (drag, or press the arrow keys)",
125 + );
126 + expect(labels(screen.container)).not.toContain("Move queued message up");
127 });
128
129 it("drops the optimistic pending row once the projection holds its message", async () => {
130 + setup();
131 state.projection = {
132 projection: { messages: [{ id: "message:acknowledged", text: "hello" }] },
133 };
@@ -142,7 +138,7 @@ describe("QueuedRunsControl attachments and edit mode", () => {
138 queuedRuns: [],
139 };
140
145 - const view = await render({
141 + await using screen = await renderQueue({
142 optimisticMessages: [
143 {
144 id: "message:acknowledged" as never,
@@ -153,20 +149,22 @@ describe("QueuedRunsControl attachments and edit mode", () => {
149 ],
150 });
151
156 - expect(view.childElementCount).toBe(0);
152 + expect(screen.container.childElementCount).toBe(0);
153 });
154
155 it("keeps the original queued message visible while editing", async () => {
156 + setup();
157 state.projection = { projection: { messages: [] } };
158 state.workflow = workflowWithAttachment();
159
163 - const view = await render({ editingRunId: "run:queued" as never });
160 + await using screen = await renderQueue({ editingRunId: "run:queued" as never });
161
165 - expect(view.textContent).toContain("Queued with a screenshot");
162 + expect(screen.container.textContent).toContain("Queued with a screenshot");
163 });
164 });
165
166 it("previews assistant quotes as readable text and preserves the citation when editing", async () => {
167 + setup();
168 const quotedText = "Cache the parsed config per worktree.";
169 const quote = serializeAssistantCitation({
170 version: 1,
@@ -199,7 +197,7 @@ it("previews assistant quotes as readable text and preserves the citation when e
197 ],
198 };
199 const onEditQueuedRun = vi.fn();
202 - await render({ onEditQueuedRun });
200 + await using _screen = await renderQueue({ onEditQueuedRun });
201
202 await expect.element(page.getByText(quotedText, { exact: true })).toBeVisible();
203 await expect
apps/web/src/components/chat/ThreadAutomationsPanel.permissions.browser.test.tsx
+24 -22
@@ -1,7 +1,5 @@
1 import { EnvironmentId, ThreadId, ScheduledTaskId, type ScheduledTask } from "@t3tools/contracts";
2 -import { act } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
2 +import { expect, it, vi } from "vite-plus/test";
3
4 const state = vi.hoisted(() => ({ allowed: true, toggle: vi.fn(), run: vi.fn() }));
5 vi.mock(import("../../state/session"), async (importOriginal) => ({
@@ -31,6 +29,7 @@ vi.mock(import("../../state/query"), async (importOriginal) => ({
29 useEnvironmentQuery: (() => ({ data: { tasks: [task] }, error: null })) as never,
30 }));
31
32 +import { act, render as renderUi } from "../../../test/render";
33 import { ThreadAutomationsPanel } from "./ThreadAutomationsPanel";
34 const environmentId = EnvironmentId.make("remote");
35 const threadId = ThreadId.make("thread");
@@ -42,32 +41,33 @@ const task = {
41 schedule: { type: "interval", everyMs: 60000 },
42 lastRunStatus: "never",
43 } as ScheduledTask;
45 -let root: Root;
46 -let container: HTMLDivElement;
47 -beforeEach(() => {
48 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
44 +
45 +async function setup() {
46 state.allowed = true;
47 state.toggle.mockReset().mockResolvedValue({ _tag: "Success" });
48 state.run.mockReset().mockResolvedValue({ _tag: "Success" });
52 - container = document.createElement("div");
53 - document.body.append(container);
54 - root = createRoot(container);
55 -});
56 -afterEach(async () => {
57 - await act(async () => root.unmount());
58 - container.remove();
59 - vi.unstubAllGlobals();
60 -});
49
62 -async function renderPanel() {
63 - await act(async () =>
64 - root.render(<ThreadAutomationsPanel environmentId={environmentId} threadId={threadId} />),
65 - );
66 -}
50 + await using stack = new AsyncDisposableStack();
51 + const screen = stack.use(await renderUi(null));
52 + const container = screen.container;
53 + async function renderPanel() {
54 + await act(
55 + async () =>
56 + await screen.rerender(
57 + <ThreadAutomationsPanel environmentId={environmentId} threadId={threadId} />,
58 + ),
59 + );
60 + }
61
68 -const byLabel = (label: string) => container.querySelector<HTMLElement>(`[aria-label="${label}"]`)!;
62 + const byLabel = (label: string) =>
63 + container.querySelector<HTMLElement>(`[aria-label="${label}"]`)!;
64
65 + const environment = stack.move();
66 + return { renderPanel, byLabel, [Symbol.asyncDispose]: () => environment.disposeAsync() };
67 +}
68 it.each([true, false])("runs scheduled work only with task permission (%s)", async (allowed) => {
69 + await using fixture = await setup();
70 + const { renderPanel, byLabel } = fixture;
71 state.allowed = allowed;
72 await renderPanel();
73 await act(async () => byLabel("Run Daily review now").click());
@@ -75,6 +75,8 @@ it.each([true, false])("runs scheduled work only with task permission (%s)", asy
75 });
76
77 it("rejects a retained toggle after task permission is revoked", async () => {
78 + await using fixture = await setup();
79 + const { renderPanel, byLabel } = fixture;
80 await renderPanel();
81 state.allowed = false;
82 await act(async () => byLabel("Pause Daily review").click());
apps/web/src/components/chat/ThreadDetailsControl.browser.test.tsx
+16 -30
@@ -1,36 +1,22 @@
1 -import { act } from "react";
2 -import { createRoot } from "react-dom/client";
3 -import { expect, it, vi } from "vite-plus/test";
1 +import { expect, it } from "vite-plus/test";
2
3 +import { act, render as renderUi } from "../../../test/render";
4 import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
5 import { ThreadDetailsControl } from "./ThreadDetailsControl";
6
7 it("keeps the row label and one chevron when used as a menu trigger", async () => {
9 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
10 - const container = document.createElement("div");
11 - document.body.append(container);
12 - const root = createRoot(container);
13 - try {
14 - await act(async () => {
15 - root.render(
16 - <Menu>
17 - <MenuTrigger render={<ThreadDetailsControl part="select" />}>
18 - Run on this machine
19 - </MenuTrigger>
20 - <MenuPopup>
21 - <MenuItem>New worktree</MenuItem>
22 - </MenuPopup>
23 - </Menu>,
24 - );
25 - });
26 - const trigger = container.querySelector("button")!;
27 - expect(trigger.textContent).toBe("Run on this machine");
28 - expect(trigger.querySelectorAll(".lucide-chevron-down")).toHaveLength(1);
29 - await act(async () => trigger.click());
30 - expect(document.querySelector('[role="menuitem"]')?.textContent).toBe("New worktree");
31 - } finally {
32 - await act(async () => root.unmount());
33 - container.remove();
34 - vi.unstubAllGlobals();
35 - }
8 + await using screen = await renderUi(
9 + <Menu>
10 + <MenuTrigger render={<ThreadDetailsControl part="select" />}>Run on this machine</MenuTrigger>
11 + <MenuPopup>
12 + <MenuItem>New worktree</MenuItem>
13 + </MenuPopup>
14 + </Menu>,
15 + );
16 + const { container } = screen;
17 + const trigger = container.querySelector("button")!;
18 + expect(trigger.textContent).toBe("Run on this machine");
19 + expect(trigger.querySelectorAll(".lucide-chevron-down")).toHaveLength(1);
20 + await act(async () => trigger.click());
21 + expect(document.querySelector('[role="menuitem"]')?.textContent).toBe("New worktree");
22 });
apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx
+52 -56
@@ -9,9 +9,7 @@ import {
9 import * as Cause from "effect/Cause";
10 import { DraftId } from "~/composerDraftStore";
11 import { AsyncResult } from "effect/reactivity";
12 -import { act } from "react";
13 -import { createRoot, type Root } from "react-dom/client";
14 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
12 +import { expect, it, vi } from "vite-plus/test";
13 import { userEvent } from "vite-plus/test/browser";
14
15 const state = vi.hoisted(() => ({
@@ -106,33 +104,12 @@ vi.mock(import("../ui/toast"), async (original) => {
104 };
105 });
106
107 +import { act, render as renderUi } from "../../../test/render";
108 import { ThreadDetailsPrRow } from "./ThreadDetailsPrRow";
109
111 -let root: Root;
112 -let container: HTMLDivElement;
113 -beforeEach(() => {
114 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
115 - container = document.createElement("div");
116 - document.body.append(container);
117 - root = createRoot(container);
118 - state.checkoutError = null;
119 - state.newThread.mockReset().mockResolvedValue({
120 - draftId: DraftId.make("new-draft"),
121 - threadId: ThreadId.make("new-thread"),
122 - });
123 - state.prepareThread.mockReset();
124 - state.addToast.mockReset().mockReturnValue("checkout-toast");
125 - state.updateToast.mockReset();
126 -});
127 -afterEach(() => {
128 - act(() => root.unmount());
129 - document.body.replaceChildren();
130 - vi.unstubAllGlobals();
131 - state.status = "success";
132 - state.extraStatus = null;
133 -});
134 -
135 -it("requires a new merge click after passing checks become pending and pass again", () => {
110 +it("requires a new merge click after passing checks become pending and pass again", async () => {
111 + await using screen = await setup();
112 + const { container } = screen;
113 const render = () => (
114 <ThreadDetailsPrRow
115 environmentId={EnvironmentId.make("environment")}
@@ -145,28 +122,28 @@ it("requires a new merge click after passing checks become pending and pass agai
122 onOpen={vi.fn()}
123 />
124 );
148 - const clickMerge = () =>
149 - act(() => {
125 + const clickMerge = async () =>
126 + await act(async () => {
127 [...container.querySelectorAll("button")]
128 .find((button) => button.textContent?.trim() === "Merge")!
129 .click();
130 });
131 const dialogs = () => [...document.querySelectorAll('[role="alertdialog"]')];
132
156 - act(() => root.render(render()));
157 - clickMerge();
133 + await act(async () => await screen.rerender(render()));
134 + await clickMerge();
135 expect(dialogs()).toHaveLength(1);
159 - act(() => {
136 + await act(async () => {
137 state.status = "pending";
161 - root.render(render());
138 + await screen.rerender(render());
139 });
140 expect(dialogs()).toHaveLength(0);
164 - act(() => {
141 + await act(async () => {
142 state.status = "success";
166 - root.render(render());
143 + await screen.rerender(render());
144 });
145 expect(dialogs()).toHaveLength(0);
169 - clickMerge();
146 + await clickMerge();
147 expect(dialogs()).toHaveLength(1);
148 expect(state.perform).not.toHaveBeenCalled();
149 });
@@ -182,11 +159,13 @@ it.each<[PullRequestCheck["status"], PullRequestCheck["status"], string]>([
159 ["neutral", "pending", "1/2"],
160 ["failure", "pending", "1/2"],
161 ["cancelled", "pending", "1/2"],
185 -])("counts finished checks while work remains (%s, %s)", (status, extraStatus, count) => {
162 +])("counts finished checks while work remains (%s, %s)", async (status, extraStatus, count) => {
163 + await using screen = await setup();
164 + const { container } = screen;
165 state.status = status;
166 state.extraStatus = extraStatus;
188 - act(() => {
189 - root.render(
167 + await act(async () => {
168 + await screen.rerender(
169 <ThreadDetailsPrRow
170 environmentId={EnvironmentId.make("environment")}
171 pr={null}
@@ -206,6 +185,8 @@ it.each<[PullRequestCheck["status"], PullRequestCheck["status"], string]>([
185 });
186
187 it("shows the current checkout recovery detail when fixing checks fails and is retried", async () => {
188 + await using screen = await setup();
189 + const { container } = screen;
190 state.status = "failure";
191 const first = new GitManagerError({
192 cwd: "/workspace",
@@ -219,7 +200,7 @@ it("shows the current checkout recovery detail when fixing checks fails and is r
200 detail: "The worktree directory already exists. Choose another directory.",
201 });
202 await act(async () => {
222 - root.render(
203 + await screen.rerender(
204 <ThreadDetailsPrRow
205 environmentId={EnvironmentId.make("environment")}
206 pr={null}
@@ -251,23 +232,38 @@ it("shows the current checkout recovery detail when fixing checks fails and is r
232 });
233
234 it("splits the change by file kind in the hover card", async () => {
254 - act(() =>
255 - root.render(
256 - <ThreadDetailsPrRow
257 - environmentId={EnvironmentId.make("environment")}
258 - pr={null}
259 - number={1}
260 - reference={{ repository: "owner/repo", number: 1 }}
261 - status={null}
262 - project={{ id: ProjectId.make("project"), repositoryIdentity: null } as never}
263 - label="Test PR"
264 - openAriaLabel="Open PR"
265 - onOpen={vi.fn()}
266 - />,
267 - ),
235 + await using screen = await setup();
236 + await screen.rerender(
237 + <ThreadDetailsPrRow
238 + environmentId={EnvironmentId.make("environment")}
239 + pr={null}
240 + number={1}
241 + reference={{ repository: "owner/repo", number: 1 }}
242 + status={null}
243 + project={{ id: ProjectId.make("project"), repositoryIdentity: null } as never}
244 + label="Test PR"
245 + openAriaLabel="Open PR"
246 + onOpen={vi.fn()}
247 + />,
248 );
269 - await act(() => userEvent.hover(container.querySelector('button[aria-label="Open PR"]')!));
249 + await userEvent.hover(screen.getByRole("button", { name: "Open PR" }));
250 await expect
251 .poll(() => document.querySelector('[data-slot="tooltip-popup"][data-open]')?.textContent)
252 .toMatch(/Docs\+7-3/);
253 });
254 +
255 +async function setup() {
256 + state.perform.mockReset();
257 + state.checkoutError = null;
258 + state.newThread.mockReset().mockResolvedValue({
259 + draftId: DraftId.make("new-draft"),
260 + threadId: ThreadId.make("new-thread"),
261 + });
262 + state.prepareThread.mockReset();
263 + state.addToast.mockReset().mockReturnValue("checkout-toast");
264 + state.updateToast.mockReset();
265 +
266 + state.status = "success";
267 + state.extraStatus = null;
268 + return renderUi(null);
269 +}
apps/web/src/components/chat/ThreadDetailsPrRows.browser.test.tsx
+74 -60
@@ -1,7 +1,6 @@
1 import { EnvironmentId, ProjectId, ThreadId, type ThreadPullRequestLink } from "@t3tools/contracts";
2 -import { act, type ComponentProps } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
2 +import type { ComponentProps } from "react";
3 +import { expect, it, vi } from "vite-plus/test";
4 import { page, userEvent } from "vite-plus/test/browser";
5 import "~/index.css";
6
@@ -79,6 +78,7 @@ vi.mock(import("../BranchToolbarBranchSelector"), () => ({
78 ),
79 }));
80
81 +import { act, render as renderUi } from "../../../test/render";
82 import { PopoverCreateHandle } from "../ui/popover";
83 import { ThreadDetailsPanel } from "./ThreadDetailsPanel";
84 import { ThreadDetailsPrRows } from "./ThreadDetailsPrRows";
@@ -121,79 +121,91 @@ const bottom = link(1, "layer-one", "main", "2026-01-01T00:00:10.000Z");
121 const top = link(2, "layer-two", "layer-one", "2026-01-01T00:00:20.000Z");
122 const other = link(3, "unrelated", "main", "2026-01-01T00:00:05.000Z");
123
124 -let root: Root;
125 -let container: HTMLDivElement;
126 -beforeEach(() => {
127 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
128 - container = document.createElement("div");
129 - document.body.append(container);
130 - root = createRoot(container);
131 -});
132 -afterEach(() => {
133 - act(() => root.unmount());
134 - container.remove();
135 - vi.unstubAllGlobals();
124 +async function setup() {
125 fixture.realRows = false;
137 -});
126 + watchCommand.mockReset();
127 + await using stack = new AsyncDisposableStack();
128 + const screen = stack.use(await renderUi(null));
129 + const container = screen.container;
130 + async function render(
131 + links: ReadonlyArray<ThreadPullRequestLink>,
132 + current: ThreadPullRequestLink,
133 + ) {
134 + await act(async () => {
135 + await screen.rerender(
136 + <ThreadDetailsPrRows
137 + threadRef={{
138 + environmentId: EnvironmentId.make("environment"),
139 + threadId: ThreadId.make("thread"),
140 + }}
141 + links={links}
142 + currentLink={current}
143 + onOpenLink={vi.fn()}
144 + environmentId={EnvironmentId.make("environment")}
145 + pr={null}
146 + number={current.number}
147 + reference={current}
148 + status={null}
149 + project={null}
150 + label={`#${current.number}`}
151 + openAriaLabel="Open pull request"
152 + onOpen={vi.fn()}
153 + />,
154 + );
155 + });
156 + }
157
139 -function render(links: ReadonlyArray<ThreadPullRequestLink>, current: ThreadPullRequestLink) {
140 - act(() => {
141 - root.render(
142 - <ThreadDetailsPrRows
143 - threadRef={{
144 - environmentId: EnvironmentId.make("environment"),
145 - threadId: ThreadId.make("thread"),
146 - }}
147 - links={links}
148 - currentLink={current}
149 - onOpenLink={vi.fn()}
150 - environmentId={EnvironmentId.make("environment")}
151 - pr={null}
152 - number={current.number}
153 - reference={current}
154 - status={null}
155 - project={null}
156 - label={`#${current.number}`}
157 - openAriaLabel="Open pull request"
158 - onOpen={vi.fn()}
159 - />,
158 + const rows = () =>
159 + [...container.querySelectorAll("[data-row]")].map((node) => node.getAttribute("data-row"));
160 + const toggleButton = () =>
161 + [...container.querySelectorAll("button")].find((button) =>
162 + /^(Show \d+ more|Show less)$/.test(button.textContent?.trim() ?? ""),
163 );
161 - });
162 -}
164 + const toggleLabel = () => toggleButton()?.textContent?.trim();
165
164 -const rows = () =>
165 - [...container.querySelectorAll("[data-row]")].map((node) => node.getAttribute("data-row"));
166 -const toggleButton = () =>
167 - [...container.querySelectorAll("button")].find((button) =>
168 - /^(Show \d+ more|Show less)$/.test(button.textContent?.trim() ?? ""),
169 - );
170 -const toggleLabel = () => toggleButton()?.textContent?.trim();
166 + async function toggle() {
167 + await act(() => toggleButton()!.click());
168 + }
169
172 -function toggle() {
173 - act(() => toggleButton()!.click());
170 + const environment = stack.move();
171 + return {
172 + screen,
173 + container,
174 + render,
175 + rows,
176 + toggleButton,
177 + toggleLabel,
178 + toggle,
179 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
180 + };
181 }
175 -
176 -it("shows only the current pull request until the rest are asked for", () => {
177 - render([other, bottom, top], top);
182 +it("shows only the current pull request until the rest are asked for", async () => {
183 + await using test = await setup();
184 + const { render, rows, toggleLabel, toggle } = test;
185 + await render([other, bottom, top], top);
186 expect(rows()).toEqual(["2"]);
187 expect(toggleLabel()).toBe("Show 2 more");
188
181 - toggle();
189 + await toggle();
190 expect(rows()).toEqual(["2", "1", "3"]);
191 expect(toggleLabel()).toBe("Show less");
192
185 - toggle();
193 + await toggle();
194 expect(rows()).toEqual(["2"]);
195 expect(toggleLabel()).toBe("Show 2 more");
196 });
197
190 -it("keeps the single row untouched when the thread links one pull request", () => {
191 - render([bottom], bottom);
198 +it("keeps the single row untouched when the thread links one pull request", async () => {
199 + await using test = await setup();
200 + const { render, rows, toggleLabel } = test;
201 + await render([bottom], bottom);
202 expect(rows()).toEqual(["1"]);
203 expect(toggleLabel()).toBeUndefined();
204 });
205
196 -it("lets only watched pull requests stop their watch", () => {
206 +it("lets only watched pull requests stop their watch", async () => {
207 + await using test = await setup();
208 + const { container, render, toggle } = test;
209 const watched: ThreadPullRequestLink = {
210 ...bottom,
211 watch: {
@@ -208,14 +220,14 @@ it("lets only watched pull requests stop their watch", () => {
220 wakes: 0,
221 },
222 };
211 - render([other, watched, top], top);
212 - toggle();
223 + await render([other, watched, top], top);
224 + await toggle();
225 const stopButtons = [...container.querySelectorAll("button")].filter((button) =>
226 button.textContent?.startsWith("Stop watching"),
227 );
228 expect(stopButtons.map((button) => button.textContent)).toEqual(["Stop watching #1"]);
229
218 - act(() => stopButtons[0]!.click());
230 + await act(() => stopButtons[0]!.click());
231 expect(watchCommand).toHaveBeenCalledWith({
232 environmentId: EnvironmentId.make("environment"),
233 input: {
@@ -229,10 +241,12 @@ it("lets only watched pull requests stop their watch", () => {
241 });
242
243 it("keeps workspace controls after expanding and collapsing 70 linked pull requests", async () => {
244 + await using test = await setup();
245 + const { screen, container } = test;
246 fixture.realRows = true;
247 container.style.cssText = "position:relative;width:1800px;height:500px";
248 await act(async () => {
235 - root.render(
249 + await screen.rerender(
250 <ThreadDetailsPanel
251 {...threadRef}
252 projectId={ProjectId.make("project")}
apps/web/src/components/chat/ThreadErrorBanner.browser.test.tsx
+13 -23
@@ -1,38 +1,28 @@
1 +import { act, render as renderUi } from "../../../test/render";
2 import "../../index.css";
3
3 -import { act } from "react";
4 -import { createRoot } from "react-dom/client";
5 -import { expect, it, vi } from "vite-plus/test";
4 +import { expect, it } from "vite-plus/test";
5 import { page } from "vite-plus/test/browser";
6
7 import { ThreadErrorBanner } from "./ThreadErrorBanner";
8
9 it("expands even a short JSON error to its exact diagnostics and collapses back to its message", async () => {
11 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
12 - const container = document.createElement("div");
13 - document.body.append(container);
14 - const root = createRoot(container);
10 const error = ' {"error": {"message":"Turn failed", "code":"unsupported_value"}}\t ';
11
17 - try {
18 - await act(async () => root.render(<ThreadErrorBanner error={error} />));
12 + await using screen = await renderUi(<ThreadErrorBanner error={error} />);
13 + const { container } = screen;
14
20 - await expect.element(page.getByText("Turn failed", { exact: true })).toBeVisible();
21 - expect(container.textContent).not.toContain("unsupported_value");
15 + await expect.element(page.getByText("Turn failed", { exact: true })).toBeVisible();
16 + expect(container.textContent).not.toContain("unsupported_value");
17
23 - await act(async () => page.getByRole("button", { name: "Show full error" }).click());
18 + await act(async () => page.getByRole("button", { name: "Show full error" }).click());
19
25 - const diagnostics = page.getByText(error, { exact: true });
26 - await expect.element(diagnostics).toBeVisible();
27 - expect(diagnostics.element().textContent).toBe(error);
20 + const diagnostics = page.getByText(error, { exact: true });
21 + await expect.element(diagnostics).toBeVisible();
22 + expect(diagnostics.element().textContent).toBe(error);
23
29 - await act(async () => page.getByRole("button", { name: "Show less" }).click());
24 + await act(async () => page.getByRole("button", { name: "Show less" }).click());
25
31 - await expect.element(page.getByText("Turn failed", { exact: true })).toBeVisible();
32 - expect(container.textContent).not.toContain("unsupported_value");
33 - } finally {
34 - await act(async () => root.unmount());
35 - container.remove();
36 - vi.unstubAllGlobals();
37 - }
26 + await expect.element(page.getByText("Turn failed", { exact: true })).toBeVisible();
27 + expect(container.textContent).not.toContain("unsupported_value");
28 });
apps/web/src/components/chat/ThreadFindProvider.browser.test.tsx
+8 -20
@@ -1,6 +1,5 @@
1 -import { act, createRef, useContext, useState, type ReactNode } from "react";
2 -import { createRoot } from "react-dom/client";
3 -import { afterEach, expect, it, vi } from "vite-plus/test";
1 +import { createRef, useContext, useState } from "react";
2 +import { expect, it, vi } from "vite-plus/test";
3 import {
4 EnvironmentId,
5 ThreadId,
@@ -12,6 +11,7 @@ import {
11 ThreadFindTimelineContext,
12 type ThreadFindControls,
13 } from "./ThreadFindProvider";
14 +import { act, render as renderUi } from "../../../test/render";
15 import type { ThreadFindBar } from "./ThreadFindBar";
16
17 const query = vi.hoisted(() => ({
@@ -51,23 +51,13 @@ vi.mock("~/state/query", async () => {
51 });
52 vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));
53
54 -type Rendered = { update: (node: ReactNode) => void; unmount: () => void };
55 -function render(node: ReactNode): Rendered {
56 - const root = createRoot(document.createElement("div"));
57 - root.render(node);
58 - return { update: (next) => root.render(next), unmount: () => root.unmount() };
59 -}
60 -
61 -let renderer: Rendered | undefined;
62 -afterEach(async () => {
63 - if (renderer) await act(async () => renderer?.unmount());
64 - renderer = undefined;
54 +function setup() {
55 query.listeners.clear();
66 - vi.unstubAllGlobals();
67 -});
56 + query.value = { data: null, isPending: false, error: null, refresh: vi.fn() };
57 +}
58
59 it("keeps navigation and pending responses out of the surrounding chat and unrelated children", async () => {
70 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
60 + setup();
61 const controls = createRef<ThreadFindControls>();
62 const parentRender = vi.fn();
63 const composerRender = vi.fn();
@@ -104,9 +94,7 @@ it("keeps navigation and pending responses out of the surrounding chat and unrel
94 match: { entryId: "message", runId: null, occurrence: index },
95 });
96 query.value = { ...query.value, data: response(0), isPending: false };
107 - await act(async () => {
108 - renderer = render(<Chat />);
109 - });
97 + await using _screen = await renderUi(<Chat />);
98 await act(async () => controls.current?.open());
99 await act(async () => bar.onQueryChange("COD4"));
100 const parentCount = parentRender.mock.calls.length;
apps/web/src/components/chat/ThreadRelationshipsControl.agents.browser.test.tsx
+90 -60
@@ -1,5 +1,4 @@
1 -import { act, cloneElement, type ReactElement, type ReactNode } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
1 +import { cloneElement, type ReactElement, type ReactNode } from "react";
2 import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3 import {
4 EnvironmentId,
@@ -10,7 +9,7 @@ import {
9 type OrchestrationV2ContextTransfer,
10 } from "@t3tools/contracts";
11 import * as DateTime from "effect/DateTime";
13 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
12 +import { expect, it, vi } from "vite-plus/test";
13
14 import "~/index.css";
15
@@ -96,64 +95,10 @@ vi.mock(import("../ui/tooltip"), async () => {
95 };
96 });
97
98 +import { act, render as renderUi } from "../../../test/render";
99 import { ThreadRelationshipsPanel } from "./ThreadRelationshipsControl";
100
101 -let root: Root;
102 -let container: HTMLDivElement;
103 -let current: ReactElement;
104 -
105 -async function render(element: ReactElement) {
106 - current = element;
107 - await act(async () => root.render(element));
108 -}
109 -// The mocked hooks read `state` while rendering, so a new element picks up changes.
110 -const update = () => act(async () => root.render(cloneElement(current)));
111 -const click = (element: HTMLElement) => act(async () => element.click());
112 -const buttons = () => [...container.querySelectorAll("button")];
113 -const allByLabel = (label: string) =>
114 - buttons().filter((button) => button.getAttribute("aria-label") === label);
115 -function byLabel(label: string) {
116 - const matches = allByLabel(label);
117 - if (matches.length !== 1)
118 - throw new Error(`Expected one "${label}" button, got ${matches.length}`);
119 - return matches[0]!;
120 -}
121 -const sectionToggles = (expanded: boolean) =>
122 - buttons().filter(
123 - (button) =>
124 - button.getAttribute("aria-expanded") === String(expanded) &&
125 - !button.hasAttribute("aria-label"),
126 - );
127 -function sectionToggle(expanded: boolean) {
128 - const [toggle] = sectionToggles(expanded);
129 - if (!toggle) throw new Error(`No ${expanded ? "expanded" : "collapsed"} section toggle`);
130 - return toggle;
131 -}
132 -const heading = () => container.querySelector("h3")?.textContent;
133 -const buttonsWithLabel = (matches: (label: string) => boolean) =>
134 - buttons().filter((button) => matches(button.getAttribute("aria-label") ?? ""));
135 -// Joins rendered text nodes; `visibleOnly` drops screen-reader-only text.
136 -function textNodes(separator: string, visibleOnly = false) {
137 - const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);
138 - const parts: string[] = [];
139 - for (let node = walker.nextNode(); node; node = walker.nextNode()) {
140 - if (visibleOnly && node.parentElement?.closest(".sr-only")) continue;
141 - parts.push(node.textContent ?? "");
142 - }
143 - return parts.join(separator);
144 -}
145 -
146 -beforeEach(() => {
147 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
148 - container = document.createElement("div");
149 - document.body.append(container);
150 - root = createRoot(container);
151 -});
152 -
153 -afterEach(async () => {
154 - await act(async () => root.unmount());
155 - container.remove();
156 - vi.unstubAllGlobals();
101 +async function setup() {
102 state.shells = [];
103 state.projects = [];
104 state.configs.clear();
@@ -164,9 +109,73 @@ afterEach(async () => {
109 state.toast.mockClear();
110 state.projection = null;
111 state.projections = null;
167 -});
112
113 + await using stack = new AsyncDisposableStack();
114 + const screen = stack.use(await renderUi(null));
115 + const container = screen.container;
116 + let current: ReactElement;
117 +
118 + async function render(element: ReactElement) {
119 + current = element;
120 + await act(async () => screen.rerender(element));
121 + }
122 + // The mocked hooks read `state` while rendering, so a new element picks up changes.
123 + const update = async () => await act(async () => screen.rerender(cloneElement(current)));
124 + const click = async (element: HTMLElement) => await act(async () => element.click());
125 + const buttons = () => [...container.querySelectorAll("button")];
126 + const allByLabel = (label: string) =>
127 + buttons().filter((button) => button.getAttribute("aria-label") === label);
128 + function byLabel(label: string) {
129 + const matches = allByLabel(label);
130 + if (matches.length !== 1)
131 + throw new Error(`Expected one "${label}" button, got ${matches.length}`);
132 + return matches[0]!;
133 + }
134 + const sectionToggles = (expanded: boolean) =>
135 + buttons().filter(
136 + (button) =>
137 + button.getAttribute("aria-expanded") === String(expanded) &&
138 + !button.hasAttribute("aria-label"),
139 + );
140 + function sectionToggle(expanded: boolean) {
141 + const [toggle] = sectionToggles(expanded);
142 + if (!toggle) throw new Error(`No ${expanded ? "expanded" : "collapsed"} section toggle`);
143 + return toggle;
144 + }
145 + const heading = () => container.querySelector("h3")?.textContent;
146 + const buttonsWithLabel = (matches: (label: string) => boolean) =>
147 + buttons().filter((button) => matches(button.getAttribute("aria-label") ?? ""));
148 + // Joins rendered text nodes; `visibleOnly` drops screen-reader-only text.
149 + function textNodes(separator: string, visibleOnly = false) {
150 + const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);
151 + const parts: string[] = [];
152 + for (let node = walker.nextNode(); node; node = walker.nextNode()) {
153 + if (visibleOnly && node.parentElement?.closest(".sr-only")) continue;
154 + parts.push(node.textContent ?? "");
155 + }
156 + return parts.join(separator);
157 + }
158 +
159 + const environment = stack.move();
160 + return {
161 + container,
162 + render,
163 + update,
164 + click,
165 + buttons,
166 + allByLabel,
167 + byLabel,
168 + sectionToggles,
169 + sectionToggle,
170 + heading,
171 + buttonsWithLabel,
172 + textNodes,
173 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
174 + };
175 +}
176 it("stops the entire native workflow through its parent without changing state before acknowledgement", async () => {
177 + await using fixture = await setup();
178 + const { render, click, byLabel, heading, buttonsWithLabel } = fixture;
179 const coordinator = {
180 id: "workflow",
181 origin: "provider_native",
@@ -264,6 +273,8 @@ it.each([
273 ["codex", "provider_native", "running"],
274 ["claudeAgent", "app_owned", "running"],
275 ])("does not offer workflow stop for %s %s %s", async (driver, origin, status) => {
276 + await using fixture = await setup();
277 + const { render, click, allByLabel, byLabel, sectionToggles } = fixture;
278 state.projection = {
279 thread: { id: "parent", lineage: { relationshipToParent: null } },
280 runs: [],
@@ -300,6 +311,8 @@ it.each([
311 });
312
313 it("opens the correct chat for every workflow phase and unphased member", async () => {
314 + await using fixture = await setup();
315 + const { render, update, click, byLabel, buttonsWithLabel, textNodes } = fixture;
316 state.showTooltips = true;
317 state.configs.set("remote", {
318 providers: [
@@ -433,6 +446,8 @@ it("opens the correct chat for every workflow phase and unphased member", async
446 });
447
448 it("groups and counts a workflow by its run status instead of its coordinator chat", async () => {
449 + await using fixture = await setup();
450 + const { render, update, click, allByLabel, byLabel, sectionToggle, heading, textNodes } = fixture;
451 state.showTooltips = true;
452 const coordinator = {
453 id: "workflow",
@@ -512,6 +527,8 @@ it.each([
527 ])(
528 "offers individual Stop for supported $origin $driver subagents with run $runId",
529 async ({ driver, origin, runId, canStop }) => {
530 + await using fixture = await setup();
531 + const { render, update, click, allByLabel, byLabel } = fixture;
532 const parent = {
533 id: "parent",
534 lineage: { relationshipToParent: null },
@@ -623,6 +640,9 @@ it.each([
640 );
641
642 it("shows the matching child agent details and refreshes them when the agent settles", async () => {
643 + await using fixture = await setup();
644 + const { render, update, click, buttons, sectionToggles, sectionToggle, heading, textNodes } =
645 + fixture;
646 const agent = {
647 id: "agent-1",
648 driver: "codex",
@@ -740,6 +760,8 @@ it("shows the matching child agent details and refreshes them when the agent set
760 });
761
762 it("keeps active supervisor status, progress, and task timing after its child turn ends", async () => {
763 + await using fixture = await setup();
764 + const { render, buttons, heading, textNodes, container } = fixture;
765 using _now = vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-09-16T12:05:15Z"));
766 state.showTooltips = true;
767 // The child request follows task creation by milliseconds, but finishing that
@@ -812,6 +834,8 @@ it("keeps active supervisor status, progress, and task timing after its child tu
834 });
835
836 it("shows readable models and only differing workspace details in agent tooltips", async () => {
837 + await using fixture = await setup();
838 + const { render, update, click, sectionToggle, textNodes } = fixture;
839 state.showTooltips = true;
840 const parent = {
841 id: "parent",
@@ -1229,6 +1253,8 @@ it("shows readable models and only differing workspace details in agent tooltips
1253 });
1254
1255 it("shows the parent's own visible status as parent and child activity change", async () => {
1256 + await using fixture = await setup();
1257 + const { render, update, textNodes } = fixture;
1258 const environmentId = EnvironmentId.make("test");
1259 const parent = {
1260 id: "parent",
@@ -1273,6 +1299,8 @@ it("shows the parent's own visible status as parent and child activity change",
1299 });
1300
1301 it("shows the native coordinator status from its member and gives follow-up activity precedence", async () => {
1302 + await using fixture = await setup();
1303 + const { render, update, buttons } = fixture;
1304 const environmentId = EnvironmentId.make("remote");
1305 const coordinator = {
1306 id: "coordinator",
@@ -1341,6 +1369,8 @@ it("shows the native coordinator status from its member and gives follow-up acti
1369 it.each(["source", "target"])(
1370 "shows transfer lifecycle states when viewing the %s thread",
1371 async (currentThreadId) => {
1372 + await using fixture = await setup();
1373 + const { render, update, textNodes } = fixture;
1374 const environmentId = EnvironmentId.make("test");
1375 const threads = ["source", "target"].map((id) => ({
1376 id,
apps/web/src/components/chat/WorkLog.browser.test.tsx
+72 -74
@@ -1,51 +1,26 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { describe, expect, it } from "vite-plus/test";
2 +import { act, render as renderUi } from "../../../test/render";
3 import { WorkLogDetails } from "./WorkLog";
4
5 // The scroller's geometry is simulated so the test controls it: a 384px
6 // viewport over content whose height the test grows like a streamed trace.
7 const VIEWPORT = 384;
9 -let contentHeight = 0;
10 -let scrollTop = 0;
11 -
12 -let root: Root;
13 -let host: HTMLDivElement;
14 -
15 -function render(followLive: boolean, text: string) {
16 - act(() => {
17 - root.render(
18 - <WorkLogDetails followLive={followLive}>
19 - <p>{text}</p>
20 - </WorkLogDetails>,
21 - );
22 - });
23 -}
24 -
25 -function scroller() {
26 - const element = host.firstElementChild;
27 - if (!(element instanceof HTMLDivElement)) throw new Error("missing scroller");
28 - return element;
29 -}
30 -
31 -function stream(followLive: boolean, text: string) {
32 - contentHeight += 200;
33 - render(followLive, text);
34 -}
35 -
36 -function readerScrollsTo(top: number) {
37 - scroller().scrollTop = top;
38 - act(() => {
39 - scroller().dispatchEvent(new Event("scroll"));
40 - });
41 -}
42 -
43 -const maxScrollTop = () => contentHeight - VIEWPORT;
44 -
45 -beforeEach(() => {
46 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
47 - contentHeight = 1000;
48 - scrollTop = 0;
8 +async function setup() {
9 + let contentHeight = 1000;
10 + let scrollTop = 0;
11 + const maxScrollTop = () => contentHeight - VIEWPORT;
12 + const keys = ["clientHeight", "scrollHeight", "scrollTop"] as const;
13 + const original = keys.map((key) =>
14 + Object.getOwnPropertyDescriptor(HTMLDivElement.prototype, key),
15 + );
16 + await using stack = new AsyncDisposableStack();
17 + stack.defer(() =>
18 + keys.forEach((key, i) => {
19 + const descriptor = original[i];
20 + if (descriptor) Object.defineProperty(HTMLDivElement.prototype, key, descriptor);
21 + else Reflect.deleteProperty(HTMLDivElement.prototype, key);
22 + }),
23 + );
24 Object.defineProperties(HTMLDivElement.prototype, {
25 clientHeight: { configurable: true, get: () => VIEWPORT },
26 scrollHeight: { configurable: true, get: () => contentHeight },
@@ -57,45 +32,68 @@ beforeEach(() => {
32 },
33 },
34 });
60 - host = document.createElement("div");
61 - document.body.append(host);
62 - root = createRoot(host);
63 -});
64 -
65 -afterEach(() => {
66 - act(() => root.unmount());
67 - host.remove();
68 - for (const key of ["clientHeight", "scrollHeight", "scrollTop"]) {
69 - Reflect.deleteProperty(HTMLDivElement.prototype, key);
70 - }
71 - vi.unstubAllGlobals();
72 -});
35 + const screen = stack.use(await renderUi(null));
36 + const render = async (followLive: boolean, text: string) =>
37 + await screen.rerender(
38 + <WorkLogDetails followLive={followLive}>
39 + <p>{text}</p>
40 + </WorkLogDetails>,
41 + );
42 + const scroller = () => {
43 + const element = screen.container.firstElementChild;
44 + if (!(element instanceof HTMLDivElement)) throw new Error("missing scroller");
45 + return element;
46 + };
47 + const stream = async (followLive: boolean, text: string) => {
48 + contentHeight += 200;
49 + await render(followLive, text);
50 + };
51 + const readerScrollsTo = async (top: number) => {
52 + scroller().scrollTop = top;
53 + await act(() => scroller().dispatchEvent(new Event("scroll")));
54 + };
55 + const environment = stack.move();
56 + return {
57 + render,
58 + stream,
59 + readerScrollsTo,
60 + maxScrollTop,
61 + getScrollTop: () => scrollTop,
62 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
63 + };
64 +}
65
66 describe("WorkLogDetails followLive", () => {
75 - it("keeps the newest streamed text in view", () => {
76 - render(true, "a");
77 - expect(scrollTop).toBe(maxScrollTop());
67 + it("keeps the newest streamed text in view", async () => {
68 + await using fixture = await setup();
69 + const { render, stream, maxScrollTop, getScrollTop } = fixture;
70 + await render(true, "a");
71 + expect(getScrollTop()).toBe(maxScrollTop());
72
79 - stream(true, "ab");
80 - stream(true, "abc");
81 - expect(scrollTop).toBe(maxScrollTop());
73 + await stream(true, "ab");
74 + await stream(true, "abc");
75 + expect(getScrollTop()).toBe(maxScrollTop());
76 });
77
84 - it("stops following when the reader scrolls up and resumes at the end", () => {
85 - render(true, "a");
86 - readerScrollsTo(100);
78 + it("stops following when the reader scrolls up and resumes at the end", async () => {
79 + await using fixture = await setup();
80 + const { render, stream, readerScrollsTo, maxScrollTop, getScrollTop } = fixture;
81 + await render(true, "a");
82 + await readerScrollsTo(100);
83
88 - stream(true, "ab");
89 - expect(scrollTop).toBe(100);
84 + await stream(true, "ab");
85 + expect(getScrollTop()).toBe(100);
86
91 - readerScrollsTo(maxScrollTop());
92 - stream(true, "abc");
93 - expect(scrollTop).toBe(maxScrollTop());
87 + await readerScrollsTo(maxScrollTop());
88 + await stream(true, "abc");
89 + expect(getScrollTop()).toBe(maxScrollTop());
90 });
91
96 - it("does not move a trace that is not streaming", () => {
97 - render(false, "a");
98 - stream(false, "ab");
99 - expect(scrollTop).toBe(0);
92 + it("does not move a trace that is not streaming", async () => {
93 + await using fixture = await setup();
94 + const { render, stream, getScrollTop } = fixture;
95 + await render(false, "a");
96 + await stream(false, "ab");
97 + expect(getScrollTop()).toBe(0);
98 });
99 });
apps/web/src/components/chat/WorkflowOpeningBlock.browser.test.tsx
+53 -58
@@ -1,10 +1,9 @@
1 import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
2 import { EnvironmentId } from "@t3tools/contracts";
3 -import { act } from "react";
4 -import { createRoot, type Root } from "react-dom/client";
5 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
3 +import { expect, it, vi } from "vite-plus/test";
4
5 import "~/index.css";
6 +import { act, render } from "../../../test/render";
7 import { getSyntaxHighlighterPromise } from "../../lib/syntaxHighlighting";
8
9 import { AppAtomRegistryProvider } from "../../rpc/atomRegistry";
@@ -63,76 +62,72 @@ function Find(props: { readonly container: HTMLElement | null; readonly query: s
62 return null;
63 }
64
66 -let root: Root;
67 -let host: HTMLElement;
68 -
69 -beforeEach(() => {
70 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
71 - host = document.createElement("div");
72 - host.style.width = "720px";
73 - document.body.append(host);
74 - root = createRoot(host);
75 -});
76 -
77 -afterEach(async () => {
78 - await act(async () => root.unmount());
79 - host.remove();
80 - CSS.highlights.clear();
81 - vi.unstubAllGlobals();
82 -});
83 -
84 -async function render(script: string, query = "") {
85 - await act(async () =>
86 - root.render(
87 - <AppAtomRegistryProvider>
88 - <MarkdownFindContext value={query.length > 0}>
89 - <div data-timeline-row-id="opening">
90 - <WorkflowOpeningBlock
91 - opening={opening(script)}
92 - environmentId={EnvironmentId.make("environment-local")}
93 - onOpenThread={() => undefined}
94 - />
95 - </div>
96 - </MarkdownFindContext>
97 - <Find container={host} query={query} />
98 - </AppAtomRegistryProvider>,
99 - ),
65 +async function renderOpening(script: string, query = "") {
66 + const container = document.createElement("div");
67 + container.style.width = "720px";
68 + const block = (script: string, query: string) => (
69 + <AppAtomRegistryProvider>
70 + <MarkdownFindContext value={query.length > 0}>
71 + <div data-timeline-row-id="opening">
72 + <WorkflowOpeningBlock
73 + opening={opening(script)}
74 + environmentId={EnvironmentId.make("environment-local")}
75 + onOpenThread={() => undefined}
76 + />
77 + </div>
78 + </MarkdownFindContext>
79 + <Find container={container} query={query} />
80 + </AppAtomRegistryProvider>
81 );
101 - await act(async () => {
102 - await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
103 - });
82 + const nextFrame = () =>
83 + act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
84 + await using stack = new AsyncDisposableStack();
85 + stack.defer(() => CSS.highlights.clear());
86 + const screen = stack.use(await render(block(script, query), { container }));
87 + await nextFrame();
88 + const environment = stack.move();
89 + return {
90 + container,
91 + rerender: async (script: string, query: string) => {
92 + await screen.rerender(block(script, query));
93 + await nextFrame();
94 + },
95 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
96 + };
97 }
98
106 -const foldToggle = () =>
99 +const foldToggle = (host: HTMLElement) =>
100 [...host.querySelectorAll("button")].find((button) =>
101 /Show full script|Show less/.test(button.textContent ?? ""),
102 );
103
104 it("shows a short script as highlighted code with nothing to open", async () => {
112 - await render(SHORT_SCRIPT);
113 - await act(async () => {
114 - await getSyntaxHighlighterPromise("javascript");
115 - });
116 - expect(host.querySelector('[data-language="javascript"]')?.textContent).toContain("SCRIPTONLY");
117 - await vi.waitFor(() => expect(host.querySelector(".chat-markdown-shiki")).not.toBeNull());
118 - expect(foldToggle()).toBeUndefined();
105 + await using screen = await renderOpening(SHORT_SCRIPT);
106 + await act(() => getSyntaxHighlighterPromise("javascript"));
107 + expect(screen.container.querySelector('[data-language="javascript"]')?.textContent).toContain(
108 + "SCRIPTONLY",
109 + );
110 + await vi.waitFor(() =>
111 + expect(screen.container.querySelector(".chat-markdown-shiki")).not.toBeNull(),
112 + );
113 + expect(foldToggle(screen.container)).toBeUndefined();
114 });
115
116 it("folds a long script until it is opened", async () => {
122 - await render(LONG_SCRIPT);
123 - expect(foldToggle()?.getAttribute("aria-expanded")).toBe("false");
124 - expect(host.querySelector("[data-thread-find-fold]")).not.toBeNull();
125 - await act(async () => foldToggle()?.click());
126 - expect(foldToggle()?.getAttribute("aria-expanded")).toBe("true");
127 - expect(host.querySelector("[data-thread-find-fold]")).toBeNull();
117 + await using screen = await renderOpening(LONG_SCRIPT);
118 + expect(foldToggle(screen.container)?.getAttribute("aria-expanded")).toBe("false");
119 + expect(screen.container.querySelector("[data-thread-find-fold]")).not.toBeNull();
120 + await act(() => foldToggle(screen.container)?.click());
121 + expect(foldToggle(screen.container)?.getAttribute("aria-expanded")).toBe("true");
122 + expect(screen.container.querySelector("[data-thread-find-fold]")).toBeNull();
123 });
124
125 it("finds the workflow's name and opens a folded script on a match below the fold", async () => {
131 - await render(LONG_SCRIPT, "repo-check");
126 + await using screen = await renderOpening(LONG_SCRIPT, "repo-check");
127 expect(CSS.highlights.get("t3-thread-find-active")?.size).toBe(1);
133 - expect(foldToggle()?.getAttribute("aria-expanded")).toBe("false");
128 + expect(foldToggle(screen.container)?.getAttribute("aria-expanded")).toBe("false");
129
135 - await render(LONG_SCRIPT, "TAILONLY");
130 + await screen.rerender(LONG_SCRIPT, "TAILONLY");
131 expect(CSS.highlights.get("t3-thread-find-active")?.size).toBe(1);
137 - expect(foldToggle()?.getAttribute("aria-expanded")).toBe("true");
132 + expect(foldToggle(screen.container)?.getAttribute("aria-expanded")).toBe("true");
133 });
apps/web/src/components/chat/composerEventScope.browser.test.tsx
+15 -29
@@ -1,7 +1,7 @@
1 -import { act, useLayoutEffect } from "react";
2 -import { createRoot } from "react-dom/client";
3 -import { afterEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { useLayoutEffect } from "react";
2 +import { describe, expect, it } from "vite-plus/test";
3
4 +import { render } from "../../../test/render";
5 import { ComposerHandleContext, type ComposerHandleRef } from "../../composerHandleContext";
6 import {
7 isInsideCollapsedComposerControls,
@@ -10,18 +10,11 @@ import {
10 useComposerMenuProps,
11 } from "./composerEventScope";
12
13 -function elementInside(html: string) {
14 - const host = document.createElement("div");
15 - host.innerHTML = html;
16 - document.body.append(host);
13 +function elementInside(html: string, host = document.createElement("div")) {
14 + host.insertAdjacentHTML("beforeend", html);
15 return host.querySelector("[data-target]")!;
16 }
17
20 -afterEach(() => {
21 - document.body.replaceChildren();
22 - vi.unstubAllGlobals();
23 -});
24 -
18 describe("composer menu focus", () => {
19 it.each([
20 [
@@ -32,14 +25,14 @@ describe("composer menu focus", () => {
25 ["an unmounted menu", null, true],
26 ["another control", "<input data-target />", false],
27 ])("closes while focus is on %s", async (_label, html, shouldFocusComposer) => {
35 - const editor = document.createElement("textarea");
36 - document.body.append(editor);
37 - const focused = html === null ? null : (elementInside(html) as HTMLElement);
28 + const host = document.body.appendChild(document.createElement("div"));
29 + using _host = { [Symbol.dispose]: () => host.remove() };
30 + const editor = host.appendChild(document.createElement("textarea"));
31 + const focused = html === null ? null : (elementInside(html, host) as HTMLElement);
32 focused?.focus();
33 const composerRef = {
34 current: { focusAtEnd: () => editor.focus() },
35 } as unknown as ComposerHandleRef;
42 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
36 let menuProps: ReturnType<typeof useComposerMenuProps> | undefined;
37 function Probe() {
38 const props = useComposerMenuProps();
@@ -48,20 +41,13 @@ describe("composer menu focus", () => {
41 }, [props]);
42 return null;
43 }
51 - const root = createRoot(document.createElement("div"));
52 - await act(async () =>
53 - root.render(
54 - <ComposerHandleContext value={composerRef}>
55 - <Probe />
56 - </ComposerHandleContext>,
57 - ),
44 + await using _screen = await render(
45 + <ComposerHandleContext value={composerRef}>
46 + <Probe />
47 + </ComposerHandleContext>,
48 );
59 - try {
60 - expect(menuProps?.finalFocus?.()).toBe(false);
61 - expect(document.activeElement).toBe(shouldFocusComposer ? editor : focused);
62 - } finally {
63 - await act(async () => root.unmount());
64 - }
49 + expect(menuProps?.finalFocus?.()).toBe(false);
50 + expect(document.activeElement).toBe(shouldFocusComposer ? editor : focused);
51 });
52 });
53
apps/web/src/components/chat/composerThreadImport.browser.test.tsx
+36 -42
@@ -1,7 +1,8 @@
1 import { EnvironmentId } from "@t3tools/contracts";
2 -import { act, useRef } from "react";
3 -import { createRoot } from "react-dom/client";
4 -import { describe, expect, it, vi } from "vite-plus/test";
2 +import { useRef } from "react";
3 +import { describe, expect, it } from "vite-plus/test";
4 +
5 +import { act, render } from "../../../test/render";
6
7 import { importComposerThreadAttachment } from "./composerThreadImport";
8 import { THREAD_CONTEXT_DROP_EVENT, useThreadContextDrop } from "./threadContextDrag";
@@ -59,46 +60,39 @@ describe("importComposerThreadAttachment from a thread drop", () => {
60 targetKey: "draft",
61 expanded: false,
62 };
62 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
63 - const root = createRoot(document.createElement("div"));
64 - try {
65 - act(() => root.render(<Composer {...props} />));
66 - act(() => target.dispatchEvent(new CustomEvent(THREAD_CONTEXT_DROP_EVENT, { detail: [] })));
67 - expect(pendingImports.get("draft")).toBe(1);
68 - if (change === "unmount") {
69 - act(() => root.unmount());
70 - } else {
71 - act(() =>
72 - root.render(
73 - <Composer
74 - {...props}
75 - expanded
76 - {...(change === "draft switch" ? { targetKey: "another-draft" } : {})}
77 - {...(change === "environment switch"
78 - ? { environmentId: EnvironmentId.make("another-environment") }
79 - : {})}
80 - />,
81 - ),
82 - );
83 - if (change !== "expand") {
84 - act(() => root.render(<Composer {...props} />));
85 - }
86 - }
87 - transcript.resolve(new File(["transcript"], "thread.txt"));
88 - await act(async () => importing);
89 - expect(attached).toEqual(change === "expand" ? ["thread.txt"] : []);
90 - expect(pendingImports.size).toBe(0);
91 - if (change === "expand") {
92 - act(() =>
93 - target.dispatchEvent(new CustomEvent(THREAD_CONTEXT_DROP_EVENT, { detail: [] })),
94 - );
95 - await act(async () => importing);
96 - expect(expandedAtDrop).toEqual([false, true]);
97 - expect(attached).toEqual(["thread.txt", "thread.txt"]);
63 + await using screen = await render(<Composer {...props} />);
64 + await act(() =>
65 + target.dispatchEvent(new CustomEvent(THREAD_CONTEXT_DROP_EVENT, { detail: [] })),
66 + );
67 + expect(pendingImports.get("draft")).toBe(1);
68 + if (change === "unmount") {
69 + await screen.unmount();
70 + } else {
71 + await screen.rerender(
72 + <Composer
73 + {...props}
74 + expanded
75 + {...(change === "draft switch" ? { targetKey: "another-draft" } : {})}
76 + {...(change === "environment switch"
77 + ? { environmentId: EnvironmentId.make("another-environment") }
78 + : {})}
79 + />,
80 + );
81 + if (change !== "expand") {
82 + await screen.rerender(<Composer {...props} />);
83 }
99 - } finally {
100 - if (change !== "unmount") act(() => root.unmount());
101 - vi.unstubAllGlobals();
84 + }
85 + transcript.resolve(new File(["transcript"], "thread.txt"));
86 + await act(() => importing);
87 + expect(attached).toEqual(change === "expand" ? ["thread.txt"] : []);
88 + expect(pendingImports.size).toBe(0);
89 + if (change === "expand") {
90 + await act(() =>
91 + target.dispatchEvent(new CustomEvent(THREAD_CONTEXT_DROP_EVENT, { detail: [] })),
92 + );
93 + await act(() => importing);
94 + expect(expandedAtDrop).toEqual([false, true]);
95 + expect(attached).toEqual(["thread.txt", "thread.txt"]);
96 }
97 },
98 );
apps/web/src/components/chat/threadContextDrag.browser.test.tsx
+11 -27
@@ -1,28 +1,12 @@
1 -import { act, memo, useRef } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { memo, useRef } from "react";
2 +import { describe, expect, it } from "vite-plus/test";
3 import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
4
5 +import { act, render } from "../../../test/render";
6 import { THREAD_CONTEXT_DROP_EVENT, useThreadContextDrop } from "./threadContextDrag";
7
8 const ENVIRONMENT_ID = "environment-local" as EnvironmentId;
9
10 -let root: Root;
11 -let container: HTMLDivElement;
12 -
13 -beforeEach(() => {
14 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
15 - container = document.createElement("div");
16 - document.body.append(container);
17 - root = createRoot(container);
18 -});
19 -
20 -afterEach(async () => {
21 - await act(() => root.unmount());
22 - container.remove();
23 - vi.unstubAllGlobals();
24 -});
25 -
10 // ChatComposer is memoized and reused across thread navigation; each render's
11 // drop callback must write into the draft of the thread it last rendered.
12 const ComposerDropTarget = memo(function ComposerDropTarget({
@@ -61,16 +45,16 @@ describe("useThreadContextDrop", () => {
45 ["thread-b", []],
46 ]);
47
64 - await act(() => root.render(<ComposerDropTarget draftKey="thread-a" drafts={drafts} />));
65 - await act(() => root.render(<ComposerDropTarget draftKey="thread-b" drafts={drafts} />));
48 + await using screen = await render(<ComposerDropTarget draftKey="thread-a" drafts={drafts} />);
49 + await screen.rerender(<ComposerDropTarget draftKey="thread-b" drafts={drafts} />);
50
51 const dropped: ScopedThreadRef = {
52 environmentId: ENVIRONMENT_ID,
53 threadId: "thread-dropped" as ThreadId,
54 };
71 - const target = container.querySelector("[data-drop-target]");
55 + const target = screen.container.querySelector("[data-drop-target]");
56 expect(target).not.toBeNull();
73 - act(() => {
57 + await act(() => {
58 target!.dispatchEvent(new CustomEvent(THREAD_CONTEXT_DROP_EVENT, { detail: [dropped] }));
59 });
60
@@ -82,12 +66,12 @@ describe("useThreadContextDrop", () => {
66 const first: Array<ThreadId> = [];
67 const latest: Array<ThreadId> = [];
68
85 - await act(() => root.render(<StableKeyDropTarget received={first} />));
86 - await act(() => root.render(<StableKeyDropTarget received={latest} />));
69 + await using screen = await render(<StableKeyDropTarget received={first} />);
70 + await screen.rerender(<StableKeyDropTarget received={latest} />);
71
88 - const target = container.querySelector("[data-drop-target]");
72 + const target = screen.container.querySelector("[data-drop-target]");
73 expect(target).not.toBeNull();
90 - act(() => {
74 + await act(() => {
75 target!.dispatchEvent(
76 new CustomEvent(THREAD_CONTEXT_DROP_EVENT, {
77 detail: [{ environmentId: ENVIRONMENT_ID, threadId: "thread-dropped" as ThreadId }],
apps/web/src/components/chat/threadFindHighlights.browser.test.tsx
+99 -110
@@ -1,6 +1,6 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { describe, expect, it, vi } from "vite-plus/test";
2 +
3 +import { act, render, stubGlobal } from "../../../test/render";
4 import { collectThreadFindRanges, useThreadFindHighlights } from "./threadFindHighlights";
5
6 function Probe(props: Parameters<typeof useThreadFindHighlights>[0]) {
@@ -8,44 +8,39 @@ function Probe(props: Parameters<typeof useThreadFindHighlights>[0]) {
8 return null;
9 }
10
11 -let root: Root;
12 -let host: HTMLElement;
13 -let container: HTMLElement;
14 -const onActiveRange = vi.fn();
11 const activeRanges = () => [
12 ...(CSS.highlights.get("t3-thread-find-active") as unknown as Set<Range>),
13 ];
14
19 -beforeEach(() => {
20 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
21 - vi.stubGlobal("CSS", { highlights: new Map() });
22 - vi.stubGlobal(
23 - "Highlight",
24 - class extends Set<Range> {
25 - constructor(...ranges: Range[]) {
26 - super(ranges);
27 - }
28 - },
15 +const nextFrame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
16 +
17 +function setup() {
18 + using stack = new DisposableStack();
19 + stack.use(stubGlobal("CSS", { highlights: new Map() }));
20 + stack.use(
21 + stubGlobal(
22 + "Highlight",
23 + class extends Set<Range> {
24 + constructor(...ranges: Range[]) {
25 + super(ranges);
26 + }
27 + },
28 + ),
29 );
30 - host = document.createElement("div");
31 - container = document.createElement("div");
30 + const container = document.createElement("div");
31 container.innerHTML =
32 '<div data-timeline-row-id="first"><p data-thread-find-text>COD4 and COD4</p></div>' +
33 '<div data-timeline-row-id="second"><p data-thread-find-text>COD4</p></div>';
35 - document.body.append(host, container);
36 - root = createRoot(host);
37 -});
38 -afterEach(async () => {
39 - await act(async () => root.unmount());
40 - host.remove();
41 - container.remove();
42 - vi.restoreAllMocks();
43 - vi.clearAllMocks();
44 - vi.unstubAllGlobals();
45 -});
34 + document.body.append(container);
35 + stack.defer(() => container.remove());
36 + const environment = stack.move();
37 + return { container, onActiveRange: vi.fn(), [Symbol.dispose]: () => environment.dispose() };
38 +}
39
40 describe("find highlight caching", () => {
41 it("checks only the old and new occurrence when cycling a message with many clipped matches", async () => {
42 + using find = setup();
43 + const { container, onActiveRange } = find;
44 container.innerHTML =
45 '<div data-timeline-row-id="first"><div data-thread-find-fold><p data-thread-find-text>' +
46 "COD4 ".repeat(1500) +
@@ -55,6 +50,9 @@ describe("find highlight caching", () => {
50 configurable: true,
51 value: bounds,
52 });
53 + using _bounds = {
54 + [Symbol.dispose]: () => Reflect.deleteProperty(Range.prototype, "getBoundingClientRect"),
55 + };
56 container.querySelector<HTMLElement>("[data-thread-find-fold]")!.getBoundingClientRect = () =>
57 new DOMRect(0, 0, 800, 100);
58 const props = {
@@ -64,117 +62,108 @@ describe("find highlight caching", () => {
62 activeOccurrence: 0,
63 onActiveRange,
64 };
67 - try {
68 - await act(async () => root.render(<Probe {...props} />));
69 - const inactive = CSS.highlights.get("t3-thread-find");
70 - const first = activeRanges()[0];
71 - bounds.mockClear();
72 - await act(async () => root.render(<Probe {...props} activeOccurrence={1} />));
73 - expect(bounds).toHaveBeenCalledTimes(2);
74 - expect(CSS.highlights.get("t3-thread-find")).toBe(inactive);
75 - expect(inactive?.size).toBe(1499);
76 - expect(inactive?.has(first!)).toBe(true);
77 - expect(activeRanges()[0]?.startOffset).toBe(5);
78 - expect(inactive?.has(activeRanges()[0]!)).toBe(false);
79 - } finally {
80 - Reflect.deleteProperty(Range.prototype, "getBoundingClientRect");
81 - }
65 + await using screen = await render(<Probe {...props} />);
66 + const inactive = CSS.highlights.get("t3-thread-find");
67 + const first = activeRanges()[0];
68 + bounds.mockClear();
69 + await screen.rerender(<Probe {...props} activeOccurrence={1} />);
70 + expect(bounds).toHaveBeenCalledTimes(2);
71 + expect(CSS.highlights.get("t3-thread-find")).toBe(inactive);
72 + expect(inactive?.size).toBe(1499);
73 + expect(inactive?.has(first!)).toBe(true);
74 + expect(activeRanges()[0]?.startOffset).toBe(5);
75 + expect(inactive?.has(activeRanges()[0]!)).toBe(false);
76 });
77
78 it("repaints for searchable text changes but not for timers outside it", async () => {
79 + using find = setup();
80 + const { container, onActiveRange } = find;
81 const timer = document.createElement("span");
82 container.firstElementChild!.append(timer);
87 - await act(async () =>
88 - root.render(
89 - <Probe
90 - container={container}
91 - query="COD4"
92 - activeRowId="first"
93 - activeOccurrence={0}
94 - onActiveRange={onActiveRange}
95 - />,
96 - ),
83 + await using _screen = await render(
84 + <Probe
85 + container={container}
86 + query="COD4"
87 + activeRowId="first"
88 + activeOccurrence={0}
89 + onActiveRange={onActiveRange}
90 + />,
91 );
92 onActiveRange.mockClear();
93 await act(async () => {
94 timer.textContent = "0:01";
101 - await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
95 + await nextFrame();
96 });
97 expect(onActiveRange).not.toHaveBeenCalled();
98 await act(async () => {
99 container.querySelector("p")!.append(" COD4");
106 - await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
100 + await nextFrame();
101 });
102 expect(onActiveRange).toHaveBeenCalled();
103 });
104
105 it("opens only the selected fold while reusing its cached text", async () => {
106 + using find = setup();
107 + const { container, onActiveRange } = find;
108 container.innerHTML =
109 '<div data-timeline-row-id="first"><div hidden><p data-thread-find-text>COD4 COD4</p></div></div>' +
110 '<div data-timeline-row-id="second"><div hidden><p data-thread-find-text>COD4</p></div></div>';
111 const folds = [...container.querySelectorAll<HTMLElement>("[hidden]")];
112 for (const fold of folds)
113 fold.addEventListener("beforematch", () => fold.removeAttribute("hidden"));
118 - const createRange = vi.spyOn(document, "createRange");
119 - await act(async () =>
120 - root.render(
121 - <Probe
122 - container={container}
123 - query="COD4"
124 - activeRowId="first"
125 - activeOccurrence={0}
126 - onActiveRange={onActiveRange}
127 - />,
128 - ),
114 + using createRange = vi.spyOn(document, "createRange");
115 + await using screen = await render(
116 + <Probe
117 + container={container}
118 + query="COD4"
119 + activeRowId="first"
120 + activeOccurrence={0}
121 + onActiveRange={onActiveRange}
122 + />,
123 );
130 - await act(async () => {
131 - await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
132 - });
124 + await act(nextFrame);
125 expect(folds[0]?.hasAttribute("hidden")).toBe(false);
126 expect(folds[1]?.hasAttribute("hidden")).toBe(true);
127 expect(activeRanges()[0]?.toString()).toBe("COD4");
128 expect(CSS.highlights.get("t3-thread-find")?.size).toBe(1);
129 const scanned = createRange.mock.calls.length;
138 - await act(async () =>
139 - root.render(
140 - <Probe
141 - container={container}
142 - query="COD4"
143 - activeRowId="first"
144 - activeOccurrence={1}
145 - onActiveRange={onActiveRange}
146 - />,
147 - ),
130 + await screen.rerender(
131 + <Probe
132 + container={container}
133 + query="COD4"
134 + activeRowId="first"
135 + activeOccurrence={1}
136 + onActiveRange={onActiveRange}
137 + />,
138 );
139 expect(createRange).toHaveBeenCalledTimes(scanned);
140 expect(activeRanges()[0]?.startOffset).toBe(5);
141 });
142
143 it("observes rows mounted synchronously while revealing the first match", async () => {
144 + using find = setup();
145 + const { container, onActiveRange } = find;
146 container.replaceChildren();
147 onActiveRange.mockImplementationOnce(() => {
148 container.innerHTML =
149 '<div data-timeline-row-id="first"><p data-thread-find-text>COD4</p></div>';
150 });
159 - await act(async () => {
160 - root.render(
161 - <Probe
162 - container={container}
163 - query="COD4"
164 - activeRowId="first"
165 - activeOccurrence={0}
166 - onActiveRange={onActiveRange}
167 - />,
168 - );
169 - await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
170 - });
171 - await act(async () => {
172 - await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
173 - });
151 + await using _screen = await render(
152 + <Probe
153 + container={container}
154 + query="COD4"
155 + activeRowId="first"
156 + activeOccurrence={0}
157 + onActiveRange={onActiveRange}
158 + />,
159 + );
160 + await act(nextFrame);
161 expect(activeRanges()[0]?.toString()).toBe("COD4");
162 });
163
164 it("rebuilds ranges when the list moves or recycles an existing row", async () => {
165 + using find = setup();
166 + const { container, onActiveRange } = find;
167 const props = {
168 container,
169 query: "COD4",
@@ -182,27 +171,29 @@ describe("find highlight caching", () => {
171 activeOccurrence: 0,
172 onActiveRange,
173 };
185 - await act(async () => root.render(<Probe {...props} />));
174 + await using screen = await render(<Probe {...props} />);
175 const initial = activeRanges()[0];
176 const row = container.querySelector<HTMLElement>('[data-timeline-row-id="first"]')!;
177 await act(async () => {
178 row.remove();
179 container.append(row);
191 - await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
180 + await nextFrame();
181 });
182 expect(activeRanges()[0]).not.toBe(initial);
183 expect(activeRanges()[0]?.toString()).toBe("COD4");
184 await act(async () => {
185 row.dataset.timelineRowId = "recycled";
197 - await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
186 + await nextFrame();
187 });
188 expect(activeRanges()).toHaveLength(0);
200 - await act(async () => root.render(<Probe {...props} activeRowId="recycled" />));
189 + await screen.rerender(<Probe {...props} activeRowId="recycled" />);
190 expect(activeRanges()[0]?.toString()).toBe("COD4");
191 });
192
193 it("reuses unchanged text ranges on navigation and scans only the streaming row", async () => {
205 - const createRange = vi.spyOn(document, "createRange");
194 + using find = setup();
195 + const { container, onActiveRange } = find;
196 + using createRange = vi.spyOn(document, "createRange");
197 const props = {
198 container,
199 query: "COD4",
@@ -210,35 +201,33 @@ describe("find highlight caching", () => {
201 activeOccurrence: 0,
202 onActiveRange,
203 };
213 - await act(async () => root.render(<Probe {...props} />));
204 + await using screen = await render(<Probe {...props} />);
205 expect(createRange).toHaveBeenCalledTimes(3);
206 const initial = activeRanges()[0];
216 - await act(async () => root.render(<Probe {...props} activeOccurrence={1} />));
207 + await screen.rerender(<Probe {...props} activeOccurrence={1} />);
208 expect(createRange).toHaveBeenCalledTimes(3);
209 expect(activeRanges()[0]?.startOffset).toBe(9);
219 - await act(async () => root.render(<Probe {...props} />));
210 + await screen.rerender(<Probe {...props} />);
211 expect(activeRanges()[0]).toBe(initial);
212 await act(async () => {
213 container.querySelector('[data-timeline-row-id="second"] p')!.firstChild!.nodeValue =
214 "COD4 COD4";
224 - await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
215 + await nextFrame();
216 });
217 expect(createRange).toHaveBeenCalledTimes(5);
218 expect(activeRanges()[0]).toBe(initial);
228 - await act(async () =>
229 - root.render(<Probe {...props} activeRowId="second" activeOccurrence={1} />),
230 - );
219 + await screen.rerender(<Probe {...props} activeRowId="second" activeOccurrence={1} />);
220 expect(createRange).toHaveBeenCalledTimes(5);
221 expect(activeRanges()[0]?.toString()).toBe("COD4");
222 expect(activeRanges()[0]?.startOffset).toBe(5);
223 await act(async () => {
224 container.querySelector('[data-timeline-row-id="second"]')!.remove();
236 - await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
225 + await nextFrame();
226 });
227 expect(activeRanges()).toHaveLength(0);
228 expect(onActiveRange).toHaveBeenLastCalledWith(null);
229 expect(CSS.highlights.get("t3-thread-find")?.size).toBe(2);
241 - await act(async () => root.render(<Probe {...props} query="missing" />));
230 + await screen.rerender(<Probe {...props} query="missing" />);
231 expect(CSS.highlights.get("t3-thread-find")?.size).toBe(0);
232 });
233 });
apps/web/src/components/chat/useComposerFocusState.browser.test.tsx
+6 -15
@@ -1,11 +1,10 @@
1 -import { act, useLayoutEffect } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { useLayoutEffect } from "react";
2 +import { describe, expect, it } from "vite-plus/test";
3
4 +import { act, render } from "../../../test/render";
5 import { shouldUseRestingComposerLayout } from "../composerFooterLayout";
6 import { useComposerFocusState } from "./useComposerFocusState";
7
8 -let root: Root;
8 let composer: ReturnType<typeof useComposerFocusState>;
9 let isResting: boolean;
10
@@ -25,19 +24,9 @@ function ComposerProbe() {
24 return null;
25 }
26
28 -beforeEach(async () => {
29 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
30 - root = createRoot(document.createElement("div"));
31 - await act(() => root.render(<ComposerProbe />));
32 -});
33 -
34 -afterEach(async () => {
35 - await act(() => root.unmount());
36 - vi.unstubAllGlobals();
37 -});
38 -
27 describe("composer focus state", () => {
28 it("stays expanded when the composer loses focus", async () => {
29 + await using _screen = await render(<ComposerProbe />);
30 await act(() => composer.setIsComposerFocused(true));
31 expect(isResting).toBe(false);
32
@@ -46,6 +35,7 @@ describe("composer focus state", () => {
35 });
36
37 it("can collapse again on the next scroll after returning to the end", async () => {
38 + await using _screen = await render(<ComposerProbe />);
39 await act(() => composer.setIsComposerScrollCollapsed(true));
40 expect(isResting).toBe(true);
41
@@ -57,6 +47,7 @@ describe("composer focus state", () => {
47 });
48
49 it("does not move focus into the composer when the timeline reaches the end", async () => {
50 + await using _screen = await render(<ComposerProbe />);
51 await act(() => composer.setIsComposerScrollCollapsed(true));
52 await act(() => composer.restoreAfterTimelineReachedEnd());
53 expect(isResting).toBe(false);
apps/web/src/components/chat/useComposerMenuState.browser.test.tsx
+17 -27
@@ -1,10 +1,9 @@
1 -import { act, StrictMode, useLayoutEffect } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { StrictMode, useLayoutEffect } from "react";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3
4 +import { act, render } from "../../../test/render";
5 import { useComposerMenuState } from "./useComposerMenuState";
6
7 -let root: Root;
7 let setOpen: ReturnType<typeof useComposerMenuState>[1];
8 let committedOpen: boolean[];
9 let closePopup = vi.fn<() => void>();
@@ -19,40 +18,30 @@ function MenuStateProbe({ hidden }: { hidden: boolean }) {
18 return null;
19 }
20
22 -async function renderMenu(hidden: boolean) {
23 - await act(() => {
24 - root.render(
25 - <StrictMode>
26 - <MenuStateProbe hidden={hidden} />
27 - </StrictMode>,
28 - );
29 - });
30 -}
21 +const menu = (hidden: boolean) => (
22 + <StrictMode>
23 + <MenuStateProbe hidden={hidden} />
24 + </StrictMode>
25 +);
26
32 -beforeEach(() => {
33 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
27 +function setup() {
28 committedOpen = [];
29 closePopup = vi.fn();
36 - root = createRoot(document.createElement("div"));
37 -});
38 -
39 -afterEach(async () => {
40 - await act(() => root.unmount());
41 - vi.unstubAllGlobals();
42 -});
30 +}
31
32 describe("useComposerMenuState", () => {
33 it("closes an open popup when its trigger hides and does not reopen when it returns", async () => {
46 - await renderMenu(false);
34 + setup();
35 + await using screen = await render(menu(false));
36 await act(() => setOpen(true));
37 expect(committedOpen.at(-1)).toBe(true);
38
50 - await renderMenu(true);
39 + await screen.rerender(menu(true));
40 expect(committedOpen.at(-1)).toBe(false);
41 expect(closePopup).toHaveBeenCalledTimes(1);
42
43 const afterClose = committedOpen.length;
55 - await renderMenu(false);
44 + await screen.rerender(menu(false));
45 expect(committedOpen).toHaveLength(afterClose);
46 expect(committedOpen.at(-1)).toBe(false);
47
@@ -64,9 +53,10 @@ describe("useComposerMenuState", () => {
53 });
54
55 it("does not commit an open popup requested while its trigger is hidden", async () => {
67 - await renderMenu(true);
56 + setup();
57 + await using screen = await render(menu(true));
58 await act(() => setOpen(true));
69 - await renderMenu(false);
59 + await screen.rerender(menu(false));
60
61 expect(committedOpen.every((open) => !open)).toBe(true);
62 expect(closePopup).not.toHaveBeenCalled();
apps/web/src/components/chat/useComposerTriggerState.browser.test.tsx
+17 -19
@@ -1,13 +1,12 @@
1 -import { act, StrictMode, useLayoutEffect } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { StrictMode, useLayoutEffect } from "react";
2 +import { describe, expect, it } from "vite-plus/test";
3
4 +import { act, render } from "../../../test/render";
5 import { detectComposerTrigger } from "../../composer-logic";
6 import { useComposerTriggerState } from "./useComposerTriggerState";
7
8 const command = "pnpm install -g @openai/codex@latest";
9 const initialPrompt = "pnpm install -g @openai";
10 -let root: Root;
10 let composer: ReturnType<typeof useComposerTriggerState>;
11
12 function ComposerProbe() {
@@ -24,25 +23,16 @@ async function updatePrompt(text: string, cursor = text.length) {
23 await act(() => composer.setTrigger(detectComposerTrigger(text, cursor)));
24 }
25
27 -beforeEach(async () => {
28 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
29 - root = createRoot(document.createElement("div"));
30 - await act(() =>
31 - root.render(
32 - <StrictMode>
33 - <ComposerProbe />
34 - </StrictMode>,
35 - ),
26 +const renderComposer = () =>
27 + render(
28 + <StrictMode>
29 + <ComposerProbe />
30 + </StrictMode>,
31 );
37 -});
38 -
39 -afterEach(async () => {
40 - await act(() => root.unmount());
41 - vi.unstubAllGlobals();
42 -});
32
33 describe("composer suggestion dismissal", () => {
34 it("closes suggestions and rejects keyboard selection before the next render", async () => {
35 + await using _screen = await renderComposer();
36 const candidate = detectComposerTrigger(initialPrompt, initialPrompt.length);
37 expect(composer.trigger).toEqual(candidate);
38
@@ -54,6 +44,7 @@ describe("composer suggestion dismissal", () => {
44 });
45
46 it("stays dismissed while typing a scoped package, including its second @", async () => {
47 + await using _screen = await renderComposer();
48 await act(() => composer.dismissTrigger(composer.trigger));
49
50 for (let cursor = initialPrompt.length; cursor <= command.length; cursor += 1) {
@@ -65,6 +56,7 @@ describe("composer suggestion dismissal", () => {
56 });
57
58 it("stays dismissed while deleting characters or moving within the same word", async () => {
59 + await using _screen = await renderComposer();
60 await act(() => composer.dismissTrigger(composer.trigger));
61
62 for (let cursor = initialPrompt.length - 1; cursor > initialPrompt.indexOf("@"); cursor -= 1) {
@@ -76,6 +68,7 @@ describe("composer suggestion dismissal", () => {
68 });
69
70 it("opens suggestions for a new @ word after a space", async () => {
71 + await using _screen = await renderComposer();
72 await act(() => composer.dismissTrigger(composer.trigger));
73 await updatePrompt(`${command} `);
74 await updatePrompt(`${command} @src`);
@@ -85,6 +78,7 @@ describe("composer suggestion dismissal", () => {
78 });
79
80 it("opens a different token when the caret moves directly to it", async () => {
81 + await using _screen = await renderComposer();
82 await act(() => composer.dismissTrigger(composer.trigger));
83 await updatePrompt(`${command} @src`);
84
@@ -92,6 +86,7 @@ describe("composer suggestion dismissal", () => {
86 });
87
88 it("can reopen after the caret leaves the dismissed word", async () => {
89 + await using _screen = await renderComposer();
90 await act(() => composer.dismissTrigger(composer.trigger));
91 await updatePrompt(initialPrompt, 0);
92 await updatePrompt(initialPrompt);
@@ -100,6 +95,7 @@ describe("composer suggestion dismissal", () => {
95 });
96
97 it("can reopen at the same position after deleting and retyping @", async () => {
98 + await using _screen = await renderComposer();
99 await act(() => composer.dismissTrigger(composer.trigger));
100 const prefix = initialPrompt.slice(0, initialPrompt.indexOf("@"));
101 await updatePrompt(prefix);
@@ -109,6 +105,7 @@ describe("composer suggestion dismissal", () => {
105 });
106
107 it("clears dismissal when switching drafts or pending questions", async () => {
108 + await using _screen = await renderComposer();
109 await act(() => composer.dismissTrigger(composer.trigger));
110 const candidate = detectComposerTrigger(initialPrompt, initialPrompt.length);
111 await act(() => composer.resetTrigger(candidate));
@@ -118,6 +115,7 @@ describe("composer suggestion dismissal", () => {
115 });
116
117 it.each(["/plan", "$skill", "#123"])("also dismisses %s suggestions", async (text) => {
118 + await using _screen = await renderComposer();
119 await updatePrompt(text);
120 await act(() => composer.dismissTrigger(composer.trigger));
121 await updatePrompt(`${text}x`);
apps/web/src/components/chat/useThreadFind.browser.test.tsx
+69 -119
@@ -1,6 +1,5 @@
1 -import { act, useLayoutEffect, type ReactNode } from "react";
2 -import { createRoot } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { useLayoutEffect } from "react";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3 import {
4 EnvironmentId,
5 RunId,
@@ -8,6 +7,7 @@ import {
7 type OrchestrationV2SearchThreadInput,
8 type OrchestrationV2SearchThreadResult,
9 } from "@t3tools/contracts";
10 +import { act, fakeTimers, render } from "../../../test/render";
11 import { useThreadFind } from "./useThreadFind";
12 import { orchestrationEnvironment } from "~/state/orchestration";
13 import { requestThreadFindOpen } from "./threadFindActionBus";
@@ -39,14 +39,6 @@ vi.mock("~/state/query", () => ({
39
40 vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));
41
42 -type Rendered = { update: (node: ReactNode) => void; unmount: () => void };
43 -function render(node: ReactNode): Rendered {
44 - const root = createRoot(document.createElement("div"));
45 - root.render(node);
46 - return { update: (next) => root.render(next), unmount: () => root.unmount() };
47 -}
48 -
49 -let renderer: Rendered | undefined;
42 let find: ReturnType<typeof useThreadFind>;
43 const a = EnvironmentId.make("environment:a");
44 const b = EnvironmentId.make("environment:b");
@@ -74,18 +66,11 @@ function Probe({
66 });
67 return null;
68 }
77 -beforeEach(() => {
78 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
79 -});
80 -afterEach(async () => {
81 - if (renderer) await act(async () => renderer?.unmount());
82 - renderer = undefined;
69 +function setup() {
70 queries.results.clear();
71 queries.pending = false;
72 vi.clearAllMocks();
86 - vi.useRealTimers();
87 - vi.unstubAllGlobals();
88 -});
73 +}
74
75 describe("V2 find state", () => {
76 function messageResult(index: number, snapshotSequence = 9): OrchestrationV2SearchThreadResult {
@@ -98,9 +83,8 @@ describe("V2 find state", () => {
83 }
84
85 it("reveals an early match and updates its count without requesting another jump", async () => {
101 - await act(async () => {
102 - renderer = render(<Probe environmentId={a} progressive />);
103 - });
86 + setup();
87 + await using screen = await render(<Probe environmentId={a} progressive />);
88 await act(async () => find.open());
89 await act(async () => find.barProps.onQueryChange("needle"));
90 const partial: OrchestrationV2SearchThreadResult = {
@@ -112,7 +96,7 @@ describe("V2 find state", () => {
96 };
97 queries.pending = true;
98 queries.results.set(a, partial);
115 - await act(async () => renderer?.update(<Probe environmentId={a} progressive />));
99 + await screen.rerender(<Probe environmentId={a} progressive />);
100 expect(find.barProps.counting).toBe(true);
101 expect(find.barProps.status).toBeNull();
102 expect(find.timelineProps.activeFindMatch).toEqual(partial.match);
@@ -125,7 +109,7 @@ describe("V2 find state", () => {
109 });
110 expect(orchestrationEnvironment.threadFindProgressive).toHaveBeenCalledTimes(requests);
111 queries.results.set(a, { ...partial, complete: true, totalMatches: 123, activeIndex: 42 });
128 - await act(async () => renderer?.update(<Probe environmentId={a} progressive />));
112 + await screen.rerender(<Probe environmentId={a} progressive />);
113 expect(find.barProps.counting).toBe(false);
114 expect(find.barProps.matchCount).toBe(123);
115 expect(find.barProps.activeIndex).toBe(42);
@@ -133,33 +117,28 @@ describe("V2 find state", () => {
117 expect(find.timelineProps.findNavigationId).toBe(navigationId);
118 expect(orchestrationEnvironment.threadFind).not.toHaveBeenCalled();
119 queries.pending = false;
136 - await act(async () => renderer?.update(<Probe environmentId={a} progressive />));
120 + await screen.rerender(<Probe environmentId={a} progressive />);
121 await act(async () => find.barProps.onNext());
122 expect(orchestrationEnvironment.threadFindProgressive).toHaveBeenCalledTimes(requests + 1);
123 });
124
125 it("coalesces incoming pages until the progressive scan finishes", async () => {
142 - vi.useFakeTimers();
126 + setup();
127 + using _timers = fakeTimers();
128 queries.pending = true;
144 - await act(async () => {
145 - renderer = render(<Probe environmentId={a} progressive />);
146 - });
129 + await using screen = await render(<Probe environmentId={a} progressive />);
130 await act(async () => find.open());
131 await act(async () => find.barProps.onQueryChange("needle"));
132 queries.results.set(a, { ...messageResult(0), complete: false, totalMatches: 1 });
133 const content = { visibleTurnItems: [], runs: [] };
151 - await act(async () =>
152 - renderer?.update(<Probe environmentId={a} progressive content={content} />),
153 - );
134 + await screen.rerender(<Probe environmentId={a} progressive content={content} />);
135 const requests = vi.mocked(orchestrationEnvironment.threadFindProgressive).mock.calls.length;
136 await act(async () => vi.advanceTimersByTime(300));
137 expect(orchestrationEnvironment.threadFindProgressive).toHaveBeenCalledTimes(requests);
138 expect(queries.refresh).not.toHaveBeenCalled();
139 queries.results.set(a, messageResult(0));
140 queries.pending = false;
160 - await act(async () =>
161 - renderer?.update(<Probe environmentId={a} progressive content={content} />),
162 - );
141 + await screen.rerender(<Probe environmentId={a} progressive content={content} />);
142 expect(orchestrationEnvironment.threadFindProgressive).toHaveBeenCalledTimes(requests + 1);
143 expect(orchestrationEnvironment.threadFindProgressive).toHaveBeenLastCalledWith({
144 environmentId: a,
@@ -174,10 +153,9 @@ describe("V2 find state", () => {
153 });
154
155 it("requests a fresh jump when the same search wraps to the same match from a new position", async () => {
156 + setup();
157 queries.results.set(a, messageResult(0));
178 - await act(async () => {
179 - renderer = render(<Probe environmentId={a} />);
180 - });
158 + await using _screen = await render(<Probe environmentId={a} />);
159 await act(async () => find.open());
160 find.timelineProps.findPositionReaderRef.current = () => ({
161 entryId: "reading",
@@ -214,6 +192,7 @@ describe("V2 find state", () => {
192 });
193
194 it("cycles cached entries immediately, wraps, and accumulates clicks in one event", async () => {
195 + setup();
196 const initial = {
197 ...messageResult(0),
198 totalMatches: 5,
@@ -224,9 +203,7 @@ describe("V2 find state", () => {
203 ],
204 };
205 queries.results.set(a, initial);
227 - await act(async () => {
228 - renderer = render(<Probe environmentId={a} />);
229 - });
206 + await using _screen = await render(<Probe environmentId={a} />);
207 await act(async () => find.open());
208 await act(async () => find.barProps.onQueryChange("COD4"));
209 const requests = vi.mocked(orchestrationEnvironment.threadFind).mock.calls.length;
@@ -252,15 +229,14 @@ describe("V2 find state", () => {
229 });
230
231 it("does not let an older background response undo a cached step", async () => {
232 + setup();
233 const initial = {
234 ...messageResult(0),
235 match: { entryId: "first", runId, occurrence: 0 },
236 navigation: [{ entryId: "first", runId, startIndex: 0, count: 3 }],
237 };
238 queries.results.set(a, initial);
261 - await act(async () => {
262 - renderer = render(<Probe environmentId={a} />);
263 - });
239 + await using screen = await render(<Probe environmentId={a} />);
240 await act(async () => find.open());
241 await act(async () => find.barProps.onQueryChange("COD4"));
242 const requests = vi.mocked(orchestrationEnvironment.threadFind).mock.calls.length;
@@ -272,7 +248,7 @@ describe("V2 find state", () => {
248 activeIndex: 1,
249 navigation: [{ entryId: "first", runId, startIndex: 1, count: 3 }],
250 });
275 - await act(async () => renderer?.update(<Probe environmentId={a} />));
251 + await screen.rerender(<Probe environmentId={a} />);
252 expect(find.timelineProps.activeFindMatch).toEqual({ entryId: "first", runId, occurrence: 1 });
253 expect(find.barProps.activeIndex).toBe(2);
254 expect(find.barProps.matchCount).toBe(11);
@@ -284,15 +260,14 @@ describe("V2 find state", () => {
260 });
261
262 it("fetches the next window from the locally selected match and retains it while pending", async () => {
263 + setup();
264 const initial = {
265 ...messageResult(0),
266 match: { entryId: "first", runId, occurrence: 0 },
267 navigation: [{ entryId: "first", runId, startIndex: 0, count: 2 }],
268 };
269 queries.results.set(a, initial);
293 - await act(async () => {
294 - renderer = render(<Probe environmentId={a} />);
295 - });
270 + await using screen = await render(<Probe environmentId={a} />);
271 await act(async () => find.open());
272 await act(async () => find.barProps.onQueryChange("COD4"));
273 await act(async () => find.barProps.onNext());
@@ -317,13 +292,14 @@ describe("V2 find state", () => {
292 expect(find.timelineProps.findNavigationId).toBe(2);
293 queries.pending = false;
294 queries.results.set(a, messageResult(3));
320 - await act(async () => renderer?.update(<Probe environmentId={a} />));
295 + await screen.rerender(<Probe environmentId={a} />);
296 expect(find.barProps.activeIndex).toBe(3);
297 expect(find.timelineProps.findNavigationId).toBe(4);
298 });
299
300 it("refreshes around the cached selection when live matches are inserted before it", async () => {
326 - vi.useFakeTimers();
301 + setup();
302 + using _timers = fakeTimers();
303 const initial = {
304 ...messageResult(0),
305 match: { entryId: "first", runId, occurrence: 0 },
@@ -333,15 +309,13 @@ describe("V2 find state", () => {
309 ],
310 };
311 queries.results.set(a, initial);
336 - await act(async () => {
337 - renderer = render(<Probe environmentId={a} />);
338 - });
312 + await using screen = await render(<Probe environmentId={a} />);
313 await act(async () => find.open());
314 await act(async () => find.barProps.onQueryChange("COD4"));
315 await act(async () => find.barProps.onNext());
316 expect(find.timelineProps.activeFindMatch?.entryId).toBe("second");
317 const content = { runs: [], visibleTurnItems: [] };
344 - await act(async () => renderer?.update(<Probe environmentId={a} content={content} />));
318 + await screen.rerender(<Probe environmentId={a} content={content} />);
319 await act(async () => vi.advanceTimersByTime(300));
320 expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({
321 environmentId: a,
@@ -358,7 +332,7 @@ describe("V2 find state", () => {
332 { entryId: "second", runId, startIndex: 2, count: 1 },
333 ],
334 });
361 - await act(async () => renderer?.update(<Probe environmentId={a} content={content} />));
335 + await screen.rerender(<Probe environmentId={a} content={content} />);
336 expect(find.barProps.matchCount).toBe(11);
337 expect(find.barProps.activeIndex).toBe(2);
338 expect(find.timelineProps.activeFindMatch?.entryId).toBe("second");
@@ -368,19 +342,16 @@ describe("V2 find state", () => {
342 });
343
344 it("asks the server rather than using stale navigation counts during live updates", async () => {
345 + setup();
346 const initial = {
347 ...messageResult(0),
348 navigation: [{ entryId: "message:2", runId, startIndex: 0, count: 10 }],
349 };
350 queries.results.set(a, initial);
376 - await act(async () => {
377 - renderer = render(<Probe environmentId={a} />);
378 - });
351 + await using screen = await render(<Probe environmentId={a} />);
352 await act(async () => find.open());
353 await act(async () => find.barProps.onQueryChange("COD4"));
381 - await act(async () =>
382 - renderer?.update(<Probe environmentId={a} content={{ runs: [], visibleTurnItems: [] }} />),
383 - );
354 + await screen.rerender(<Probe environmentId={a} content={{ runs: [], visibleTurnItems: [] }} />);
355 await act(async () => find.barProps.onNext());
356 expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({
357 environmentId: a,
@@ -395,10 +366,9 @@ describe("V2 find state", () => {
366 });
367
368 it("starts from the viewport and steps from the server-selected match", async () => {
369 + setup();
370 queries.results.set(a, messageResult(4));
399 - await act(async () => {
400 - renderer = render(<Probe environmentId={a} />);
401 - });
371 + await using _screen = await render(<Probe environmentId={a} />);
372 await act(async () => find.open());
373 find.timelineProps.findPositionReaderRef.current = () => ({
374 entryId: "message:6",
@@ -444,10 +414,9 @@ describe("V2 find state", () => {
414 });
415
416 it("accumulates rapid navigation against the same match until the response arrives", async () => {
417 + setup();
418 queries.results.set(a, messageResult(4));
448 - await act(async () => {
449 - renderer = render(<Probe environmentId={a} />);
450 - });
419 + await using screen = await render(<Probe environmentId={a} />);
420 await act(async () => find.open());
421 await act(async () => find.barProps.onQueryChange("COD4"));
422 queries.pending = true;
@@ -467,22 +436,21 @@ describe("V2 find state", () => {
436 expect(find.timelineProps.findNavigationId).toBe(1);
437 queries.pending = false;
438 queries.results.set(a, messageResult(6));
470 - await act(async () => renderer?.update(<Probe environmentId={a} />));
439 + await screen.rerender(<Probe environmentId={a} />);
440 expect(find.timelineProps.findNavigationId).toBe(3);
441 expect(find.barProps.activeIndex).toBe(6);
442 });
443
444 it("refreshes continuous updates without shifting the current match or showing Searching", async () => {
476 - vi.useFakeTimers();
445 + setup();
446 + using _timers = fakeTimers();
447 queries.results.set(a, messageResult(4));
478 - await act(async () => {
479 - renderer = render(<Probe environmentId={a} />);
480 - });
448 + await using screen = await render(<Probe environmentId={a} />);
449 await act(async () => find.open());
450 await act(async () => find.barProps.onQueryChange("COD4"));
451 for (let i = 0; i < 3; i++) {
484 - await act(async () =>
485 - renderer?.update(<Probe environmentId={a} content={{ visibleTurnItems: [], runs: [] }} />),
452 + await screen.rerender(
453 + <Probe environmentId={a} content={{ visibleTurnItems: [], runs: [] }} />,
454 );
455 await act(async () => vi.advanceTimersByTime(100));
456 }
@@ -497,7 +465,7 @@ describe("V2 find state", () => {
465 });
466 const updated = { ...messageResult(5, 10), totalMatches: 11, match: messageResult(4).match };
467 queries.results.set(a, updated);
500 - await act(async () => renderer?.update(<Probe environmentId={a} />));
468 + await screen.rerender(<Probe environmentId={a} />);
469 expect(find.barProps.matchCount).toBe(11);
470 expect(find.barProps.activeIndex).toBe(5);
471 expect(find.timelineProps.activeFindMatch?.entryId).toBe("message:6");
@@ -517,19 +485,16 @@ describe("V2 find state", () => {
485 });
486
487 it("keeps pending navigation when incoming content triggers a refresh", async () => {
520 - vi.useFakeTimers();
488 + setup();
489 + using _timers = fakeTimers();
490 queries.results.set(a, messageResult(4));
522 - await act(async () => {
523 - renderer = render(<Probe environmentId={a} />);
524 - });
491 + await using screen = await render(<Probe environmentId={a} />);
492 await act(async () => find.open());
493 await act(async () => find.barProps.onQueryChange("COD4"));
494 queries.pending = true;
495 queries.results.delete(a);
496 await act(async () => find.barProps.onNext());
530 - await act(async () =>
531 - renderer?.update(<Probe environmentId={a} content={{ visibleTurnItems: [], runs: [] }} />),
532 - );
497 + await screen.rerender(<Probe environmentId={a} content={{ visibleTurnItems: [], runs: [] }} />);
498 await act(async () => vi.advanceTimersByTime(300));
499 expect(queries.refresh).toHaveBeenCalledTimes(1);
500 expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({
@@ -544,17 +509,16 @@ describe("V2 find state", () => {
509 });
510 queries.pending = false;
511 queries.results.set(a, { ...messageResult(6, 10), totalMatches: 11 });
547 - await act(async () => renderer?.update(<Probe environmentId={a} />));
512 + await screen.rerender(<Probe environmentId={a} />);
513 expect(find.timelineProps.activeFindMatch?.entryId).toBe("message:8");
514 expect(find.timelineProps.findNavigationId).toBe(2);
515 expect(find.barProps.matchCount).toBe(11);
516 });
517
518 it("does not navigate the previous result while a new match is loading", async () => {
519 + setup();
520 queries.results.set(a, messageResult(0));
555 - await act(async () => {
556 - renderer = render(<Probe environmentId={a} />);
557 - });
521 + await using screen = await render(<Probe environmentId={a} />);
522 await act(async () => find.open());
523 await act(async () => find.barProps.onQueryChange("COD4"));
524 queries.pending = true;
@@ -567,16 +531,15 @@ describe("V2 find state", () => {
531 expect(find.barProps.matchCount).toBe(10);
532 queries.pending = false;
533 queries.results.set(a, messageResult(1));
570 - await act(async () => renderer?.update(<Probe environmentId={a} />));
534 + await screen.rerender(<Probe environmentId={a} />);
535 expect(find.timelineProps.activeFindMatch?.entryId).toBe("message:3");
536 expect(find.timelineProps.findNavigationId).toBe(2);
537 });
538
539 it("keeps the reading-position start when Enter is pressed before results arrive", async () => {
540 + setup();
541 queries.pending = true;
577 - await act(async () => {
578 - renderer = render(<Probe environmentId={a} />);
579 - });
542 + await using _screen = await render(<Probe environmentId={a} />);
543 await act(async () => find.open());
544 find.timelineProps.findPositionReaderRef.current = () => ({
545 entryId: "message:6",
@@ -596,16 +559,15 @@ describe("V2 find state", () => {
559 });
560
561 it("shows Searching only when the query has no result yet", async () => {
562 + setup();
563 queries.pending = true;
600 - await act(async () => {
601 - renderer = render(<Probe environmentId={a} />);
602 - });
564 + await using screen = await render(<Probe environmentId={a} />);
565 await act(async () => find.open());
566 await act(async () => find.barProps.onQueryChange("COD4"));
567 expect(find.barProps.status).toBe("loading");
568 queries.pending = false;
569 queries.results.set(a, messageResult(0));
608 - await act(async () => renderer?.update(<Probe environmentId={a} />));
570 + await screen.rerender(<Probe environmentId={a} />);
571 expect(find.barProps.status).toBeNull();
572 queries.pending = true;
573 queries.results.delete(a);
@@ -620,9 +582,8 @@ describe("V2 find state", () => {
582 });
583
584 it("keeps search unavailable when the server does not support it", async () => {
623 - await act(async () => {
624 - renderer = render(<Probe environmentId={a} enabled={false} />);
625 - });
585 + setup();
586 + await using _screen = await render(<Probe environmentId={a} enabled={false} />);
587 await act(async () => {
588 find.open();
589 requestThreadFindOpen();
@@ -633,38 +594,32 @@ describe("V2 find state", () => {
594 });
595
596 it("closes search when support disappears without restoring stale queries", async () => {
636 - await act(async () => {
637 - renderer = render(<Probe environmentId={a} />);
638 - });
597 + setup();
598 + await using screen = await render(<Probe environmentId={a} />);
599 await act(async () => find.open());
600 await act(async () => find.barProps.onQueryChange("needle"));
601 expect(find.isOpen).toBe(true);
602 vi.mocked(orchestrationEnvironment.threadFind).mockClear();
643 - await act(async () => {
644 - renderer?.update(<Probe environmentId={a} enabled={false} />);
645 - });
603 + await screen.rerender(<Probe environmentId={a} enabled={false} />);
604 expect(find.isOpen).toBe(false);
605 expect(find.timelineProps.activeFindMatch).toBeNull();
606 expect(find.timelineProps.findQuery).toBe("");
607 expect(orchestrationEnvironment.threadFind).not.toHaveBeenCalled();
650 - await act(async () => {
651 - renderer?.update(<Probe environmentId={a} />);
652 - });
608 + await screen.rerender(<Probe environmentId={a} />);
609 expect(find.isOpen).toBe(false);
610 await act(async () => find.open());
611 expect(find.barProps.query).toBe("");
612 });
613
614 it("preserves plan item ID and run ownership for navigation", async () => {
615 + setup();
616 queries.results.set(a, {
617 snapshotSequence: 9,
618 totalMatches: 1,
619 activeIndex: 0,
620 match: { entryId: "plan-item", runId, occurrence: 0 },
621 });
665 - await act(async () => {
666 - renderer = render(<Probe environmentId={a} />);
667 - });
622 + await using _screen = await render(<Probe environmentId={a} />);
623 await act(async () => {
624 find.open();
625 });
@@ -684,6 +639,7 @@ describe("V2 find state", () => {
639 });
640
641 it("drops results on environment changes even when the thread IDs are identical", async () => {
642 + setup();
643 queries.results.set(a, {
644 snapshotSequence: 1,
645 totalMatches: 3,
@@ -696,9 +652,7 @@ describe("V2 find state", () => {
652 activeIndex: 0,
653 match: null,
654 });
699 - await act(async () => {
700 - renderer = render(<Probe environmentId={a} />);
701 - });
655 + await using screen = await render(<Probe environmentId={a} />);
656 await act(async () => {
657 find.open();
658 });
@@ -706,9 +660,7 @@ describe("V2 find state", () => {
660 find.barProps.onQueryChange("needle");
661 });
662 expect(find.barProps.matchCount).toBe(3);
709 - await act(async () => {
710 - renderer?.update(<Probe environmentId={b} />);
711 - });
663 + await screen.rerender(<Probe environmentId={b} />);
664 expect(find.isOpen).toBe(false);
665 expect(find.timelineProps.activeFindMatch).toBeNull();
666 await act(async () => {
@@ -718,9 +670,7 @@ describe("V2 find state", () => {
670 find.barProps.onQueryChange("needle");
671 });
672 expect(find.barProps.matchCount).toBe(0);
721 - await act(async () => {
722 - renderer?.update(<Probe environmentId={a} />);
723 - });
673 + await screen.rerender(<Probe environmentId={a} />);
674 expect(find.isOpen).toBe(false);
675 });
676 });
apps/web/src/components/chat/useThreadFindNavigation.browser.test.tsx
+107 -116
@@ -1,7 +1,8 @@
1 import type { LegendListRef } from "@legendapp/list/react";
2 -import { act, type ComponentProps } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2 +import type { ComponentProps } from "react";
3 +import { describe, expect, it, vi } from "vite-plus/test";
4 +
5 +import { act, render, stubGlobal } from "../../../test/render";
6 import { useThreadFindNavigation } from "./useThreadFindNavigation";
7
8 const renders = vi.fn();
@@ -11,37 +12,39 @@ function Probe(props: Parameters<typeof useThreadFindNavigation>[0]) {
12 return null;
13 }
14
14 -let root: Root;
15 -let host: HTMLDivElement;
15 let container: HTMLDivElement;
16 let rect: DOMRect;
17 const scrollToIndex = vi.fn<LegendListRef["scrollToIndex"]>();
18 const scrollToOffset = vi.fn<LegendListRef["scrollToOffset"]>();
19 let props: ComponentProps<typeof Probe>;
20
22 -beforeEach(() => {
23 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
24 - vi.stubGlobal("CSS", { highlights: new Map() });
25 - vi.stubGlobal(
26 - "Highlight",
27 - class extends Set<Range> {
28 - constructor(...ranges: Range[]) {
29 - super(ranges);
30 - }
31 - },
21 +function setup() {
22 + vi.clearAllMocks();
23 + using stack = new DisposableStack();
24 + stack.use(stubGlobal("CSS", { highlights: new Map() }));
25 + stack.use(
26 + stubGlobal(
27 + "Highlight",
28 + class extends Set<Range> {
29 + constructor(...ranges: Range[]) {
30 + super(ranges);
31 + }
32 + },
33 + ),
34 );
35 rect = new DOMRect(0, 200, 40, 20);
36 Object.defineProperty(Range.prototype, "getBoundingClientRect", {
37 configurable: true,
38 value: () => rect,
39 });
38 - host = document.createElement("div");
40 + stack.defer(() => Reflect.deleteProperty(Range.prototype, "getBoundingClientRect"));
41 container = document.createElement("div");
42 container.innerHTML =
43 '<div data-timeline-row-id="message"><p data-thread-find-text>COD4 and COD4</p></div>';
44 container.getBoundingClientRect = () => new DOMRect(0, 0, 800, 600);
43 - document.body.append(host, container);
44 - root = createRoot(host);
45 + document.body.append(container);
46 + const ownContainer = container;
47 + stack.defer(() => ownContainer.remove());
48 scrollToIndex.mockResolvedValue();
49 props = {
50 container,
@@ -60,19 +63,14 @@ beforeEach(() => {
63 contentInsetEndAdjustment: 100,
64 listReady: true,
65 };
63 -});
66 + return stack.move();
67 +}
68
65 -afterEach(async () => {
66 - await act(async () => root.unmount());
67 - host.remove();
68 - container.remove();
69 - Reflect.deleteProperty(Range.prototype, "getBoundingClientRect");
70 - vi.clearAllMocks();
71 - vi.unstubAllGlobals();
72 -});
69 +const nextFrame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
70
71 describe("find result navigation", () => {
72 it("retargets a pending first jump when progressive history moves the matching row", async () => {
73 + using _environment = setup();
74 container.replaceChildren();
75 let first!: () => void;
76 let second!: () => void;
@@ -89,9 +87,9 @@ describe("find result navigation", () => {
87 second = resolve;
88 }),
89 );
92 - await act(async () => root.render(<Probe {...props} rowIndex={2} />));
93 - await act(async () =>
94 - root.render(<Probe {...props} rowIndex={6} entries={[{ id: "tool" }, ...props.entries]} />),
90 + await using screen = await render(<Probe {...props} rowIndex={2} />);
91 + await screen.rerender(
92 + <Probe {...props} rowIndex={6} entries={[{ id: "tool" }, ...props.entries]} />,
93 );
94 expect(scrollToIndex.mock.calls.map(([request]) => request.index)).toEqual([2, 6]);
95 await act(async () => first());
@@ -101,59 +99,58 @@ describe("find result navigation", () => {
99 '<div data-timeline-row-id="message"><p data-thread-find-text>COD4</p></div>';
100 rect = new DOMRect(0, 450, 40, 20);
101 second();
104 - await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
102 + await nextFrame();
103 });
104 expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 366, animated: false });
105 });
106
107 it("keeps the highlighted text at the same position when progressive activity arrives", async () => {
108 + using _environment = setup();
109 const historyControls = {
110 hasMoreHistory: true,
111 loading: true,
112 error: null,
113 onLoadEarlier: vi.fn(),
114 };
116 - await act(async () => root.render(<Probe {...props} historyControls={historyControls} />));
115 + await using screen = await render(<Probe {...props} historyControls={historyControls} />);
116 rect = new DOMRect(0, 368, 40, 20);
117 scrollToOffset.mockImplementationOnce(async () => {
118 rect = new DOMRect(0, 200, 40, 20);
119 });
121 - await act(async () =>
122 - root.render(
123 - <Probe
124 - {...props}
125 - entries={[{ id: "tool" }, { id: "message" }]}
126 - historyControls={{ ...historyControls, loading: false }}
127 - />,
128 - ),
120 + await screen.rerender(
121 + <Probe
122 + {...props}
123 + entries={[{ id: "tool" }, { id: "message" }]}
124 + historyControls={{ ...historyControls, loading: false }}
125 + />,
126 );
127 expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 468, animated: false });
128 expect(scrollToIndex).not.toHaveBeenCalled();
129 });
130
131 it("respects scrolling away from a partial match before activity arrives", async () => {
132 + using _environment = setup();
133 const historyControls = {
134 hasMoreHistory: true,
135 loading: true,
136 error: null,
137 onLoadEarlier: vi.fn(),
138 };
141 - await act(async () => root.render(<Probe {...props} historyControls={historyControls} />));
139 + await using screen = await render(<Probe {...props} historyControls={historyControls} />);
140 rect = new DOMRect(0, -600, 40, 20);
141 container.dispatchEvent(new Event("scroll"));
144 - await act(async () =>
145 - root.render(
146 - <Probe
147 - {...props}
148 - entries={[{ id: "tool" }, { id: "message" }]}
149 - historyControls={{ ...historyControls, loading: false }}
150 - />,
151 - ),
142 + await screen.rerender(
143 + <Probe
144 + {...props}
145 + entries={[{ id: "tool" }, { id: "message" }]}
146 + historyControls={{ ...historyControls, loading: false }}
147 + />,
148 );
149 expect(scrollToOffset).not.toHaveBeenCalled();
150 });
151
152 it("reveals settled virtual text without another timeline render", async () => {
153 + using _environment = setup();
154 let complete!: () => void;
155 scrollToIndex.mockImplementationOnce(
156 () =>
@@ -162,19 +159,20 @@ describe("find result navigation", () => {
159 }),
160 );
161 rect = new DOMRect(0, 1800, 40, 20);
165 - await act(async () => root.render(<Probe {...props} />));
162 + await using _screen = await render(<Probe {...props} />);
163 expect(renders).toHaveBeenCalledTimes(1);
164 expect(scrollToOffset).not.toHaveBeenCalled();
165 rect = new DOMRect(0, 450, 40, 20);
166 await act(async () => {
167 complete();
171 - await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
168 + await nextFrame();
169 });
170 expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 366, animated: false });
171 expect(renders).toHaveBeenCalledTimes(1);
172 });
173
174 it("ignores an older scroll completion after navigation moves to another occurrence", async () => {
175 + using _environment = setup();
176 let first!: () => void;
177 let second!: () => void;
178 scrollToIndex
@@ -191,72 +189,69 @@ describe("find result navigation", () => {
189 }),
190 );
191 rect = new DOMRect(0, 1800, 40, 20);
194 - await act(async () => root.render(<Probe {...props} />));
195 - await act(async () =>
196 - root.render(
197 - <Probe
198 - {...props}
199 - navigationId={1}
200 - match={{ entryId: "message", runId: null, occurrence: 1 }}
201 - />,
202 - ),
192 + await using screen = await render(<Probe {...props} />);
193 + await screen.rerender(
194 + <Probe
195 + {...props}
196 + navigationId={1}
197 + match={{ entryId: "message", runId: null, occurrence: 1 }}
198 + />,
199 );
200 rect = new DOMRect(0, 450, 40, 20);
201 await act(async () => first());
202 expect(scrollToOffset).not.toHaveBeenCalled();
203 await act(async () => {
204 second();
209 - await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
205 + await nextFrame();
206 });
207 expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 366, animated: false });
208 });
209
210 it("loads history until a distant match can be revealed in the conversation", async () => {
211 + using _environment = setup();
212 const onLoadEarlier = vi.fn();
213 const historyControls = { hasMoreHistory: true, loading: false, error: null, onLoadEarlier };
214 const pending = { ...props, rowIndex: -1, entries: [{ id: "recent" }], historyControls };
218 - await act(async () => root.render(<Probe {...pending} />));
215 + await using screen = await render(<Probe {...pending} />);
216 expect(onLoadEarlier).toHaveBeenCalledTimes(1);
217 expect(scrollToIndex).not.toHaveBeenCalled();
221 - await act(async () =>
222 - root.render(<Probe {...pending} historyControls={{ ...historyControls, loading: true }} />),
218 + await screen.rerender(
219 + <Probe {...pending} historyControls={{ ...historyControls, loading: true }} />,
220 );
221 expect(onLoadEarlier).toHaveBeenCalledTimes(1);
225 - await act(async () =>
226 - root.render(<Probe {...pending} entries={[{ id: "older" }, ...pending.entries]} />),
227 - );
222 + await screen.rerender(<Probe {...pending} entries={[{ id: "older" }, ...pending.entries]} />);
223 expect(onLoadEarlier).toHaveBeenCalledTimes(2);
224 rect = new DOMRect(0, 1800, 40, 20);
225 scrollToIndex.mockImplementationOnce(async () => {
226 rect = new DOMRect(0, 200, 40, 20);
227 });
233 - await act(async () => root.render(<Probe {...props} historyControls={historyControls} />));
228 + await screen.rerender(<Probe {...props} historyControls={historyControls} />);
229 expect(onLoadEarlier).toHaveBeenCalledTimes(2);
230 expect(scrollToIndex).toHaveBeenCalledTimes(1);
231 });
232
233 it("waits for list bootstrap before positioning the first result", async () => {
234 + using _environment = setup();
235 rect = new DOMRect(0, 1800, 40, 20);
240 - await act(async () => root.render(<Probe {...props} listReady={false} />));
236 + await using screen = await render(<Probe {...props} listReady={false} />);
237 expect(scrollToIndex).not.toHaveBeenCalled();
238 expect(scrollToOffset).not.toHaveBeenCalled();
239 scrollToIndex.mockImplementationOnce(async () => {
240 rect = new DOMRect(0, 200, 40, 20);
241 });
246 - await act(async () => root.render(<Probe {...props} />));
242 + await screen.rerender(<Probe {...props} />);
243 expect(scrollToIndex).toHaveBeenCalledTimes(1);
244 expect(scrollToOffset).not.toHaveBeenCalled();
245 });
246 it("leaves the scroll position unchanged between already visible occurrences", async () => {
251 - await act(async () => root.render(<Probe {...props} />));
252 - await act(async () =>
253 - root.render(
254 - <Probe
255 - {...props}
256 - navigationId={1}
257 - match={{ entryId: "message", runId: null, occurrence: 1 }}
258 - />,
259 - ),
247 + using _environment = setup();
248 + await using screen = await render(<Probe {...props} />);
249 + await screen.rerender(
250 + <Probe
251 + {...props}
252 + navigationId={1}
253 + match={{ entryId: "message", runId: null, occurrence: 1 }}
254 + />,
255 );
256 expect(scrollToIndex).not.toHaveBeenCalled();
257 expect(scrollToOffset).not.toHaveBeenCalled();
@@ -268,14 +263,15 @@ describe("find result navigation", () => {
263 });
264
265 it("reveals the same match again when search restarts after scrolling away", async () => {
271 - await act(async () => root.render(<Probe {...props} />));
266 + using _environment = setup();
267 + await using screen = await render(<Probe {...props} />);
268 rect = new DOMRect(0, -1800, 40, 20);
269 props.listRef.current = {
270 scrollToIndex,
271 scrollToOffset,
272 getState: () => ({ scroll: 2400 }),
273 } as unknown as LegendListRef;
278 - await act(async () => root.render(<Probe {...props} navigationId={1} />));
274 + await screen.rerender(<Probe {...props} navigationId={1} />);
275 expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 504, animated: false });
276 expect(scrollToIndex).not.toHaveBeenCalled();
277 expect(
@@ -284,38 +280,37 @@ describe("find result navigation", () => {
280 });
281
282 it("moves only far enough to reveal text below the composer", async () => {
287 - await act(async () => root.render(<Probe {...props} />));
283 + using _environment = setup();
284 + await using screen = await render(<Probe {...props} />);
285 rect = new DOMRect(0, 450, 40, 20);
289 - await act(async () =>
290 - root.render(
291 - <Probe
292 - {...props}
293 - navigationId={1}
294 - match={{ entryId: "message", runId: null, occurrence: 1 }}
295 - />,
296 - ),
286 + await screen.rerender(
287 + <Probe
288 + {...props}
289 + navigationId={1}
290 + match={{ entryId: "message", runId: null, occurrence: 1 }}
291 + />,
292 );
293 expect(scrollToIndex).not.toHaveBeenCalled();
294 expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 366, animated: false });
295 });
296
297 it("moves only far enough to reveal text above the viewport margin", async () => {
303 - await act(async () => root.render(<Probe {...props} />));
298 + using _environment = setup();
299 + await using screen = await render(<Probe {...props} />);
300 rect = new DOMRect(0, 40, 40, 20);
305 - await act(async () =>
306 - root.render(
307 - <Probe
308 - {...props}
309 - navigationId={1}
310 - match={{ entryId: "message", runId: null, occurrence: 1 }}
311 - />,
312 - ),
301 + await screen.rerender(
302 + <Probe
303 + {...props}
304 + navigationId={1}
305 + match={{ entryId: "message", runId: null, occurrence: 1 }}
306 + />,
307 );
308 expect(scrollToIndex).not.toHaveBeenCalled();
309 expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 244, animated: false });
310 });
311
312 it("keeps the selected text visible when newly measured rows shift during scrolling", async () => {
313 + using _environment = setup();
314 let scroll = 300;
315 props.listRef.current = {
316 scrollToIndex,
@@ -330,16 +325,14 @@ describe("find result navigation", () => {
325 scroll = offset;
326 rect = new DOMRect(0, 200, 40, 20);
327 });
333 - await act(async () => root.render(<Probe {...props} />));
328 + await using screen = await render(<Probe {...props} />);
329 rect = new DOMRect(0, 450, 40, 20);
335 - await act(async () =>
336 - root.render(
337 - <Probe
338 - {...props}
339 - navigationId={1}
340 - match={{ entryId: "message", runId: null, occurrence: 1 }}
341 - />,
342 - ),
330 + await screen.rerender(
331 + <Probe
332 + {...props}
333 + navigationId={1}
334 + match={{ entryId: "message", runId: null, occurrence: 1 }}
335 + />,
336 );
337 await act(async () => {
338 await new Promise<void>((resolve) =>
@@ -355,23 +348,21 @@ describe("find result navigation", () => {
348 });
349
350 it("waits for a new context window to settle before revealing an offscreen result", async () => {
351 + using _environment = setup();
352 rect = new DOMRect(0, 1800, 40, 20);
353 scrollToIndex.mockImplementationOnce(async () => {
354 rect = new DOMRect(0, 450, 40, 20);
355 });
362 - await act(async () => {
363 - root.render(<Probe {...props} />);
364 - });
365 - await act(async () => {
366 - await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
367 - });
356 + await using _screen = await render(<Probe {...props} />);
357 + await act(nextFrame);
358 expect(scrollToIndex).toHaveBeenCalledTimes(1);
359 expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 366, animated: false });
360 });
361
362 it("materializes a virtualized message before revealing its occurrence", async () => {
363 + using _environment = setup();
364 container.replaceChildren();
374 - await act(async () => root.render(<Probe {...props} rowIndex={4} />));
365 + await using _screen = await render(<Probe {...props} rowIndex={4} />);
366 expect(scrollToIndex).toHaveBeenCalledExactlyOnceWith({
367 index: 4,
368 animated: false,
@@ -382,7 +373,7 @@ describe("find result navigation", () => {
373 await act(async () => {
374 container.innerHTML =
375 '<div data-timeline-row-id="message"><p data-thread-find-text>COD4</p></div>';
385 - await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
376 + await nextFrame();
377 });
378 expect(scrollToIndex).toHaveBeenCalledTimes(1);
379 expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 366, animated: false });
apps/web/src/components/cloud/CloudEnvironmentConnectList.browser.test.tsx
+35 -38
@@ -3,9 +3,10 @@ import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
3 import { EnvironmentId, ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";
4 import * as Option from "effect/Option";
5 import { AsyncResult } from "effect/reactivity";
6 -import { act, useState } from "react";
7 -import { createRoot, type Root } from "react-dom/client";
8 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
6 +import { useState, type ReactElement } from "react";
7 +import { describe, expect, it, vi } from "vite-plus/test";
8 +
9 +import { act, fakeTimers, render } from "../../../test/render";
10
11 type DiscoveredEnvironments = Discovery.RelayEnvironmentDiscoveryState["environments"];
12
@@ -67,7 +68,6 @@ const linkedMachines: DiscoveredEnvironments = new Map([
68 ],
69 ]);
70
70 -let root: Root | null;
71 let container: HTMLDivElement;
72 let visibility: DocumentVisibilityState;
73
@@ -76,13 +76,10 @@ function publish(state: Discovery.RelayEnvironmentDiscoveryState) {
76 for (const listener of discovery.listeners) listener();
77 }
78
79 -async function render(element: React.ReactElement) {
80 - root ??= createRoot(container);
81 - await act(async () => root!.render(element));
82 -}
79 +const renderRows = (element: ReactElement) => render(element, { container });
80
84 -async function mount(refreshWhileEmpty = true) {
85 - await render(
81 +function mount(refreshWhileEmpty = true) {
82 + return renderRows(
83 <CloudEnvironmentConnectRows
84 primaryEnvironmentId={null}
85 savedEnvironments={[]}
@@ -110,14 +107,12 @@ async function advance(milliseconds: number) {
107 });
108 }
109
113 -beforeEach(() => {
114 - vi.useFakeTimers();
115 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
110 +function setup() {
111 + using stack = new DisposableStack();
112 + stack.use(fakeTimers());
113 visibility = "visible";
117 - vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility);
114 + stack.use(vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility));
115 container = document.createElement("div");
119 - document.body.append(container);
120 - root = null;
116 discovery.listeners.clear();
117 discovery.state = {
118 environments: new Map(),
@@ -133,18 +128,12 @@ beforeEach(() => {
128 publish({ environments, refreshing: false, offline: false, error: Option.none() });
129 return AsyncResult.success(undefined);
130 });
136 -});
137 -
138 -afterEach(async () => {
139 - await act(async () => root?.unmount());
140 - container.remove();
141 - vi.useRealTimers();
142 - vi.restoreAllMocks();
143 - vi.unstubAllGlobals();
144 -});
131 + return stack.move();
132 +}
133
134 describe("cloud environment offline reasons", () => {
135 it("tells the user to update a computer whose idle tunnel was removed", async () => {
136 + using _environment = setup();
137 const base = linkedMachines.get(newMachineId)!;
138 const offlineEntry = (offlineReason?: "tunnel_released") => ({
139 ...base,
@@ -160,7 +149,7 @@ describe("cloud environment offline reasons", () => {
149 });
150
151 discovery.listEnvironments.mockResolvedValue(new Map([[newMachineId, offlineEntry()]]));
163 - await mount();
152 + await using _screen = await mount();
153 expect(text()).toContain("T3 Connect · Not added · Relay offline");
154
155 await act(async () => {
@@ -177,6 +166,7 @@ describe("cloud environment offline reasons", () => {
166
167 describe("cloud onboarding discovery", () => {
168 it("signals that the section can expand after initial discovery settles", async () => {
169 + using _environment = setup();
170 let finishDiscovery!: (environments: DiscoveredEnvironments) => void;
171 discovery.listEnvironments.mockReturnValue(
172 new Promise((resolve) => {
@@ -184,7 +174,7 @@ describe("cloud onboarding discovery", () => {
174 }),
175 );
176 const onDiscoveryReady = vi.fn();
187 - await render(
177 + await using _screen = await renderRows(
178 <CloudEnvironmentConnectRows
179 primaryEnvironmentId={null}
180 savedEnvironments={[]}
@@ -200,6 +190,7 @@ describe("cloud onboarding discovery", () => {
190 });
191
192 it("keeps incompatible discoveries unselected until the user enables a compatible server", async () => {
193 + using _environment = setup();
194 const base = linkedMachines.get(newMachineId)!;
195 const entry = (protocolVersion: number) => ({
196 ...base,
@@ -248,7 +239,7 @@ describe("cloud onboarding discovery", () => {
239 />
240 );
241 }
251 - await render(<Setup />);
242 + await using _screen = await renderRows(<Setup />);
243 expect(discovery.register).not.toHaveBeenCalled();
244 expect(onSelectionChange).toHaveBeenCalledWith(newMachineId, false);
245 expect(checked()).toBe(false);
@@ -271,6 +262,7 @@ describe("cloud onboarding discovery", () => {
262 });
263
264 it("connects and selects discovered computers by default without overwriting deselection", async () => {
265 + using _environment = setup();
266 discovery.listEnvironments.mockResolvedValue(linkedMachines);
267 const autoSelectedComputers = new Set<EnvironmentId>();
268 function Setup() {
@@ -294,7 +286,7 @@ describe("cloud onboarding discovery", () => {
286 />
287 );
288 }
297 - await render(<Setup />);
289 + await using _screen = await renderRows(<Setup />);
290
291 expect(discovery.register).toHaveBeenCalledTimes(1);
292 expect(checked()).toBe(true);
@@ -307,10 +299,11 @@ describe("cloud onboarding discovery", () => {
299 });
300
301 it("shows a newly linked computer without remounting and stops polling once found", async () => {
302 + using _environment = setup();
303 discovery.listEnvironments
304 .mockResolvedValueOnce(new Map())
305 .mockResolvedValueOnce(linkedMachines);
313 - await mount();
306 + await using _screen = await mount();
307 expect(text()).toBe("Waiting for your computer to connect.");
308
309 await advance(5_000);
@@ -322,10 +315,11 @@ describe("cloud onboarding discovery", () => {
315 });
316
317 it("keeps a discovered computer visible when it is added to the browser", async () => {
318 + using _environment = setup();
319 discovery.listEnvironments.mockResolvedValue(linkedMachines);
326 - await mount();
320 + await using screen = await mount();
321 expect(button()?.textContent).toBe("Add");
328 - await render(
322 + await screen.rerender(
323 <CloudEnvironmentConnectRows
324 primaryEnvironmentId={null}
325 savedEnvironments={[
@@ -344,8 +338,9 @@ describe("cloud onboarding discovery", () => {
338 });
339
340 it("waits while hidden and refreshes immediately when visible again", async () => {
341 + using _environment = setup();
342 visibility = "hidden";
348 - await mount();
343 + await using _screen = await mount();
344 await advance(30_000);
345 expect(discovery.listEnvironments).not.toHaveBeenCalled();
346
@@ -359,12 +354,13 @@ describe("cloud onboarding discovery", () => {
354 });
355
356 it("does not overlap a slow refresh or restart polling after unmount", async () => {
357 + using _environment = setup();
358 let resolveRefresh!: (environments: DiscoveredEnvironments) => void;
359 const pending = new Promise<DiscoveredEnvironments>((resolve) => {
360 resolveRefresh = resolve;
361 });
362 discovery.listEnvironments.mockResolvedValueOnce(new Map()).mockReturnValueOnce(pending);
367 - await mount();
363 + await using screen = await mount();
364 await advance(5_000);
365 expect(text()).toBe("Waiting for your computer to connect.");
366
@@ -373,15 +369,15 @@ describe("cloud onboarding discovery", () => {
369 await advance(30_000);
370 expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
371
376 - await act(async () => root!.unmount());
377 - root = null;
372 + await screen.unmount();
373 await act(async () => resolveRefresh(new Map()));
374 await advance(30_000);
375 expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
376 });
377
378 it("pauses while offline and resumes when discovery is online", async () => {
384 - await mount();
379 + using _environment = setup();
380 + await using _screen = await mount();
381 await act(async () => publish({ ...discovery.state!, offline: true }));
382 await advance(30_000);
383 expect(discovery.listEnvironments).toHaveBeenCalledTimes(1);
@@ -392,7 +388,8 @@ describe("cloud onboarding discovery", () => {
388 });
389
390 it("does not add polling to other cloud lists", async () => {
395 - await mount(false);
391 + using _environment = setup();
392 + await using _screen = await mount(false);
393 await advance(30_000);
394 expect(discovery.listEnvironments).toHaveBeenCalledTimes(1);
395 });
apps/web/src/components/desktop/DesktopWebLinkCoordinator.browser.test.tsx
+29 -29
@@ -1,8 +1,8 @@
1 import { EnvironmentId, ProjectId } from "@t3tools/contracts";
2 import type { Atom } from "effect/reactivity";
3 -import { act } from "react";
4 -import { createRoot, type Root } from "react-dom/client";
5 -import { afterEach, expect, it, vi } from "vite-plus/test";
3 +import { expect, it, vi } from "vite-plus/test";
4 +
5 +import { act, render, stubGlobal } from "../../../test/render";
6
7 const state = vi.hoisted(() => ({
8 projects: [] as never[],
@@ -87,44 +87,43 @@ const pullRequestView = {
87 },
88 };
89
90 -let root: Root;
90 +function setup() {
91 + vi.clearAllMocks();
92 + state.projects = [];
93 + appAtomRegistry.set(discoverySettled, false);
94 +}
95
96 /** Mounts the coordinator behind a desktop bridge that hands over `urls` once the renderer is ready. */
97 async function mount(...urls: string[]) {
98 let deliver: ((url: string) => void) | undefined;
95 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
96 - vi.stubGlobal("desktopBridge", {
97 - getClientSettings: async () => null,
98 - webLinks: {
99 - onOpen: (listener: (url: string) => void) => {
100 - deliver = listener;
101 - return () => undefined;
102 - },
103 - setReady: async (ready: boolean) => {
104 - if (ready) for (const url of urls.splice(0)) deliver?.(url);
99 + await using stack = new AsyncDisposableStack();
100 + stack.use(
101 + stubGlobal("desktopBridge", {
102 + getClientSettings: async () => null,
103 + webLinks: {
104 + onOpen: (listener: (url: string) => void) => {
105 + deliver = listener;
106 + return () => undefined;
107 + },
108 + setReady: async (ready: boolean) => {
109 + if (ready) for (const url of urls.splice(0)) deliver?.(url);
110 + },
111 },
106 - },
107 - });
108 - root = createRoot(document.createElement("div"));
109 - await act(async () =>
110 - root.render(
112 + }),
113 + );
114 + stack.use(
115 + await render(
116 <AppAtomRegistryProvider>
117 <DesktopWebLinkCoordinator />
118 </AppAtomRegistryProvider>,
119 ),
120 );
121 + return stack.move();
122 }
123
118 -afterEach(async () => {
119 - await act(async () => root.unmount());
120 - vi.unstubAllGlobals();
121 - vi.clearAllMocks();
122 - state.projects = [];
123 - appAtomRegistry.set(discoverySettled, false);
124 -});
125 -
124 it("holds a launch PR link until project discovery settles, then opens the PR view", async () => {
127 - await mount(pullRequestUrl);
125 + setup();
126 + await using _coordinator = await mount(pullRequestUrl);
127 expect(state.navigate).not.toHaveBeenCalled();
128 expect(state.openScratchProject).not.toHaveBeenCalled();
129
@@ -141,7 +140,8 @@ it("holds a launch PR link until project discovery settles, then opens the PR vi
140 });
141
142 it("opens an ordinary link in the browser while a PR link is still held", async () => {
144 - await mount(pullRequestUrl, "https://example.com/docs");
143 + setup();
144 + await using _coordinator = await mount(pullRequestUrl, "https://example.com/docs");
145 expect(state.openScratchProject).toHaveBeenCalledOnce();
146 expect(state.navigate).not.toHaveBeenCalled();
147 });
apps/web/src/components/device/DevicePanel.browser.test.tsx
+40 -45
@@ -4,12 +4,13 @@ import {
4 type DeviceServiceState,
5 type ScopedThreadRef,
6 } from "@t3tools/contracts";
7 -import { act, type ReactNode } from "react";
8 -import { createRoot, type Root } from "react-dom/client";
9 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
7 +import type { ReactNode } from "react";
8 +import { describe, expect, it, vi } from "vite-plus/test";
9
10 import type { RightPanelSurface } from "~/rightPanelStore";
11
12 +import { act, render } from "../../../test/render";
13 +
14 import { DevicePanel } from "./DevicePanel";
15 import "~/index.css";
16
@@ -120,22 +121,18 @@ const deferred = () => {
121 return { promise, settle };
122 };
123
123 -let root: Root;
124 let container: HTMLDivElement;
125 // Fixed key and a changing threadRef, as RightPanelSurfaceContent mounts it.
126 -const show = (threadRef: ScopedThreadRef, surface = picker) =>
127 - act(async () =>
128 - root.render(
129 - <DevicePanel
130 - key="device-panel"
131 - mode="embedded"
132 - threadRef={threadRef}
133 - surface={surface}
134 - visible
135 - onDismissSetup={() => undefined}
136 - />,
137 - ),
138 - );
126 +const devicePanel = (threadRef: ScopedThreadRef, surface = picker) => (
127 + <DevicePanel
128 + key="device-panel"
129 + mode="embedded"
130 + threadRef={threadRef}
131 + surface={surface}
132 + visible
133 + onDismissSetup={() => undefined}
134 + />
135 +);
136 const startButton = () => container.querySelector<HTMLButtonElement>('[aria-label="Start Phone"]');
137 const click = (button: HTMLButtonElement | null) =>
138 act(async () => {
@@ -143,48 +140,42 @@ const click = (button: HTMLButtonElement | null) =>
140 });
141 const errors = () => container.querySelectorAll('[role="alert"]');
142
146 -beforeEach(() => {
143 +function setup() {
144 vi.resetAllMocks();
145 currentState = deviceState;
149 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
146 container = document.createElement("div");
147 container.style.width = "480px";
148 container.style.height = "800px";
153 - document.body.append(container);
154 - root = createRoot(container);
155 -});
156 -afterEach(async () => {
157 - await act(() => root.unmount());
158 - container.remove();
159 - vi.unstubAllGlobals();
160 -});
149 +}
150
151 describe("DevicePanel notices", () => {
152 it("keeps discovery warnings dismissed until the diagnostic or environment changes", async () => {
153 + setup();
154 currentState = {
155 ...deviceState,
156 hostStatusDetail: "Could not read simulator usage timestamps.",
157 };
168 - await show(threadA);
158 + await using screen = await render(devicePanel(threadA), { container });
159 expect(errors()).toHaveLength(1);
160 expect(startButton()?.disabled).toBe(false);
161 await click(container.querySelector('[aria-label="Dismiss device warning"]'));
162 expect(errors()).toHaveLength(0);
173 - await show(threadA);
163 + await screen.rerender(devicePanel(threadA));
164 expect(errors()).toHaveLength(0);
165
166 currentState = { ...currentState, hostStatusDetail: "A different discovery warning." };
177 - await show(threadA);
167 + await screen.rerender(devicePanel(threadA));
168 expect(errors()).toHaveLength(1);
169 await click(container.querySelector('[aria-label="Dismiss device warning"]'));
180 - await show(otherEnvironment);
170 + await screen.rerender(devicePanel(otherEnvironment));
171 expect(errors()).toHaveLength(1);
172 });
173
174 it("keeps the loading content centered when discovery and boot notices arrive or are dismissed", async () => {
175 + setup();
176 const pick = deferred();
177 mocks.open.mockReturnValue(pick.promise);
187 - await show(threadA);
178 + await using screen = await render(devicePanel(threadA), { container });
179 await click(startButton());
180 const loadingBounds = () =>
181 container
@@ -200,7 +191,7 @@ describe("DevicePanel notices", () => {
191 hostStatusDetail: "Could not read CoreSimulator plist.\n".repeat(8),
192 bootingDevices: [{ ...phone, threadId: threadA.threadId }],
193 };
203 - await show(threadA);
194 + await screen.rerender(devicePanel(threadA));
195 expect(loadingBounds().top).toBe(before.top);
196 expect(loadingBounds().left).toBe(before.left);
197 await click(container.querySelector('[aria-label="Dismiss device warning"]'));
@@ -212,24 +203,25 @@ describe("DevicePanel notices", () => {
203
204 describe("DevicePanel thread switches", () => {
205 it.each(switches)("does not carry a pending or failed pick to %s", async (_, target) => {
206 + setup();
207 const pick = deferred();
208 mocks.open.mockReturnValue(pick.promise);
217 - await show(threadA);
209 + await using screen = await render(devicePanel(threadA), { container });
210 await click(startButton());
211 expect(startButton()).toBeNull();
212
221 - await show(target);
213 + await screen.rerender(devicePanel(target));
214 expect(startButton()?.disabled).toBe(false);
215
216 await act(async () => pick.settle(failed));
217 expect(errors()).toHaveLength(0);
218 expect(mocks.openDevice).not.toHaveBeenCalled();
219
228 - await show(threadA);
220 + await screen.rerender(devicePanel(threadA));
221 expect(startButton()?.disabled).toBe(false);
222 expect(errors()).toHaveLength(1);
223
232 - await show(target);
224 + await screen.rerender(devicePanel(target));
225 expect(startButton()?.disabled).toBe(false);
226 expect(errors()).toHaveLength(0);
227 });
@@ -252,12 +244,13 @@ describe("DevicePanel thread switches", () => {
244 ] as const)(
245 "applies a late %s to its starting thread after switching environments with the same thread id",
246 async (_, surface, command, start, expectApplied) => {
247 + setup();
248 const late = deferred();
249 command().mockReturnValue(late.promise);
257 - await show(threadA, surface);
250 + await using screen = await render(devicePanel(threadA, surface), { container });
251 await start();
252
260 - await show(otherEnvironment, surface);
253 + await screen.rerender(devicePanel(otherEnvironment, surface));
254 await act(async () => late.settle(opened));
255
256 expectApplied();
@@ -265,21 +258,23 @@ describe("DevicePanel thread switches", () => {
258 );
259
260 it("keeps a late power-off error in the environment that started it", async () => {
261 + setup();
262 const powerOff = deferred();
263 mocks.close.mockReturnValue(powerOff.promise);
270 - await show(threadA, streaming);
264 + await using screen = await render(devicePanel(threadA, streaming), { container });
265 await click(container.querySelector("button"));
266
273 - await show(otherEnvironment, streaming);
267 + await screen.rerender(devicePanel(otherEnvironment, streaming));
268 await act(async () => powerOff.settle(failed));
269
270 expect(errors()).toHaveLength(0);
271 expect(mocks.closeSurface).not.toHaveBeenCalled();
278 - await show(threadA, streaming);
272 + await screen.rerender(devicePanel(threadA, streaming));
273 expect(errors()).toHaveLength(1);
274 });
275
276 it("keeps the latest pick pending across switches away and back", async () => {
277 + setup();
278 const first = deferred();
279 const second = deferred();
280 const latest = deferred();
@@ -287,11 +282,11 @@ describe("DevicePanel thread switches", () => {
282 .mockReturnValueOnce(first.promise)
283 .mockReturnValueOnce(second.promise)
284 .mockReturnValueOnce(latest.promise);
290 - await show(threadA);
285 + await using screen = await render(devicePanel(threadA), { container });
286 await click(startButton());
292 - await show(threadB);
287 + await screen.rerender(devicePanel(threadB));
288 await click(startButton());
294 - await show(threadA);
289 + await screen.rerender(devicePanel(threadA));
290 await click(startButton());
291
292 await act(async () => first.settle(failed));
apps/web/src/components/device/DeviceStreamView.browser.test.tsx
+90 -83
@@ -1,7 +1,8 @@
1 -import { act, useEffect, useSyncExternalStore } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
1 +import { useEffect, useSyncExternalStore } from "react";
2 import { EnvironmentId } from "@t3tools/contracts";
4 -import { afterEach, beforeEach, expect, it, onTestFinished, vi } from "vite-plus/test";
3 +import { expect, it, vi } from "vite-plus/test";
4 +
5 +import { act, fakeTimers, render, stubGlobal } from "../../../test/render";
6
7 const accessStore = {
8 value: { httpBase: "http://test", wsBase: "ws://test", query: {}, credentials: true },
@@ -88,98 +89,93 @@ async function publishFrame(image: HTMLImageElement) {
89 framedImages.add(image);
90 await act(async () => image.dispatchEvent(new Event("load")));
91 }
91 -let root: Root;
92 let container: HTMLDivElement;
93 let primes = 0;
94 -beforeEach(() => {
94 +
95 +async function setup(h264 = false, platform: "ios" | "android" = "ios") {
96 primes = 0;
97 viewerMounts = 0;
98 viewerUnmounts = 0;
99 images = [];
100 + await using stack = new AsyncDisposableStack();
101 stubImages();
100 - container = document.createElement("div");
101 - container.style.cssText = "width: 400px; height: 800px; display: flex";
102 - document.body.append(container);
103 - root = createRoot(container);
104 -});
105 -afterEach(async () => {
106 - await act(async () => root.unmount());
107 - container.remove();
108 - restoreImages();
109 - vi.useRealTimers();
110 - vi.unstubAllGlobals();
111 -});
112 -
113 -async function setup(h264 = false, platform: "ios" | "android" = "ios") {
102 + stack.defer(restoreImages);
103 + stack.use(fakeTimers());
104 const touches: unknown[] = [];
115 - vi.useFakeTimers();
116 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
105 let videoBody: ReadableStreamDefaultController<Uint8Array> | undefined;
106 let output: VideoFrameOutputCallback | undefined;
107 if (h264) {
120 - vi.stubGlobal(
121 - "VideoDecoder",
122 - class {
123 - static isConfigSupported = async () => ({ supported: true });
124 - state = "unconfigured";
125 - constructor(callbacks: VideoDecoderInit) {
126 - output = callbacks.output;
127 - }
128 - configure() {
129 - this.state = "configured";
130 - }
131 - close() {
132 - this.state = "closed";
133 - }
134 - },
108 + stack.use(
109 + stubGlobal(
110 + "VideoDecoder",
111 + class {
112 + static isConfigSupported = async () => ({ supported: true });
113 + state = "unconfigured";
114 + constructor(callbacks: VideoDecoderInit) {
115 + output = callbacks.output;
116 + }
117 + configure() {
118 + this.state = "configured";
119 + }
120 + close() {
121 + this.state = "closed";
122 + }
123 + },
124 + ),
125 );
136 - vi.stubGlobal("EncodedVideoChunk", vi.fn());
126 + stack.use(stubGlobal("EncodedVideoChunk", vi.fn()));
127 } else {
128 // Without WebCodecs the iOS client streams MJPEG.
129 const videoDecoder = Object.getOwnPropertyDescriptor(globalThis, "VideoDecoder");
130 if (videoDecoder) {
131 Reflect.deleteProperty(globalThis, "VideoDecoder");
142 - onTestFinished(() => {
132 + stack.defer(() => {
133 Object.defineProperty(globalThis, "VideoDecoder", videoDecoder);
134 });
135 }
136 }
147 - vi.stubGlobal("fetch", (url: string, init: RequestInit) => {
148 - if (url.endsWith("stream.avcc")) {
149 - return Promise.resolve(
150 - new Response(
151 - new ReadableStream<Uint8Array>({
152 - start(controller) {
153 - videoBody = controller;
154 - init.signal?.addEventListener("abort", () => controller.error(new Error("aborted")));
155 - },
156 - }),
157 - ),
158 - );
159 - }
160 - primes++;
161 - return Promise.resolve(new Response("prime"));
162 - });
137 + stack.use(
138 + stubGlobal("fetch", (url: string, init: RequestInit) => {
139 + if (url.endsWith("stream.avcc")) {
140 + return Promise.resolve(
141 + new Response(
142 + new ReadableStream<Uint8Array>({
143 + start(controller) {
144 + videoBody = controller;
145 + init.signal?.addEventListener("abort", () =>
146 + controller.error(new Error("aborted")),
147 + );
148 + },
149 + }),
150 + ),
151 + );
152 + }
153 + primes++;
154 + return Promise.resolve(new Response("prime"));
155 + }),
156 + );
157 const sockets: Array<{ onmessage?: (event: { data: ArrayBuffer }) => void }> = [];
158 const sent: unknown[] = [];
165 - vi.stubGlobal(
166 - "WebSocket",
167 - class {
168 - static OPEN = 1;
169 - readyState = 1;
170 - constructor() {
171 - sockets.push(this);
172 - }
173 - onmessage?: (event: { data: ArrayBuffer }) => void;
174 - send(message: string | Uint8Array) {
175 - if (typeof message === "string") {
176 - sent.push(message);
177 - } else if (message[0] === 0x03) {
178 - touches.push(JSON.parse(new TextDecoder().decode(message.subarray(1))));
159 + stack.use(
160 + stubGlobal(
161 + "WebSocket",
162 + class {
163 + static OPEN = 1;
164 + readyState = 1;
165 + constructor() {
166 + sockets.push(this);
167 }
180 - }
181 - close() {}
182 - },
168 + onmessage?: (event: { data: ArrayBuffer }) => void;
169 + send(message: string | Uint8Array) {
170 + if (typeof message === "string") {
171 + sent.push(message);
172 + } else if (message[0] === 0x03) {
173 + touches.push(JSON.parse(new TextDecoder().decode(message.subarray(1))));
174 + }
175 + }
176 + close() {}
177 + },
178 + ),
179 );
180 const view = (visible: boolean) => (
181 <DeviceStreamView
@@ -191,11 +187,15 @@ async function setup(h264 = false, platform: "ios" | "android" = "ios") {
187 allowPhoneView={h264}
188 />
189 );
194 - await act(async () => root.render(view(true)));
190 + container = document.createElement("div");
191 + container.style.cssText = "width: 400px; height: 800px; display: flex";
192 + const screen = stack.use(await render(view(true), { container }));
193 + const environment = stack.move();
194 return {
195 images,
196 + show: (visible: boolean) => screen.rerender(view(visible)),
197 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
198 sent,
198 - view,
199 touches,
200 configure() {
201 const json = new TextEncoder().encode(
@@ -228,7 +228,8 @@ it.each([
228 { name: "middle", button: 1, buttons: 4 },
229 { name: "right", button: 2, buttons: 2 },
230 ])("ignores $name-button drags and forwards the next primary drag", async ({ button, buttons }) => {
231 - const { touches, configure } = await setup();
231 + await using stream = await setup();
232 + const { touches, configure } = stream;
233 await act(async () => configure());
234 const viewport = container.querySelector("canvas")!.parentElement!;
235 viewport.style.width = "400px";
@@ -270,18 +271,20 @@ it.each([
271 });
272
273 it("removes MJPEG requests while hidden and reconnects when shown", async () => {
273 - const { images, view } = await setup();
274 + await using stream = await setup();
275 + const { images, show } = stream;
276 expect(images[0]!.src).toContain("stream.mjpeg");
275 - await act(async () => root.render(view(false)));
277 + await show(false);
278 expect(container.querySelectorAll("img")).toHaveLength(0);
279 expect(images[0]!.src).toBe("");
280 expect(vi.getTimerCount()).toBe(0);
279 - await act(async () => root.render(view(true)));
281 + await show(true);
282 expect(images.at(-1)!.src).toContain("stream.mjpeg");
283 });
284
285 it("offers Reconnect after the shared timeout and receives a frame after retry with unchanged access", async () => {
284 - const { images } = await setup();
286 + await using stream = await setup();
287 + const { images } = stream;
288 await act(async () => {
289 await vi.advanceTimersByTimeAsync(15_000);
290 });
@@ -297,7 +300,7 @@ it("offers Reconnect after the shared timeout and receives a frame after retry w
300 });
301
302 it("starts exactly one new stream per Reconnect press", async () => {
300 - await setup();
303 + await using _stream = await setup();
304 await act(async () => {
305 await vi.advanceTimersByTimeAsync(15_000);
306 });
@@ -307,7 +310,8 @@ it("starts exactly one new stream per Reconnect press", async () => {
310 });
311
312 it("keeps the 3D viewer mounted across iOS video recovery and releases it when hidden", async () => {
310 - const { configure, frame, view } = await setup(true);
313 + await using stream = await setup(true);
314 + const { configure, frame, show } = stream;
315 await act(async () => configure());
316 expect(viewerMounts).toBe(0);
317 await act(async () => frame());
@@ -323,13 +327,14 @@ it("keeps the 3D viewer mounted across iOS video recovery and releases it when h
327 });
328 await act(async () => frame());
329 expect(viewerMounts).toBe(1);
326 - await act(async () => root.render(view(false)));
330 + await show(false);
331 expect(viewerUnmounts).toBe(1);
332 expect(vi.getTimerCount()).toBe(0);
333 });
334
335 it("types a paste on the Android screen into the device and lets Ctrl+V reach the paste", async () => {
332 - const { sent } = await setup(true, "android");
336 + await using stream = await setup(true, "android");
337 + const { sent } = stream;
338 const screen = container.querySelector<HTMLElement>('[role="application"]')!;
339 screen.focus();
340 expect(document.activeElement).toBe(screen);
@@ -348,7 +353,9 @@ it("types a paste on the Android screen into the device and lets Ctrl+V reach th
353 const capturePaste = (event: ClipboardEvent) =>
354 composerPastes.push(pasteTextToFocusComposer(event));
355 window.addEventListener("paste", capturePaste, true);
351 - onTestFinished(() => window.removeEventListener("paste", capturePaste, true));
356 + using _paste = {
357 + [Symbol.dispose]: () => window.removeEventListener("paste", capturePaste, true),
358 + };
359 const paste = new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true });
360 screen.dispatchEvent(paste);
361 expect(paste.defaultPrevented).toBe(true);
apps/web/src/components/device/useDeviceControls.browser.test.tsx
+32 -41
@@ -1,9 +1,10 @@
1 import { EnvironmentId, type DeviceDetail, type DeviceSummary } from "@t3tools/contracts";
2 import type { DeviceHubAccess } from "@t3tools/client-runtime/device/hub-access";
3 import * as Cause from "effect/Cause";
4 -import { act, useEffect } from "react";
5 -import { createRoot, type Root } from "react-dom/client";
6 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
4 +import { useEffect } from "react";
5 +import { expect, it, vi } from "vite-plus/test";
6 +
7 +import { act, render } from "../../../test/render";
8
9 type Result = { _tag: "Success"; value: DeviceDetail } | { _tag: "Failure"; cause: unknown };
10 const { read, action, subscribe } = vi.hoisted(() => ({
@@ -54,7 +55,6 @@ function deferred() {
55 });
56 return { promise, resolve };
57 }
57 -let root: Root;
58 let controls: DeviceControls;
59 function Probe({ visible, access = null }: { visible: boolean; access?: DeviceHubAccess | null }) {
60 const next = useDeviceControls({
@@ -68,27 +68,17 @@ function Probe({ visible, access = null }: { visible: boolean; access?: DeviceHu
68 }, [next]);
69 return null;
70 }
71 -beforeEach(() => {
72 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
71 +function setup() {
72 read.mockReset();
73 action.mockReset();
74 subscribe.mockReset();
75 subscribe.mockReturnValue(() => {});
76 read.mockResolvedValue(snapshot("light"));
78 - root = createRoot(document.createElement("div"));
79 -});
80 -afterEach(async () => {
81 - await act(async () => root.unmount());
82 - vi.unstubAllGlobals();
83 -});
84 -async function mount() {
85 - await act(async () => {
86 - root.render(<Probe visible />);
87 - });
77 }
78
79 it("serializes rapid actions and retains confirmed settings while pending or after failure", async () => {
91 - await mount();
80 + setup();
81 + await using _screen = await render(<Probe visible />);
82 const response = deferred();
83 action.mockReturnValueOnce(response.promise);
84 let pending!: Promise<void>;
@@ -112,16 +102,17 @@ it("serializes rapid actions and retains confirmed settings while pending or aft
102 });
103
104 it("serializes host actions across hide/reopen and discards detached results", async () => {
115 - await mount();
105 + setup();
106 + await using screen = await render(<Probe visible />);
107 const response = deferred();
108 action.mockReturnValueOnce(response.promise);
109 let pending!: Promise<void>;
110 await act(async () => {
111 pending = controls.act({ type: "setAppearance", value: "dark" });
112 });
122 - await act(async () => root.render(<Probe visible={false} />));
113 + await screen.rerender(<Probe visible={false} />);
114 expect(controls.disabled).toBe(true);
124 - await act(async () => root.render(<Probe visible />));
115 + await screen.rerender(<Probe visible />);
116 await act(async () => controls.act({ type: "setAppearance", value: "light" }));
117 expect(action).toHaveBeenCalledOnce();
118 expect(controls.disabled).toBe(true);
@@ -146,15 +137,16 @@ it("serializes host actions across hide/reopen and discards detached results", a
137 });
138
139 it("keeps actions disabled when settings cannot be confirmed after a detached command", async () => {
149 - await mount();
140 + setup();
141 + await using screen = await render(<Probe visible />);
142 const response = deferred();
143 action.mockReturnValueOnce(response.promise);
144 let pending!: Promise<void>;
145 await act(async () => {
146 pending = controls.act({ type: "setAppearance", value: "dark" });
147 });
156 - await act(async () => root.render(<Probe visible={false} />));
157 - await act(async () => root.render(<Probe visible />));
148 + await screen.rerender(<Probe visible={false} />);
149 + await screen.rerender(<Probe visible />);
150 read.mockResolvedValueOnce({ _tag: "Failure", cause: offline });
151 await act(async () => {
152 response.resolve(snapshot("dark"));
@@ -165,35 +157,37 @@ it("keeps actions disabled when settings cannot be confirmed after a detached co
157 expect(controls.error).toBe("Device offline");
158 await act(async () => controls.act({ type: "setAppearance", value: "light" }));
159 expect(action).toHaveBeenCalledOnce();
168 - await act(async () => root.render(<Probe visible={false} />));
169 - await act(async () => root.render(<Probe visible />));
160 + await screen.rerender(<Probe visible={false} />);
161 + await screen.rerender(<Probe visible />);
162 expect(controls.disabled).toBe(false);
163 expect(controls.error).toBeNull();
164 });
165
166 it("disables stale settings after a failed reopen read and recovers on a successful read", async () => {
175 - await mount();
176 - await act(async () => root.render(<Probe visible={false} />));
167 + setup();
168 + await using screen = await render(<Probe visible />);
169 + await screen.rerender(<Probe visible={false} />);
170 read.mockResolvedValueOnce({ _tag: "Failure", cause: offline });
178 - await act(async () => root.render(<Probe visible />));
171 + await screen.rerender(<Probe visible />);
172 expect(controls.detail).toBeNull();
173 expect(controls.disabled).toBe(true);
174 expect(controls.error).toBe("Device offline");
175 await act(async () => controls.act({ type: "setAppearance", value: "dark" }));
176 expect(action).not.toHaveBeenCalled();
184 - await act(async () => root.render(<Probe visible={false} />));
185 - await act(async () => root.render(<Probe visible />));
177 + await screen.rerender(<Probe visible={false} />);
178 + await screen.rerender(<Probe visible />);
179 expect(controls.detail?.settings.appearance).toBe("light");
180 expect(controls.disabled).toBe(false);
181 expect(controls.error).toBeNull();
182 });
183
184 it("does not let an older refresh overwrite a newer confirmed action", async () => {
192 - await mount();
193 - await act(async () => root.render(<Probe visible={false} />));
185 + setup();
186 + await using screen = await render(<Probe visible />);
187 + await screen.rerender(<Probe visible={false} />);
188 const refresh = deferred();
189 read.mockReturnValueOnce(refresh.promise);
196 - await act(async () => root.render(<Probe visible />));
190 + await screen.rerender(<Probe visible />);
191 action.mockResolvedValueOnce(snapshot("dark"));
192 await act(async () => controls.act({ type: "setAppearance", value: "dark" }));
193 await act(async () => {
@@ -206,6 +200,7 @@ it("does not let an older refresh overwrite a newer confirmed action", async ()
200 it.each(["hidden", "access renewed"] as const)(
201 "uses the detail snapshot until a new foreground event after the subscription is %s",
202 async (restart) => {
203 + setup();
204 const access: DeviceHubAccess = {
205 httpBase: "https://remote.test/api/device-hub",
206 wsBase: "wss://remote.test/api/device-hub",
@@ -218,19 +213,15 @@ it.each(["hidden", "access renewed"] as const)(
213 ...detail,
214 value: { ...detail.value, foregroundApp: { id: "snapshot.app" } },
215 });
221 - await act(async () => {
222 - root.render(<Probe visible access={access} />);
223 - });
216 + await using screen = await render(<Probe visible access={access} />);
217 const oldEvent = subscribe.mock.calls[0]![1];
218 await act(async () => oldEvent({ id: "previous.live.app" }));
219 expect(controls.foregroundApp?.id).toBe("previous.live.app");
220 if (restart === "hidden") {
228 - await act(async () => root.render(<Probe visible={false} access={access} />));
229 - await act(async () => root.render(<Probe visible access={access} />));
221 + await screen.rerender(<Probe visible={false} access={access} />);
222 + await screen.rerender(<Probe visible access={access} />);
223 } else {
231 - await act(async () =>
232 - root.render(<Probe visible access={{ ...access, query: { ticket: "renewed" } }} />),
233 - );
224 + await screen.rerender(<Probe visible access={{ ...access, query: { ticket: "renewed" } }} />);
225 }
226 expect(controls.foregroundApp?.id).toBe("snapshot.app");
227 await act(async () => oldEvent({ id: "late.previous.app" }));
apps/web/src/components/diffs/AnnotatableCodeView.browser.test.tsx
+50 -56
@@ -1,8 +1,9 @@
1 import type { CodeViewDiffItem, FileDiffMetadata, SelectedLineRange } from "@pierre/diffs";
2 import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
3 -import { act, StrictMode, type ComponentProps } from "react";
4 -import { createRoot, type Root } from "react-dom/client";
5 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 +import { StrictMode, type ComponentProps } from "react";
4 +import { describe, expect, it, vi } from "vite-plus/test";
5 +
6 +import { act, render } from "../../../test/render";
7
8 import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
9 import { buildFileDiffIdentityKey } from "~/lib/diffRendering";
@@ -51,7 +52,6 @@ import type { StyledDiffCodeView } from "./StyledDiffCodeView";
52
53 const target = DraftId.make("diff-draft-test");
54 const range: SelectedLineRange = { start: 1, end: 1, side: "additions" };
54 -let root: Root;
55 let container: HTMLDivElement;
56
57 function file(
@@ -75,28 +75,26 @@ function file(
75 };
76 }
77
78 -function render(
78 +function view(
79 files: ReturnType<typeof file>[],
80 codeViewKey = "initial",
81 pendingFiles: FileDiffMetadata[] = [],
82 ) {
83 - act(() =>
84 - root.render(
85 - <StrictMode>
86 - <AnnotatableCodeView
87 - codeViewKey={codeViewKey}
88 - files={files}
89 - pendingFiles={pendingFiles}
90 - sectionId="unstaged"
91 - sectionTitle="Uncommitted"
92 - composerDraftTarget={target}
93 - options={{}}
94 - renderHeaderFilenameSuffix={() => null}
95 - renderHeaderPrefix={() => null}
96 - onRevealSearchMatch={() => {}}
97 - />
98 - </StrictMode>,
99 - ),
83 + return (
84 + <StrictMode>
85 + <AnnotatableCodeView
86 + codeViewKey={codeViewKey}
87 + files={files}
88 + pendingFiles={pendingFiles}
89 + sectionId="unstaged"
90 + sectionTitle="Uncommitted"
91 + composerDraftTarget={target}
92 + options={{}}
93 + renderHeaderFilenameSuffix={() => null}
94 + renderHeaderPrefix={() => null}
95 + onRevealSearchMatch={() => {}}
96 + />
97 + </StrictMode>
98 );
99 }
100
@@ -105,7 +103,7 @@ function click(label: string) {
103 (node) => node.textContent === label,
104 );
105 if (!button) throw new Error(`Missing button: ${label}`);
108 - act(() => button.click());
106 + return act(() => button.click());
107 }
108
109 function editor() {
@@ -115,7 +113,7 @@ function editor() {
113 }
114
115 function typeComment(text: string) {
118 - act(() => {
116 + return act(() => {
117 Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(
118 editor(),
119 text,
@@ -124,32 +122,25 @@ function typeComment(text: string) {
122 });
123 }
124
127 -beforeEach(() => {
128 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
129 - useComposerDraftStore.setState(useComposerDraftStore.getInitialState(), true);
125 +function setup(): Disposable {
126 + const reset = () => useComposerDraftStore.setState(useComposerDraftStore.getInitialState(), true);
127 + reset();
128 container = document.createElement("div");
131 - document.body.append(container);
132 - root = createRoot(container);
133 -});
134 -
135 -afterEach(() => {
136 - act(() => root.unmount());
137 - container.remove();
138 - useComposerDraftStore.setState(useComposerDraftStore.getInitialState(), true);
139 - vi.unstubAllGlobals();
140 -});
129 + return { [Symbol.dispose]: reset };
130 +}
131
132 describe("diff comment drafts", () => {
133 it.each(["removed file", "replaced rename"] as const)(
134 "allows a fresh comment after a %s loses its draft",
145 - (scenario) => {
135 + async (scenario) => {
136 + using _drafts = setup();
137 const original =
138 scenario === "removed file"
139 ? file("a.ts")
140 : file("shared.ts", 1, "rename-changed", "old.ts");
150 - render([original, file("b.ts")]);
151 - click(`Comment on ${original.filePath}`);
152 - typeComment("Discard this draft");
141 + await using screen = await render(view([original, file("b.ts")]), { container });
142 + await click(`Comment on ${original.filePath}`);
143 + await typeComment("Discard this draft");
144 const pending =
145 scenario === "removed file"
146 ? []
@@ -161,12 +152,12 @@ describe("diff comment drafts", () => {
152 },
153 ];
154
164 - render([file("b.ts")], "refreshed", pending);
155 + await screen.rerender(view([file("b.ts")], "refreshed", pending));
156 expect(container.querySelector("textarea")).toBeNull();
166 - click("Comment on b.ts");
157 + await click("Comment on b.ts");
158 expect(editor().value).toBe("");
168 - typeComment(" Review b.ts ");
169 - click("Comment");
159 + await typeComment(" Review b.ts ");
160 + await click("Comment");
161
162 expect(useComposerDraftStore.getState().getComposerDraft(target)?.reviewComments).toEqual([
163 expect.objectContaining({
@@ -175,31 +166,34 @@ describe("diff comment drafts", () => {
166 selection: { ...range, endSide: "additions" },
167 }),
168 ]);
178 - render([original, file("b.ts")], "returned");
169 + await screen.rerender(view([original, file("b.ts")], "returned"));
170 expect(container.querySelector("textarea")).toBeNull();
171 expect(container.querySelector("mark")).toBeNull();
172 expect(container.querySelector("p")?.textContent).toBe("Review b.ts");
173 },
174 );
175
185 - it("keeps the text and selected line through refresh and a provisional lazy patch", () => {
176 + it("keeps the text and selected line through refresh and a provisional lazy patch", async () => {
177 + using _drafts = setup();
178 const original = file("shared.ts", 1, "rename-pure", "old.ts");
187 - render([original]);
188 - click("Comment on shared.ts");
189 - typeComment("Keep this draft");
179 + await using screen = await render(view([original]), { container });
180 + await click("Comment on shared.ts");
181 + await typeComment("Keep this draft");
182 const refreshed = file("shared.ts", 2, "rename-pure", "old.ts");
191 - render([refreshed], "refreshed");
183 + await screen.rerender(view([refreshed], "refreshed"));
184 expect(editor().value).toBe("Keep this draft");
185 expect(container.querySelector("mark")?.textContent).toBe("Line 1");
186
195 - render([], "loading", [
196 - { ...refreshed.fileDiff, type: "rename-changed", hunks: [], cacheKey: "shared:pending" },
197 - ]);
187 + await screen.rerender(
188 + view([], "loading", [
189 + { ...refreshed.fileDiff, type: "rename-changed", hunks: [], cacheKey: "shared:pending" },
190 + ]),
191 + );
192 expect(container.querySelector("textarea")).toBeNull();
199 - render([refreshed], "loaded");
193 + await screen.rerender(view([refreshed], "loaded"));
194 expect(editor().value).toBe("Keep this draft");
195 expect(container.querySelector("mark")?.textContent).toBe("Line 1");
202 - click("Comment");
196 + await click("Comment");
197 expect(useComposerDraftStore.getState().getComposerDraft(target)?.reviewComments).toEqual([
198 expect.objectContaining({
199 filePath: "shared.ts",
apps/web/src/components/diffs/DiffFileTree.browser.test.tsx
+56 -52
@@ -1,11 +1,12 @@
1 import type { CodeViewScrollTarget } from "@pierre/diffs";
2 import type { FileTree as FileTreeModel } from "@pierre/trees";
3 -import { act, type ComponentProps } from "react";
4 -import { createRoot, type Root } from "react-dom/client";
5 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 +import type { ComponentProps } from "react";
4 +import { describe, expect, it, vi } from "vite-plus/test";
5
6 import type { FileDiffMetadata } from "@pierre/diffs";
7
8 +import { act, render } from "../../../test/render";
9 +
10 import { DiffFileTree, type DiffFileTreeEntry } from "./DiffFileTree";
11 import { diffFileTreeEntries } from "./diffFileTree.logic";
12 import { useCodeViewFileReveal } from "./useCodeViewFileReveal";
@@ -31,7 +32,6 @@ const entries: DiffFileTreeEntry[] = [
32 ];
33
34 describe("diff tree file activation", () => {
34 - let root: Root | undefined;
35 let container: HTMLDivElement;
36 const targets: CodeViewScrollTarget[] = [];
37 const viewer = {
@@ -62,9 +62,10 @@ describe("diff tree file activation", () => {
62
63 const model = (): FileTreeModel => captured.model as FileTreeModel;
64
65 - async function mount(props: Parameters<typeof Panel>[0] = {}) {
66 - root ??= createRoot(container);
67 - await act(async () => root!.render(<Panel {...props} />));
65 + function setup() {
66 + targets.length = 0;
67 + container = document.createElement("div");
68 + container.style.cssText = "display: flex; flex-direction: column; width: 320px; height: 480px";
69 }
70
71 function row(path: string): HTMLElement {
@@ -99,29 +100,14 @@ describe("diff tree file activation", () => {
100 });
101 }
102
102 - beforeEach(() => {
103 - targets.length = 0;
104 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
105 - container = document.createElement("div");
106 - container.style.cssText = "display: flex; flex-direction: column; width: 320px; height: 480px";
107 - document.body.append(container);
108 - });
109 -
110 - afterEach(async () => {
111 - await act(async () => root?.unmount());
112 - root = undefined;
113 - container.remove();
114 - vi.restoreAllMocks();
115 - vi.unstubAllGlobals();
116 - });
117 -
103 it("mounts a file-to-symlink type change as one tree row", async () => {
104 + setup();
105 const typeChange = diffFileTreeEntries([
106 { type: "deleted", name: "AGENTS.md", prevName: "AGENTS.md" } as FileDiffMetadata,
107 { type: "new", name: "AGENTS.md", prevName: "AGENTS.md" } as FileDiffMetadata,
108 { type: "change", name: "CLAUDE.md", prevName: "CLAUDE.md" } as FileDiffMetadata,
109 ]);
124 - await mount({ files: [...typeChange] });
110 + await using _screen = await render(<Panel files={[...typeChange]} />, { container });
111
112 const tree = model();
113 expect(tree.getItem("AGENTS.md")?.isDirectory()).toBe(false);
@@ -131,7 +117,8 @@ describe("diff tree file activation", () => {
117 });
118
119 it("reissues the reveal when the sole selected file is activated again", async () => {
134 - await mount();
120 + setup();
121 + await using _screen = await render(<Panel />, { container });
122 await activate("02-short.ts");
123 expect(model().getSelectedPaths()).toEqual(["02-short.ts"]);
124 await activate("02-short.ts");
@@ -142,7 +129,8 @@ describe("diff tree file activation", () => {
129 });
130
131 it("reveals newly selected files once in either direction", async () => {
145 - await mount();
132 + setup();
133 + await using _screen = await render(<Panel />, { container });
134 await activate("02-short.ts");
135 await activate("01-tall.ts");
136 await activate("03-medium.ts");
@@ -152,7 +140,8 @@ describe("diff tree file activation", () => {
140 });
141
142 it("keeps focus-only navigation separate from button activation", async () => {
155 - await mount();
143 + setup();
144 + await using _screen = await render(<Panel />, { container });
145 await activate("02-short.ts");
146 await act(async () => model().getItem("01-tall.ts")!.focus());
147 expect(model().getSelectedPaths()).toEqual(["02-short.ts"]);
@@ -165,7 +154,8 @@ describe("diff tree file activation", () => {
154 it.each(["ctrlKey", "metaKey"] as const)(
155 "does not reveal a selected file that a %s click deselects",
156 async (modifier) => {
168 - await mount();
157 + setup();
158 + await using _screen = await render(<Panel />, { container });
159 await activate("02-short.ts");
160 await activate("02-short.ts", { [modifier]: true });
161 expect(model().getSelectedPaths()).toEqual([]);
@@ -174,7 +164,8 @@ describe("diff tree file activation", () => {
164 );
165
166 it("lets a click narrow multiple selected files without a second reveal", async () => {
177 - await mount();
167 + setup();
168 + await using _screen = await render(<Panel />, { container });
169 await activate("02-short.ts");
170 await act(async () => model().getItem("01-tall.ts")!.select());
171 expect(model().getSelectedPaths()).toHaveLength(2);
@@ -185,7 +176,11 @@ describe("diff tree file activation", () => {
176 });
177
178 it("leaves directory selection and expansion to the tree", async () => {
188 - await mount({ files: [{ path: "src/app.ts", status: "modified" }] });
179 + setup();
180 + await using _screen = await render(
181 + <Panel files={[{ path: "src/app.ts", status: "modified" }]} />,
182 + { container },
183 + );
184 const directory = model().getItem("src/")!;
185 if (!("isExpanded" in directory)) throw new Error("Expected the directory handle");
186 expect(directory.isExpanded()).toBe(true);
@@ -197,28 +192,28 @@ describe("diff tree file activation", () => {
192 });
193
194 it("reorders refreshed files without reopening a collapsed folder", async () => {
195 + setup();
196 const files: DiffFileTreeEntry[] = [
197 { path: "src/state/shell.ts", status: "modified" },
198 { path: "src/features/route.ts", status: "added" },
199 ];
204 - await mount({ files });
200 + await using screen = await render(<Panel files={files} />, { container });
201 const initialFolder = model().getItem("src/features/")!;
202 if (!("collapse" in initialFolder)) throw new Error("Expected the directory handle");
203 await act(async () => initialFolder.collapse());
208 - await act(async () => {
209 - root!.render(<Panel files={[files[1]!, files[0]!]} />);
210 - });
204 + await screen.rerender(<Panel files={[files[1]!, files[0]!]} />);
205 const folder = model().getItem("src/features/")!;
206 if (!("isExpanded" in folder)) throw new Error("Expected the directory handle");
207 expect(folder.isExpanded()).toBe(false);
208 });
209
210 it("reveals real diff paths and statuses when a directory is replaced by a file", async () => {
211 + setup();
212 const files: DiffFileTreeEntry[] = [
213 { path: "office/config.ts", status: "deleted" },
214 { path: "office", status: "added" },
215 ];
221 - await mount({ files, selectedPath: "office" });
216 + await using screen = await render(<Panel files={files} selectedPath="office" />, { container });
217 expect(fileRows().map((row) => row.getAttribute("data-item-git-status"))).toEqual([
218 "deleted",
219 "added",
@@ -233,25 +228,26 @@ describe("diff tree file activation", () => {
228 { type: "item", id: "office/config.ts\0office/config.ts", align: "start" },
229 ]);
230 expect(row("office/").getAttribute("aria-expanded")).toBe("false");
236 - await mount({ files, selectedPath: "office/config.ts" });
231 + await screen.rerender(<Panel files={files} selectedPath="office/config.ts" />);
232 expect(row("office/").getAttribute("aria-expanded")).toBe("true");
233 expect(fileRows()[0]!.getAttribute("aria-selected")).toBe("true");
234 expect(targets).toHaveLength(2);
235 });
236
237 it("keeps selection, focus, and collapsed folders through a colliding slice and refresh", async () => {
238 + setup();
239 const files: DiffFileTreeEntry[] = [
240 { path: "office", status: "deleted" },
241 { path: "src/route.ts", status: "modified" },
242 ];
247 - await mount({ files });
243 + await using screen = await render(<Panel files={files} />, { container });
244 await activate("src/");
245 await activate("office");
246 await act(async () => model().focusPath("office"));
247 expect(model().getFocusedPath()).toBe("office");
248 expect(row("office").getAttribute("aria-selected")).toBe("true");
249 const appended: DiffFileTreeEntry[] = [...files, { path: "office/config.ts", status: "added" }];
254 - await mount({ files: appended });
250 + await screen.rerender(<Panel files={appended} />);
251 expect(row("src/").getAttribute("aria-expanded")).toBe("false");
252 expect(fileRows()[0]!.getAttribute("aria-selected")).toBe("true");
253 expect(row("office/").getAttribute("aria-selected")).toBe("false");
@@ -265,7 +261,7 @@ describe("diff tree file activation", () => {
261 { type: "item", id: "office/config.ts\0office/config.ts", align: "start" },
262 ]);
263 await activate("office/");
268 - await mount({ files: appended.map((file) => ({ ...file })) });
264 + await screen.rerender(<Panel files={appended.map((file) => ({ ...file }))} />);
265 expect(row("src/").getAttribute("aria-expanded")).toBe("false");
266 expect(row("office/").getAttribute("aria-expanded")).toBe("false");
267 await activate(fileRows()[0]!);
@@ -274,6 +270,7 @@ describe("diff tree file activation", () => {
270 });
271
272 it("preserves filename and extension icons when files become directory prefixes", async () => {
273 + setup();
274 const files: DiffFileTreeEntry[] = [
275 { path: "AGENTS.md", status: "deleted" },
276 { path: "config.ts", status: "deleted" },
@@ -282,25 +279,30 @@ describe("diff tree file activation", () => {
279 fileRows()
280 .filter((row) => row.getAttribute("aria-level") === "1")
281 .map((row) => row.querySelector('[data-item-section="icon"] use')?.getAttribute("href"));
285 - await mount({ files });
282 + await using screen = await render(<Panel files={files} />, { container });
283 const icons = rootFileIcons();
284 expect(icons).toEqual(["#t3-file-icon-agents", "#file-tree-builtin-typescript"]);
288 - await mount({
289 - files: [
290 - ...files,
291 - { path: "AGENTS.md/note.txt", status: "added" },
292 - { path: "config.ts/note.txt", status: "added" },
293 - ],
294 - });
285 + await screen.rerender(
286 + <Panel
287 + files={[
288 + ...files,
289 + { path: "AGENTS.md/note.txt", status: "added" },
290 + { path: "config.ts/note.txt", status: "added" },
291 + ]}
292 + />,
293 + );
294 expect(rootFileIcons()).toEqual(icons);
295 });
296
297 it("preserves a collapsed controlled selection through paging until explicitly revealed", async () => {
298 + setup();
299 const files: DiffFileTreeEntry[] = [
300 { path: "src/office", status: "deleted" },
301 { path: "src/route.ts", status: "modified" },
302 ];
303 - await mount({ files, selectedPath: "src/office" });
303 + await using screen = await render(<Panel files={files} selectedPath="src/office" />, {
304 + container,
305 + });
306 expect(model().getSelectedPaths()).toEqual(["src/office"]);
307 expect(targets).toEqual([]);
308 await activate("src/office");
@@ -310,9 +312,9 @@ describe("diff tree file activation", () => {
312 if (!("collapse" in folder)) throw new Error("Expected the directory handle");
313 await act(async () => folder.collapse());
314 expect(row("src/").getAttribute("aria-expanded")).toBe("false");
313 - const scroll = vi.spyOn(model(), "scrollToPath");
315 + using scroll = vi.spyOn(model(), "scrollToPath");
316 const appended: DiffFileTreeEntry[] = [...files, { path: "src/office/x.ts", status: "added" }];
315 - await mount({ files: appended, selectedPath: "src/office" });
317 + await screen.rerender(<Panel files={appended} selectedPath="src/office" />);
318 expect.soft(row("src/").getAttribute("aria-expanded")).toBe("false");
319 expect.soft(scroll).not.toHaveBeenCalled();
320 const selected = model().getSelectedPaths();
@@ -322,7 +324,7 @@ describe("diff tree file activation", () => {
324
325 await act(async () => folder.collapse());
326 scroll.mockClear();
325 - await mount({ files: appended, selectedPath: "src/office", revealRequestId: 1 });
327 + await screen.rerender(<Panel files={appended} selectedPath="src/office" revealRequestId={1} />);
328 expect(row("src/").getAttribute("aria-expanded")).toBe("true");
329 expect(model().getSelectedPaths()).toEqual(selected);
330 expect(row(selected[0]!).getAttribute("aria-selected")).toBe("true");
@@ -335,7 +337,9 @@ describe("diff tree file activation", () => {
337 ]);
338
339 await act(async () => folder.collapse());
338 - await mount({ files: appended, selectedPath: "src/route.ts", revealRequestId: 1 });
340 + await screen.rerender(
341 + <Panel files={appended} selectedPath="src/route.ts" revealRequestId={1} />,
342 + );
343 expect(row("src/").getAttribute("aria-expanded")).toBe("true");
344 expect(model().getSelectedPaths()).toEqual(["src/route.ts"]);
345 expect(targets).toHaveLength(2);
apps/web/src/components/diffs/StyledDiffCodeView.browser.test.tsx
+128 -129
@@ -1,3 +1,4 @@
1 +import { act, render, fakeTimers } from "../../../test/render";
2 import {
3 CodeView,
4 FileDiff,
@@ -12,18 +13,16 @@ import { WorkerPoolManager, type WorkerRequest, type WorkerResponse } from "@pie
13 import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
14 import { getDiffLineStat, getRenderablePatch } from "../../lib/diffRendering";
15 import {
15 - act,
16 StrictMode,
17 useEffect,
18 useImperativeHandle,
19 useLayoutEffect,
20 useRef,
21 useState,
22 - type ReactElement,
22 + type ReactNode,
23 type Ref,
24 } from "react";
25 -import { createRoot, type Root } from "react-dom/client";
26 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
25 +import { describe, expect, it, vi } from "vite-plus/test";
26
27 const testState = vi.hoisted(() => ({
28 workers: [] as Worker[],
@@ -147,31 +146,12 @@ function renderViews(count: number) {
146 );
147 }
148
150 -const roots: Root[] = [];
151 -
152 -function mount(element: ReactElement) {
153 - const container = document.createElement("div");
154 - document.body.append(container);
155 - const root = createRoot(container);
156 - roots.push(root);
157 - return {
158 - root,
159 - render: (next: ReactElement) => act(async () => root.render(next)),
160 - initial: act(async () => root.render(element)),
161 - };
162 -}
163 -
164 -async function unmountAll() {
165 - for (const root of roots.splice(0)) await act(async () => root.unmount());
166 - document.body.replaceChildren();
167 -}
168 -
149 const codeFile = (name: string) =>
150 document.querySelector(`[data-code-file="${name}"]`)?.textContent ?? "";
151 const loadingViews = () => document.querySelectorAll('[role="status"]').length;
152
153 describe("code-view worker lifecycle", () => {
174 - beforeEach(() => {
154 + function setup() {
155 testState.workers = [];
156 testState.terminations = 0;
157 testState.requests = [];
@@ -181,38 +161,54 @@ describe("code-view worker lifecycle", () => {
161 testState.holdInitialization = false;
162 testState.heldResponses = [];
163 testState.onInitializationHeld = undefined;
184 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
164 + }
165 + // Worker startup runs on real time, so only the idle expiry checks use this clock.
166 + // Faking startup too would let advancing the idle clock time out a worker startup.
167 + const idleClock = () => fakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
168 + async function workerEnvironment() {
169 + await using stack = new AsyncDisposableStack();
170 // Pins the pool at two workers whatever machine runs the suite.
186 - Object.defineProperty(navigator, "hardwareConcurrency", { configurable: true, value: 2 });
171 + stack.use(vi.spyOn(navigator, "hardwareConcurrency", "get").mockReturnValue(2));
172 const initialize = WorkerPoolManager.prototype.initialize;
188 - vi.spyOn(WorkerPoolManager.prototype, "initialize").mockImplementation(function (
189 - this: WorkerPoolManager,
190 - ...args
191 - ) {
192 - const pending = initialize.apply(this, args);
193 - testState.pools.set(this, pending);
194 - return pending;
173 + stack.use(
174 + vi.spyOn(WorkerPoolManager.prototype, "initialize").mockImplementation(function (
175 + this: WorkerPoolManager,
176 + ...args
177 + ) {
178 + const pending = initialize.apply(this, args);
179 + testState.pools.set(this, pending);
180 + return pending;
181 + }),
182 + );
183 + // Runs out the idle timer each view's unmount scheduled, releasing its pool.
184 + stack.defer(async () => {
185 + await vi.runOnlyPendingTimersAsync();
186 + vi.useRealTimers();
187 });
196 - });
197 -
198 - afterEach(async () => {
199 - if (!vi.isFakeTimers()) vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
200 - await unmountAll();
201 - await vi.runOnlyPendingTimersAsync();
202 - vi.useRealTimers();
203 - vi.restoreAllMocks();
204 - vi.unstubAllGlobals();
205 - delete (navigator as { hardwareConcurrency?: number }).hardwareConcurrency;
206 - });
188 + const environment = stack.move();
189 + return {
190 + async render(ui: ReactNode) {
191 + const view = environment.use(await render(ui, { router: false }));
192 + // Disposed before the view, so its unmount schedules the idle timer on a fake clock
193 + // that the run-out above then restores.
194 + environment.defer(() => {
195 + if (!vi.isFakeTimers()) idleClock();
196 + });
197 + return view;
198 + },
199 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
200 + };
201 + }
202
203 it("starts on demand, keeps quick reopens warm, and expires the last closed pool", async () => {
209 - const view = mount(renderViews(0));
210 - await view.initial;
204 + setup();
205 + await using workers = await workerEnvironment();
206 + const view = await workers.render(renderViews(0));
207 const button = document.querySelector("button")!;
208 expect(testState.workers).toHaveLength(0);
209 expect(testState.pools.size).toBe(0);
210 await act(async () => button.click());
215 - await view.render(renderViews(1));
211 + await view.rerender(renderViews(1));
212 const pool = [...testState.pools.keys()][0]!;
213 await act(async () => testState.pools.get(pool));
214 expect(pool.isInitialized()).toBe(true);
@@ -220,7 +216,7 @@ describe("code-view worker lifecycle", () => {
216 await vi.waitFor(() => expect(codeFile("notes.txt")).toContain("Plain text is ready."));
217 expect(testState.requests.filter((request) => request.type === "file")).toHaveLength(0);
218
223 - await view.render(renderViews(2));
219 + await view.rerender(renderViews(2));
220 await act(async () => pool.primeFileHighlightCache(files[1]!));
221 expect(testState.pools.size).toBe(1);
222 expect(testState.workers).toHaveLength(2);
@@ -228,32 +224,31 @@ describe("code-view worker lifecycle", () => {
224 expect(pool.getFileResultCache(files[1]!)).toBeDefined();
225 await vi.waitFor(() => expect(codeFile("answer.ts")).toContain("answer"));
226
231 - // Worker startup uses real time. Only advance the clock once highlighting
232 - // has finished, so idle expiry cannot also expire a worker startup timer.
233 - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
234 - await view.render(renderViews(1));
235 - expect(pool.getStats().totalWorkers).toBe(2);
236 - expect(testState.terminations).toBe(0);
237 - await view.render(renderViews(0));
238 - await vi.advanceTimersByTimeAsync(29_999);
239 - expect(pool.getStats().totalWorkers).toBe(2);
240 - expect(testState.terminations).toBe(0);
241 -
242 - await view.render(renderViews(1));
243 - expect(testState.pools.size).toBe(1);
244 - expect(testState.workers).toHaveLength(2);
245 - expect(loadingViews()).toBe(0);
246 - expect(pool.getFileResultCache(files[1]!)).toBeDefined();
247 - await vi.advanceTimersByTimeAsync(30_000);
248 - expect(pool.getStats().totalWorkers).toBe(2);
249 -
250 - await view.render(renderViews(0));
251 - await vi.advanceTimersByTimeAsync(30_000);
252 - expect(pool.getStats().totalWorkers).toBe(0);
253 - expect(testState.terminations).toBe(2);
227 + {
228 + using _idleClock = idleClock();
229 + await view.rerender(renderViews(1));
230 + expect(pool.getStats().totalWorkers).toBe(2);
231 + expect(testState.terminations).toBe(0);
232 + await view.rerender(renderViews(0));
233 + await vi.advanceTimersByTimeAsync(29_999);
234 + expect(pool.getStats().totalWorkers).toBe(2);
235 + expect(testState.terminations).toBe(0);
236 +
237 + await view.rerender(renderViews(1));
238 + expect(testState.pools.size).toBe(1);
239 + expect(testState.workers).toHaveLength(2);
240 + expect(loadingViews()).toBe(0);
241 + expect(pool.getFileResultCache(files[1]!)).toBeDefined();
242 + await vi.advanceTimersByTimeAsync(30_000);
243 + expect(pool.getStats().totalWorkers).toBe(2);
244 +
245 + await view.rerender(renderViews(0));
246 + await vi.advanceTimersByTimeAsync(30_000);
247 + expect(pool.getStats().totalWorkers).toBe(0);
248 + expect(testState.terminations).toBe(2);
249 + }
250
255 - vi.useRealTimers();
256 - await view.render(renderViews(1));
251 + await view.rerender(renderViews(1));
252 const reopenedPool = [...testState.pools.keys()][1]!;
253 await act(async () => testState.pools.get(reopenedPool));
254 expect(reopenedPool.isInitialized()).toBe(true);
@@ -264,8 +259,10 @@ describe("code-view worker lifecycle", () => {
259 });
260
261 it("renders through Pierre's main-thread fallback when worker creation fails", async () => {
262 + setup();
263 + await using workers = await workerEnvironment();
264 testState.failWorkers = true;
268 - await mount(renderViews(1)).initial;
265 + await workers.render(renderViews(1));
266 const pool = [...testState.pools.keys()][0]!;
267 await act(async () => {
268 await expect(testState.pools.get(pool)).rejects.toMatchObject({ _tag: "DiffWorkerError" });
@@ -281,13 +278,14 @@ describe("code-view worker lifecycle", () => {
278 });
279
280 it("keeps an initializing pool until its last view closes and ignores late responses", async () => {
284 - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
281 + setup();
282 + using _idleClock = idleClock();
283 + await using workers = await workerEnvironment();
284 testState.holdInitialization = true;
285 const held = new Promise<void>((resolve) => {
286 testState.onInitializationHeld = resolve;
287 });
289 - const view = mount(renderViews(2));
290 - await view.initial;
288 + const view = await workers.render(renderViews(2));
289 const pool = [...testState.pools.keys()][0]!;
290 const pending = testState.pools.get(pool)!;
291 await held;
@@ -296,10 +294,10 @@ describe("code-view worker lifecycle", () => {
294 expect(loadingViews()).toBe(2);
295 expect(testState.renderPools).toHaveLength(0);
296
299 - await view.render(renderViews(1));
297 + await view.rerender(renderViews(1));
298 expect(pool.getStats().totalWorkers).toBe(2);
299 expect(testState.terminations).toBe(0);
302 - await view.render(renderViews(0));
300 + await view.rerender(renderViews(0));
301 // Pierre gives up on a held startup after 10 seconds; the idle timer then tears the pool down.
302 const timedOut = expect(pending).rejects.toThrow("worker initialization timed out");
303 await vi.advanceTimersByTimeAsync(30_000);
@@ -316,10 +314,6 @@ describe("code-view worker lifecycle", () => {
314 });
315
316 describe("collapsed diff content", () => {
319 - let pool: WorkerPoolManager;
320 - let container: HTMLDivElement;
321 - let viewer: FileDiff<string> | CodeView<string> | undefined;
322 -
317 const loadedDiff = () => {
318 const parsed = getRenderablePatch(
319 [
@@ -339,41 +333,45 @@ describe("collapsed diff content", () => {
333 if (parsed?.kind !== "files" || !parsed.files[0]) throw new Error("Expected diff");
334 return parsed.files[0];
335 };
342 - const code = () =>
336 + const codeIn = (container: HTMLElement) =>
337 [...container.querySelectorAll("diffs-container")]
338 .flatMap((element) => [...(element.shadowRoot?.querySelectorAll("[data-line]") ?? [])])
339 .map((line) => line.textContent)
340 .join("\n");
341
348 - beforeEach(async () => {
342 + async function setup() {
343 + await using stack = new AsyncDisposableStack();
344 testState.requests = [];
345 testState.failWorkers = false;
346 testState.holdInitialization = false;
352 - pool = new WorkerPoolManager(
347 + const pool = new WorkerPoolManager(
348 { workerFactory: () => new DiffsWorker(), poolSize: 1 },
349 { theme: "pierre-dark", langs: ["typescript"], preferredHighlighter: "shiki-wasm" },
350 );
351 + stack.defer(() => pool.terminate());
352 await pool.initialize();
357 - container = document.createElement("div");
353 + const container = document.createElement("div");
354 container.style.cssText = "height: 400px; width: 800px; overflow: auto";
355 document.body.append(container);
360 - });
361 -
362 - afterEach(() => {
363 - viewer?.cleanUp();
364 - viewer = undefined;
365 - pool.terminate();
366 - container.remove();
367 - vi.restoreAllMocks();
368 - });
356 + stack.defer(() => container.remove());
357 + const environment = stack.move();
358 + return {
359 + pool,
360 + container,
361 + code: () => codeIn(container),
362 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
363 + };
364 + }
365
366 it("defers plain AST and highlight work across collapsed renders until expansion", async () => {
367 + await using environment = await setup();
368 + const { pool, container, code } = environment;
369 const fileDiff = loadedDiff();
372 - const highlight = vi.spyOn(pool, "highlightDiffAST");
373 - const plainAST = vi.spyOn(pool, "getPlainDiffAST");
370 + using highlight = vi.spyOn(pool, "highlightDiffAST");
371 + using plainAST = vi.spyOn(pool, "getPlainDiffAST");
372 const options = { theme: "pierre-dark", collapsed: true, disableErrorHandling: true } as const;
373 const file = new FileDiff<string>(options, pool);
376 - viewer = file;
374 + using _viewer = { [Symbol.dispose]: () => file.cleanUp() };
375 file.render({ fileDiff, containerWrapper: container });
376 file.render({ fileDiff, forceRender: true });
377 expect.soft(highlight.mock.calls.length).toBe(0);
@@ -393,6 +391,8 @@ describe("collapsed diff content", () => {
391 });
392
393 it("finds newly loaded collapsed lines and unfolds the match with its annotation and header", async () => {
394 + await using environment = await setup();
395 + const { pool, container, code } = environment;
396 const fileDiff = loadedDiff();
397 const item: CodeViewItem<string> = {
398 type: "diff",
@@ -422,7 +422,7 @@ describe("collapsed diff content", () => {
422 },
423 pool,
424 );
425 - viewer = view;
425 + using _viewer = { [Symbol.dispose]: () => view.cleanUp() };
426 view.setup(container);
427 view.openSearch();
428 const search = container.querySelector("[data-diffs-search]")!.shadowRoot!;
@@ -447,8 +447,8 @@ describe("collapsed diff content", () => {
447
448 await pool.primeDiffHighlightCache(fileDiff);
449 view.render(true);
450 - const highlight = vi.spyOn(pool, "highlightDiffAST");
451 - const plainAST = vi.spyOn(pool, "getPlainDiffAST");
450 + using highlight = vi.spyOn(pool, "highlightDiffAST");
451 + using plainAST = vi.spyOn(pool, "getPlainDiffAST");
452 const updatedDiff = { ...fileDiff, name: "updated.ts", cacheKey: "collapsed-update" };
453 view.setItems([{ ...item, fileDiff: updatedDiff, version: 2 }]);
454 view.render(true);
@@ -568,27 +568,22 @@ function RevealViews({
568 }
569
570 describe("code-view file reveals", () => {
571 - let view: ReturnType<typeof mount>;
571 const reveal = () => act(async () => document.querySelector("button")!.click());
572
574 - beforeEach(() => {
573 + function setup() {
574 revealCalls.length = 0;
576 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
577 - });
578 -
579 - afterEach(async () => {
580 - await unmountAll();
581 - vi.unstubAllGlobals();
582 - });
575 + }
576
577 it("does not replay a handled tree click or scroll an old handle when a selected file remounts the view", async () => {
585 - view = mount(<RevealViews scope="first" visible selectedFile="external-a" />);
586 - await view.initial;
578 + setup();
579 + await using view = await render(
580 + <RevealViews scope="first" visible selectedFile="external-a" />,
581 + );
582 await reveal();
583 expect(revealCalls.at(-1)?.fileKey).toBe("tree-file");
584 revealCalls.length = 0;
585
591 - await view.render(
586 + await view.rerender(
587 <RevealViews scope="second" visible selectedFile="external-b" requestId={1} />,
588 );
589 expect(revealCalls).toEqual([
@@ -597,16 +592,18 @@ describe("code-view file reveals", () => {
592 });
593
594 it("waits for a live viewer and applies each pending tree click only once", async () => {
600 - view = mount(<RevealViews scope="diff" visible={false} selectedFile="external" />);
601 - await view.initial;
595 + setup();
596 + await using view = await render(
597 + <RevealViews scope="diff" visible={false} selectedFile="external" />,
598 + );
599 await reveal();
600 expect(revealCalls).toEqual([]);
601
605 - await view.render(<RevealViews scope="diff" visible selectedFile="external" />);
602 + await view.rerender(<RevealViews scope="diff" visible selectedFile="external" />);
603 expect(revealCalls.map((call) => call.fileKey)).toEqual(["external", "tree-file"]);
604 revealCalls.length = 0;
608 - await view.render(<RevealViews scope="diff" visible={false} selectedFile="external" />);
609 - await view.render(<RevealViews scope="diff" visible selectedFile="external" />);
605 + await view.rerender(<RevealViews scope="diff" visible={false} selectedFile="external" />);
606 + await view.rerender(<RevealViews scope="diff" visible selectedFile="external" />);
607 expect(revealCalls).toEqual([
608 { scope: "diff", fileKey: "external", mounted: true, collapsed: false },
609 ]);
@@ -615,10 +612,10 @@ describe("code-view file reveals", () => {
612 // A click that lands in the same update that hides the viewer waits for it to return.
613 await act(async () => {
614 document.querySelector("button")!.click();
618 - view.root.render(<RevealViews scope="diff" visible={false} selectedFile="external" />);
615 + await view.rerender(<RevealViews scope="diff" visible={false} selectedFile="external" />);
616 });
617 expect(revealCalls).toEqual([]);
621 - await view.render(<RevealViews scope="diff" visible selectedFile="external" />);
618 + await view.rerender(<RevealViews scope="diff" visible selectedFile="external" />);
619 expect(revealCalls).toEqual([
620 { scope: "diff", fileKey: "external", mounted: true, collapsed: false },
621 { scope: "diff", fileKey: "tree-file", mounted: true, collapsed: false },
@@ -626,25 +623,27 @@ describe("code-view file reveals", () => {
623 });
624
625 it("cancels pending tree clicks when an external selection or diff scope changes", async () => {
629 - view = mount(<RevealViews scope="first" visible={false} selectedFile="external-a" />);
630 - await view.initial;
626 + setup();
627 + await using view = await render(
628 + <RevealViews scope="first" visible={false} selectedFile="external-a" />,
629 + );
630 await reveal();
632 - await view.render(
631 + await view.rerender(
632 <RevealViews scope="first" visible selectedFile="external-b" requestId={1} />,
633 );
634 expect(revealCalls.map((call) => call.fileKey)).toEqual(["external-b"]);
635 revealCalls.length = 0;
636
638 - await view.render(<RevealViews scope="first" visible={false} />);
637 + await view.rerender(<RevealViews scope="first" visible={false} />);
638 await reveal();
640 - await view.render(<RevealViews scope="second" visible={false} />);
641 - await view.render(<RevealViews scope="first" visible />);
639 + await view.rerender(<RevealViews scope="second" visible={false} />);
640 + await view.rerender(<RevealViews scope="first" visible />);
641 expect(revealCalls).toEqual([]);
642 });
643
644 it("reveals after a collapsed file expands and honors another click on the same file", async () => {
646 - view = mount(<RevealViews scope="diff" visible />);
647 - await view.initial;
645 + setup();
646 + await using _view = await render(<RevealViews scope="diff" visible />);
647 await reveal();
648 await reveal();
649 expect(revealCalls).toEqual([
apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
+61 -63
@@ -1,7 +1,6 @@
1 +import { act, render, stubGlobal, type Screen } from "../../../test/render";
2 import { EnvironmentId } from "@t3tools/contracts";
2 -import { act } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 +import { describe, expect, it, vi } from "vite-plus/test";
4
5 const { refresh } = vi.hoisted(() => ({ refresh: vi.fn<() => Promise<string | null>>() }));
6
@@ -20,101 +19,100 @@ import { AttachmentFilePreview } from "./AttachmentFilePreview";
19 describe("attachment HTML preview recovery", () => {
20 const originalUrl = "data:text/html,original";
21 const renewedUrl = "data:text/html,renewed";
23 - let now = 0;
24 - let root: Root;
25 - let container: HTMLDivElement;
22
27 - beforeEach(() => {
28 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
29 - now = 0;
30 - vi.spyOn(Date, "now").mockImplementation(() => now);
23 + function setup() {
24 refresh.mockReset().mockResolvedValueOnce(originalUrl).mockResolvedValue(renewedUrl);
32 - vi.stubGlobal(
33 - "fetch",
34 - vi.fn(async () => new Response("<p>Captured HTML</p>")),
35 - );
36 - container = document.createElement("div");
37 - document.body.append(container);
38 - root = createRoot(container);
39 - });
40 -
41 - afterEach(async () => {
42 - await act(async () => root.unmount());
43 - container.remove();
44 - vi.restoreAllMocks();
45 - vi.unstubAllGlobals();
46 - });
25 + }
26
27 const openRemote = () =>
49 - act(async () =>
50 - root.render(
51 - <AttachmentFilePreview
52 - name="document.html"
53 - mimeType="text/html"
54 - sizeBytes={100}
55 - asset={{ environmentId: EnvironmentId.make("test-environment"), attachmentId: "html" }}
56 - />,
57 - ),
28 + render(
29 + <AttachmentFilePreview
30 + name="document.html"
31 + mimeType="text/html"
32 + sizeBytes={100}
33 + asset={{ environmentId: EnvironmentId.make("test-environment"), attachmentId: "html" }}
34 + />,
35 );
36
60 - const toggleMode = async (label: string) => {
61 - const button = container.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);
37 + const toggleMode = async (screen: Screen, label: string) => {
38 + const button = screen.container.querySelector<HTMLButtonElement>(
39 + `button[aria-label="${label}"]`,
40 + );
41 expect(button, label).not.toBeNull();
42 await act(async () => button!.click());
43 };
65 - const alert = () => container.querySelector('[role="alert"]');
44 + const alert = (screen: Screen) => screen.container.querySelector('[role="alert"]');
45
46 it("keeps a renewed URL for subsequent rendered and source views", async () => {
68 - await openRemote();
69 - expect(container.querySelector("iframe")?.getAttribute("src")).toBe(originalUrl);
47 + setup();
48 + let now = 0;
49 + using _now = vi.spyOn(Date, "now").mockImplementation(() => now);
50 + using _fetch = stubGlobal(
51 + "fetch",
52 + vi.fn(async () => new Response("<p>Captured HTML</p>")),
53 + );
54 + await using screen = await openRemote();
55 + expect(screen.container.querySelector("iframe")?.getAttribute("src")).toBe(originalUrl);
56 now = 61 * 60_000;
71 - await toggleMode("Show HTML source");
57 + await toggleMode(screen, "Show HTML source");
58 await act(async () => {
59 await import("./ReadOnlySourcePreview");
60 });
61 expect(fetch).toHaveBeenCalledExactlyOnceWith(renewedUrl, expect.any(Object));
62 await vi.waitFor(() =>
77 - expect(container.querySelector("pre")?.textContent).toBe("<p>Captured HTML</p>"),
63 + expect(screen.container.querySelector("pre")?.textContent).toBe("<p>Captured HTML</p>"),
64 );
65
80 - await toggleMode("Show rendered page");
81 - expect(container.querySelector("iframe")?.getAttribute("src")).toBe(renewedUrl);
82 - await toggleMode("Show HTML source");
66 + await toggleMode(screen, "Show rendered page");
67 + expect(screen.container.querySelector("iframe")?.getAttribute("src")).toBe(renewedUrl);
68 + await toggleMode(screen, "Show HTML source");
69 expect(refresh).toHaveBeenCalledTimes(2);
70 expect(vi.mocked(fetch).mock.calls.map(([url]) => url)).toEqual([renewedUrl, renewedUrl]);
71 });
72
73 it("does not fetch or mark an expired URL fresh when reauthorization is unavailable", async () => {
88 - await openRemote();
74 + setup();
75 + let now = 0;
76 + using _now = vi.spyOn(Date, "now").mockImplementation(() => now);
77 + using _fetch = stubGlobal(
78 + "fetch",
79 + vi.fn(async () => new Response("<p>Captured HTML</p>")),
80 + );
81 + await using screen = await openRemote();
82 now = 61 * 60_000;
83 refresh.mockResolvedValue(null);
91 - await toggleMode("Show HTML source");
84 + await toggleMode(screen, "Show HTML source");
85 expect(fetch).not.toHaveBeenCalled();
93 - expect(alert()?.textContent).toContain("Reconnect to the environment and try again.");
86 + expect(alert(screen)?.textContent).toContain("Reconnect to the environment and try again.");
87
95 - await toggleMode("Show rendered page");
96 - await toggleMode("Show HTML source");
88 + await toggleMode(screen, "Show rendered page");
89 + await toggleMode(screen, "Show HTML source");
90 expect(refresh).toHaveBeenCalledTimes(3);
91 expect(fetch).not.toHaveBeenCalled();
92 });
93
94 it("can return to rendered HTML after local source decoding fails", async () => {
95 + setup();
96 + let now = 0;
97 + using _now = vi.spyOn(Date, "now").mockImplementation(() => now);
98 + using _fetch = stubGlobal(
99 + "fetch",
100 + vi.fn(async () => new Response("<p>Captured HTML</p>")),
101 + );
102 const file = new Blob([new Uint8Array([0x3c, 0x70, 0x3e, 0xe9])], { type: "text/html" });
103 - await act(async () =>
104 - root.render(
105 - <AttachmentFilePreview
106 - name="document.html"
107 - mimeType="text/html"
108 - sizeBytes={file.size}
109 - file={file}
110 - />,
111 - ),
103 + await using screen = await render(
104 + <AttachmentFilePreview
105 + name="document.html"
106 + mimeType="text/html"
107 + sizeBytes={file.size}
108 + file={file}
109 + />,
110 );
113 - await toggleMode("Show HTML source");
114 - await vi.waitFor(() => expect(alert()?.textContent).toContain("not UTF-8"));
111 + await toggleMode(screen, "Show HTML source");
112 + await vi.waitFor(() => expect(alert(screen)?.textContent).toContain("not UTF-8"));
113
116 - await toggleMode("Show rendered page");
117 - expect(alert()).toBeNull();
118 - expect(container.querySelector("iframe")?.title).toBe("document.html");
114 + await toggleMode(screen, "Show rendered page");
115 + expect(alert(screen)).toBeNull();
116 + expect(screen.container.querySelector("iframe")?.title).toBe("document.html");
117 });
118 });
apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx
+11 -23
@@ -1,39 +1,27 @@
1 -import { act } from "react";
2 -import { createRoot } from "react-dom/client";
3 -import { expect, it, onTestFinished, vi } from "vite-plus/test";
1 +import { render } from "../../../test/render";
2 +import { expect, it } from "vite-plus/test";
3
4 import { BrowserDocumentFrame } from "./BrowserDocumentFrame";
5
6 it("keeps the loaded HTML page while its signed URL renews, and reloads on a new revision", async () => {
8 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
9 - const container = document.createElement("div");
10 - document.body.append(container);
11 - const root = createRoot(container);
12 - onTestFinished(async () => {
13 - await act(async () => root.unmount());
14 - container.remove();
15 - vi.unstubAllGlobals();
16 - });
17 - const render = (src: string, documentKey?: string) =>
18 - act(async () =>
19 - root.render(
20 - <BrowserDocumentFrame src={src} title="Review" pdf={false} documentKey={documentKey} />,
21 - ),
22 - );
7 + const frameUi = (src: string, documentKey?: string) => (
8 + <BrowserDocumentFrame src={src} title="Review" pdf={false} documentKey={documentKey} />
9 + );
10
24 - await render("about:blank#token-a", "review.html:1");
11 + await using screen = await render(frameUi("about:blank#token-a", "review.html:1"));
12 + const { container } = screen;
13 const frame = container.querySelector("iframe");
26 - await render("about:blank#token-b", "review.html:1");
14 + await screen.rerender(frameUi("about:blank#token-b", "review.html:1"));
15 expect(container.querySelector("iframe")).toBe(frame);
16 expect(frame?.getAttribute("src")).toBe("about:blank#token-a");
17
30 - await render("about:blank#token-c", "review.html:2");
18 + await screen.rerender(frameUi("about:blank#token-c", "review.html:2"));
19 expect(container.querySelector("iframe")).not.toBe(frame);
20 expect(container.querySelector("iframe")?.getAttribute("src")).toBe("about:blank#token-c");
21
34 - await render("about:blank#first");
22 + await screen.rerender(frameUi("about:blank#first"));
23 const urlDrivenFrame = container.querySelector("iframe");
36 - await render("about:blank#second");
24 + await screen.rerender(frameUi("about:blank#second"));
25 expect(container.querySelector("iframe")).not.toBe(urlDrivenFrame);
26 expect(container.querySelector("iframe")?.getAttribute("src")).toBe("about:blank#second");
27 });
apps/web/src/components/files/FileBrowserPanel.browser.test.tsx
+125 -100
@@ -1,9 +1,9 @@
1 +import { act, render } from "../../../test/render";
2 import "../../index.css";
3
4 import { EnvironmentId, type ProjectEntry } from "@t3tools/contracts";
4 -import { act, type ReactNode } from "react";
5 -import { createRoot, type Root } from "react-dom/client";
6 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5 +import { type ReactNode } from "react";
6 +import { describe, expect, it, vi } from "vite-plus/test";
7
8 import FileBrowserPanel from "./FileBrowserPanel";
9
@@ -53,8 +53,6 @@ vi.mock("~/components/ui/tooltip", () => ({
53 }));
54
55 describe("Files panel", () => {
56 - let root: Root | undefined;
57 - let container: HTMLDivElement | undefined;
56 const props = {
57 environmentId: EnvironmentId.make("test-environment"),
58 cwd: "/workspace",
@@ -65,67 +63,75 @@ describe("Files panel", () => {
63 workspaceMutationId: null,
64 };
65
68 - async function render() {
69 - if (!container) {
70 - container = document.body.appendChild(document.createElement("div"));
71 - // The tree virtualizes its rows, so it needs a real viewport to render any.
72 - container.style.cssText =
73 - "display: flex; flex-direction: column; width: 320px; height: 480px;";
74 - root = createRoot(container);
66 + async function renderPanel() {
67 + const container = document.createElement("div");
68 + // The tree virtualizes its rows, so it needs a real viewport to render any.
69 + container.style.cssText = "display: flex; flex-direction: column; width: 320px; height: 480px;";
70 + await using stack = new AsyncDisposableStack();
71 + const screen = stack.use(await render(<FileBrowserPanel {...props} />, { container }));
72 + const rerender = () => screen.rerender(<FileBrowserPanel {...props} />);
73 + function searchInput() {
74 + const input = container!.querySelector<HTMLInputElement>('input[type="search"]');
75 + expect(input).not.toBeNull();
76 + return input!;
77 }
76 - await act(async () => root!.render(<FileBrowserPanel {...props} />));
77 - }
78
79 - function searchInput() {
80 - const input = container!.querySelector<HTMLInputElement>('input[type="search"]');
81 - expect(input).not.toBeNull();
82 - return input!;
83 - }
79 + async function search(value: string) {
80 + const input = searchInput();
81 + // React tracks the last value it saw on the element, so set it through the native setter.
82 + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
83 + await act(async () => {
84 + input.dispatchEvent(new Event("input", { bubbles: true }));
85 + });
86 + }
87
85 - async function search(value: string) {
86 - const input = searchInput();
87 - // React tracks the last value it saw on the element, so set it through the native setter.
88 - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
89 - await act(async () => {
90 - input.dispatchEvent(new Event("input", { bubbles: true }));
91 - });
92 - }
88 + function visiblePaths() {
89 + const tree = container!.querySelector("file-tree-container");
90 + if (!tree) return [];
91 + return [...tree.shadowRoot!.querySelectorAll("[data-item-path]")].map((row) =>
92 + row.getAttribute("data-item-path"),
93 + );
94 + }
95
94 - function visiblePaths() {
95 - const tree = container!.querySelector("file-tree-container");
96 - if (!tree) return [];
97 - return [...tree.shadowRoot!.querySelectorAll("[data-item-path]")].map((row) =>
98 - row.getAttribute("data-item-path"),
99 - );
100 - }
96 + function hasMessage(message: string) {
97 + return [...container!.querySelectorAll("div")].some(
98 + (node) => node.childNodes.length === 1 && node.textContent === message,
99 + );
100 + }
101
102 - function hasMessage(message: string) {
103 - return [...container!.querySelectorAll("div")].some(
104 - (node) => node.childNodes.length === 1 && node.textContent === message,
105 - );
106 - }
102 + function expectVisibleLoadingStatus() {
103 + const status = container!.querySelector<HTMLElement>('[role="status"]');
104 + expect(status?.textContent).toBe("Loading files…");
105 + expect(status!.checkVisibility()).toBe(true);
106 + const bounds = status!.getBoundingClientRect();
107 + expect(bounds.width).toBeGreaterThan(1);
108 + expect(bounds.height).toBeGreaterThan(1);
109 + }
110
108 - function expectVisibleLoadingStatus() {
109 - const status = container!.querySelector<HTMLElement>('[role="status"]');
110 - expect(status?.textContent).toBe("Loading files…");
111 - expect(status!.checkVisibility()).toBe(true);
112 - const bounds = status!.getBoundingClientRect();
113 - expect(bounds.width).toBeGreaterThan(1);
114 - expect(bounds.height).toBeGreaterThan(1);
115 - }
111 + function rowTop(path: string) {
112 + const row = container!
113 + .querySelector("file-tree-container")
114 + ?.shadowRoot!.querySelector(`[data-item-path="${CSS.escape(path)}"]`);
115 + expect(row, `visible row ${path}`).not.toBeNull();
116 + const bounds = row!.getBoundingClientRect();
117 + expect(bounds.height).toBeGreaterThan(0);
118 + return bounds.top;
119 + }
120
117 - function rowTop(path: string) {
118 - const row = container!
119 - .querySelector("file-tree-container")
120 - ?.shadowRoot!.querySelector(`[data-item-path="${CSS.escape(path)}"]`);
121 - expect(row, `visible row ${path}`).not.toBeNull();
122 - const bounds = row!.getBoundingClientRect();
123 - expect(bounds.height).toBeGreaterThan(0);
124 - return bounds.top;
121 + const environment = stack.move();
122 + return {
123 + container,
124 + searchInput,
125 + search,
126 + visiblePaths,
127 + hasMessage,
128 + expectVisibleLoadingStatus,
129 + rowTop,
130 + rerender,
131 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
132 + };
133 }
126 -
127 - beforeEach(() => {
128 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
134 + function setup() {
135 files.directoryEntries = [
136 { path: "src", kind: "directory" },
137 { path: "src/app.ts", kind: "file" },
@@ -136,34 +142,32 @@ describe("Files panel", () => {
142 files.searchEntries = [];
143 files.searchPending = false;
144 files.searchError = null;
139 - });
140 -
141 - afterEach(async () => {
142 - await act(async () => root?.unmount());
143 - container?.remove();
144 - root = undefined;
145 - container = undefined;
146 - vi.unstubAllGlobals();
147 - });
145 + files.load.mockReset();
146 + files.refresh.mockReset();
147 + files.loadingDirectories = new Set();
148 + props.onOpenFile.mockReset();
149 + }
150
151 it("keeps visible rows stationary during loading while showing initial loading status", async () => {
152 + setup();
153 const entries = files.directoryEntries;
154 files.directoryEntries = [];
155 files.directoryReady = false;
156 files.directoryPending = true;
154 - await render();
157 + await using screen = await renderPanel();
158 + const { search, visiblePaths, expectVisibleLoadingStatus, rowTop } = screen;
159 expect(visiblePaths()).toEqual([]);
160 expectVisibleLoadingStatus();
161
162 files.directoryEntries = entries;
163 files.directoryReady = true;
164 files.directoryPending = false;
161 - await render();
165 + await screen.rerender();
166 expect(visiblePaths()).toEqual(["src/", "package.json"]);
167 const initialTop = rowTop("package.json");
168
169 files.directoryPending = true;
166 - await render();
170 + await screen.rerender();
171 expect(rowTop("package.json")).toBe(initialTop);
172
173 files.directoryPending = false;
@@ -177,12 +181,14 @@ describe("Files panel", () => {
181 expect(rowTop("package.json")).toBe(filteredTop);
182
183 files.searchPending = false;
180 - await render();
184 + await screen.rerender();
185 expect(rowTop("package.json")).toBe(filteredTop);
186 });
187
188 it("shows no matching files instead of the full tree when a filename is absent", async () => {
185 - await render();
189 + setup();
190 + await using screen = await renderPanel();
191 + const { search, visiblePaths, hasMessage } = screen;
192 expect(visiblePaths()).toEqual(["src/", "package.json"]);
193
194 await search(".env.local");
@@ -198,15 +204,19 @@ describe("Files panel", () => {
204 });
205
206 it("still finds ignored files already loaded from a directory", async () => {
207 + setup();
208 files.directoryEntries.push({ path: ".env.local", kind: "file", ignored: true });
202 - await render();
209 + await using screen = await renderPanel();
210 + const { search, visiblePaths, hasMessage } = screen;
211 await search(".env.local");
212 expect(visiblePaths()).toEqual([".env.local"]);
213 expect(hasMessage("No matching files.")).toBe(false);
214 });
215
216 it("waits for remote matches without showing unrelated files or a premature empty result", async () => {
209 - await render();
217 + setup();
218 + await using screen = await renderPanel();
219 + const { search, visiblePaths, hasMessage, expectVisibleLoadingStatus } = screen;
220 files.searchPending = true;
221 await search("settings.ts");
222 expect(visiblePaths()).toEqual([]);
@@ -215,13 +225,15 @@ describe("Files panel", () => {
225
226 files.searchEntries = [{ path: "config/settings.ts", kind: "file" }];
227 files.searchPending = false;
218 - await render();
228 + await screen.rerender();
229 expect(visiblePaths()).toEqual(["config/", "config/settings.ts"]);
230 expect(hasMessage("No matching files.")).toBe(false);
231 });
232
233 it("restores the tree on Escape after an unsuccessful search", async () => {
224 - await render();
234 + setup();
235 + await using screen = await renderPanel();
236 + const { searchInput, search, visiblePaths, hasMessage } = screen;
237 await search("missing-file");
238 expect(visiblePaths()).toEqual([]);
239
@@ -236,7 +248,9 @@ describe("Files panel", () => {
248 });
249
250 it("does not report an empty result when the search failed", async () => {
239 - await render();
251 + setup();
252 + await using screen = await renderPanel();
253 + const { container, search, visiblePaths, hasMessage } = screen;
254 files.searchError = "Workspace search failed.";
255 await search("missing-file");
256 expect(visiblePaths()).toEqual([]);
@@ -260,71 +274,82 @@ describe("Files panel", () => {
274 const listed = () => files.load.mock.calls.map(([path]) => path);
275
276 // Answer each listing the panel asks for, as the server would, until it asks for no more.
263 - async function answerListings() {
277 + async function answerListings(screen: Awaited<ReturnType<typeof renderPanel>>) {
278 const answered = new Set<string>();
279 for (;;) {
280 const path = listed().find((requested) => !answered.has(requested));
281 if (path === undefined) return;
282 answered.add(path);
283 files.directoryEntries = [...files.directoryEntries, ...(workspace[path] ?? [])];
270 - await render();
284 + await screen.rerender();
285 }
286 }
287
274 - function button(label: "Expand all folders" | "Collapse all folders") {
275 - const match = container!.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);
288 + function button(
289 + screen: Awaited<ReturnType<typeof renderPanel>>,
290 + label: "Expand all folders" | "Collapse all folders",
291 + ) {
292 + const match = screen.container.querySelector<HTMLButtonElement>(
293 + `button[aria-label="${label}"]`,
294 + );
295 expect(match, label).not.toBeNull();
296 return match!;
297 }
298
280 - async function clickRow(path: string) {
281 - const row = container!
299 + async function clickRow(screen: Awaited<ReturnType<typeof renderPanel>>, path: string) {
300 + const row = screen.container
301 .querySelector("file-tree-container")!
302 .shadowRoot!.querySelector<HTMLElement>(`[data-item-path="${path}"]`);
303 expect(row, path).not.toBeNull();
304 await act(async () => row!.click());
286 - await answerListings();
305 + await answerListings(screen);
306 }
307
289 - beforeEach(() => {
308 + function setupExpandAll() {
309 files.load.mockClear();
310 files.directoryEntries = [
311 { path: "src", kind: "directory" },
312 { path: "node_modules", kind: "directory", ignored: true },
313 { path: "README.md", kind: "file" },
314 ];
296 - });
315 + }
316
317 it("opens every folder except ignored ones, which it never lists", async () => {
299 - await render();
300 - await act(async () => button("Expand all folders").click());
301 - await answerListings();
318 + setup();
319 + setupExpandAll();
320 + await using screen = await renderPanel();
321 + const { visiblePaths } = screen;
322 + await act(async () => button(screen, "Expand all folders").click());
323 + await answerListings(screen);
324
325 expect(listed().toSorted()).toEqual(["src", "src/lib"]);
326 expect(visiblePaths()).toContain("src/lib/util.ts");
327 expect(visiblePaths()).not.toContain("node_modules/.modules.yaml");
306 - button("Collapse all folders");
328 + button(screen, "Collapse all folders");
329
330 // Collapsing a folder by hand ends expand all; reopening it counts as all expanded again,
331 // with the ignored folder still closed.
310 - await clickRow("src/lib/");
311 - button("Expand all folders");
312 - await clickRow("src/lib/");
313 - button("Collapse all folders");
332 + await clickRow(screen, "src/lib/");
333 + button(screen, "Expand all folders");
334 + await clickRow(screen, "src/lib/");
335 + button(screen, "Collapse all folders");
336 });
337
338 it("opens an ignored folder by hand without walking into it, and collapses it with the rest", async () => {
317 - await render();
318 - await act(async () => button("Expand all folders").click());
319 - await answerListings();
320 -
321 - await clickRow("node_modules/");
339 + setup();
340 + setupExpandAll();
341 + await using screen = await renderPanel();
342 + const { visiblePaths } = screen;
343 + await act(async () => button(screen, "Expand all folders").click());
344 + await answerListings(screen);
345 +
346 + await clickRow(screen, "node_modules/");
347 expect(listed()).toContain("node_modules");
348 expect(listed()).not.toContain("node_modules/react");
349 expect(visiblePaths()).toContain("node_modules/react/");
350 expect(visiblePaths()).not.toContain("node_modules/react/index.js");
351
327 - await act(async () => button("Collapse all folders").click());
352 + await act(async () => button(screen, "Collapse all folders").click());
353 expect(visiblePaths()).toEqual(["node_modules/", "src/", "README.md"]);
354 });
355 });
apps/web/src/components/files/useFileSaveCoordinator.browser.test.tsx
+71 -71
@@ -1,8 +1,8 @@
1 +import { render, fakeTimers } from "../../../test/render";
2 import { EnvironmentId } from "@t3tools/contracts";
3 import { AsyncResult } from "effect/reactivity";
3 -import { act, StrictMode, useEffect } from "react";
4 -import { createRoot, type Root } from "react-dom/client";
5 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4 +import { StrictMode, useEffect } from "react";
5 +import { describe, expect, it, vi } from "vite-plus/test";
6
7 const { writeFile, confirmFile, readScope, getUnsavedFile } = vi.hoisted(() => ({
8 writeFile: vi.fn(),
@@ -36,59 +36,43 @@ const defaultProps = {
36 relativePath: "file.txt",
37 onPendingChange,
38 };
39 -let root: Root | null;
40 -// The editor's change callback from the latest commit, as an editor would hold it.
41 -let latestChange: (contents: string) => void;
42 -
43 -function FileSurface(props: Parameters<typeof useFileSaveCoordinator>[0]) {
44 - const coordinator = useFileSaveCoordinator(props);
45 - const onChange = (contents: string) => coordinator.change(contents);
46 - useEffect(() => {
47 - latestChange = onChange;
48 - });
49 - return null;
50 -}
51 -
52 -async function render(props = defaultProps) {
53 - root ??= createRoot(document.createElement("div"));
54 - await act(async () =>
55 - root!.render(
56 - <StrictMode>
57 - <FileSurface {...props} />
58 - </StrictMode>,
59 - ),
60 - );
61 -}
62 -const mount = render;
63 -
64 -async function unmountSurface() {
65 - await act(async () => root!.unmount());
66 - root = null;
67 -}
68 -
69 -const changeHandler = () => latestChange;
70 -
71 -beforeEach(() => {
72 - root = null;
73 - vi.useFakeTimers();
74 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
39 +function setup() {
40 writeFile.mockReset().mockResolvedValue(AsyncResult.success(undefined));
41 confirmFile.mockReset();
42 readScope.mockReset().mockReturnValue(true);
43 getUnsavedFile.mockReset().mockReturnValue(null);
44 onPendingChange.mockReset();
80 -});
45 +}
46
82 -afterEach(async () => {
83 - if (root) await unmountSurface();
84 - vi.useRealTimers();
85 - vi.unstubAllGlobals();
86 -});
47 +async function mount(props = defaultProps) {
48 + let latestChange: (contents: string) => void = () => {};
49 + function FileSurface(props: Parameters<typeof useFileSaveCoordinator>[0]) {
50 + const coordinator = useFileSaveCoordinator(props);
51 + useEffect(() => {
52 + latestChange = (contents) => coordinator.change(contents);
53 + });
54 + return null;
55 + }
56 + const ui = (props: Parameters<typeof useFileSaveCoordinator>[0]) => (
57 + <StrictMode>
58 + <FileSurface {...props} />
59 + </StrictMode>
60 + );
61 + const screen = await render(ui(props), { router: false });
62 + return {
63 + changeHandler: () => latestChange,
64 + rerender: (props: Parameters<typeof useFileSaveCoordinator>[0]) => screen.rerender(ui(props)),
65 + unmount: screen.unmount,
66 + [Symbol.asyncDispose]: () => screen[Symbol.asyncDispose](),
67 + };
68 +}
69
70 describe("file-save React lifecycle", () => {
71 it("persists editor model changes after StrictMode setup replay", async () => {
90 - await mount();
91 - changeHandler()("AUDIT7907NATIVE\n");
72 + setup();
73 + using _timers = fakeTimers();
74 + await using screen = await mount();
75 + screen.changeHandler()("AUDIT7907NATIVE\n");
76 expect(onPendingChange).toHaveBeenCalledWith("file.txt", true);
77 await vi.advanceTimersByTimeAsync(500);
78 expect(writeFile).toHaveBeenCalledExactlyOnceWith({
@@ -105,9 +89,11 @@ describe("file-save React lifecycle", () => {
89 });
90
91 it("persists rendered Markdown task changes after StrictMode setup replay", async () => {
108 - await mount({ ...defaultProps, relativePath: "README.md" });
92 + setup();
93 + using _timers = fakeTimers();
94 + await using screen = await mount({ ...defaultProps, relativePath: "README.md" });
95 const nextContents = setMarkdownTaskChecked("- [ ] task\n", 2, true);
110 - changeHandler()(nextContents);
96 + screen.changeHandler()(nextContents);
97 await vi.advanceTimersByTimeAsync(500);
98 expect(writeFile).toHaveBeenCalledExactlyOnceWith({
99 environmentId,
@@ -116,11 +102,13 @@ describe("file-save React lifecycle", () => {
102 });
103
104 it("keeps the debounce across rerenders of the same file", async () => {
119 - await mount();
120 - changeHandler()("first");
105 + setup();
106 + using _timers = fakeTimers();
107 + await using screen = await mount();
108 + screen.changeHandler()("first");
109 await vi.advanceTimersByTimeAsync(300);
122 - await render(defaultProps);
123 - changeHandler()("latest");
110 + await screen.rerender(defaultProps);
111 + screen.changeHandler()("latest");
112 await vi.advanceTimersByTimeAsync(499);
113 expect(writeFile).not.toHaveBeenCalled();
114 await vi.advanceTimersByTimeAsync(1);
@@ -129,10 +117,12 @@ describe("file-save React lifecycle", () => {
117 });
118
119 it("flushes on unmount and ignores a retired editor callback", async () => {
132 - await mount();
133 - const retiredChange = changeHandler();
120 + setup();
121 + using _timers = fakeTimers();
122 + await using screen = await mount();
123 + const retiredChange = screen.changeHandler();
124 retiredChange("pending edit");
135 - await unmountSurface();
125 + await screen.unmount();
126 retiredChange("stale editor contents");
127 await vi.runAllTimersAsync();
128 expect(writeFile).toHaveBeenCalledTimes(1);
@@ -142,11 +132,13 @@ describe("file-save React lifecycle", () => {
132 it.each([false, true])(
133 "keeps edits pending after permission is revoked before a React update (unmount: %s)",
134 async (unmount) => {
145 - await mount();
146 - changeHandler()("pending edit");
135 + setup();
136 + using _timers = fakeTimers();
137 + await using screen = await mount();
138 + screen.changeHandler()("pending edit");
139 readScope.mockReturnValue(false);
140 if (unmount) {
149 - await unmountSurface();
141 + await screen.unmount();
142 }
143 await vi.runAllTimersAsync();
144 expect(writeFile).not.toHaveBeenCalled();
@@ -156,14 +148,16 @@ describe("file-save React lifecycle", () => {
148 );
149
150 it("resumes an unsaved draft when write permission returns after effect replay", async () => {
151 + setup();
152 + using _timers = fakeTimers();
153 readScope.mockReturnValue(false);
154 getUnsavedFile.mockReturnValue({ contents: "pending draft" });
161 - await mount();
155 + await using screen = await mount();
156 await vi.runAllTimersAsync();
157 expect(writeFile).not.toHaveBeenCalled();
158
159 readScope.mockReturnValue(true);
166 - await render(defaultProps);
160 + await screen.rerender(defaultProps);
161 await vi.advanceTimersByTimeAsync(500);
162 expect(writeFile).toHaveBeenCalledExactlyOnceWith({
163 environmentId,
@@ -173,8 +167,10 @@ describe("file-save React lifecycle", () => {
167 });
168
169 it("recovers an existing draft once after StrictMode setup replay", async () => {
170 + setup();
171 + using _timers = fakeTimers();
172 getUnsavedFile.mockReturnValue({ contents: "reopened draft" });
177 - await mount();
173 + await using _screen = await mount();
174 await vi.runAllTimersAsync();
175 expect(writeFile).toHaveBeenCalledExactlyOnceWith({
176 environmentId,
@@ -188,13 +184,15 @@ describe("file-save React lifecycle", () => {
184 { cwd: "/other-workspace" },
185 { environmentId: EnvironmentId.make("other-environment") },
186 ])("retires callbacks when the file identity changes: %j", async (change) => {
191 - await mount();
192 - const retiredChange = changeHandler();
187 + setup();
188 + using _timers = fakeTimers();
189 + await using screen = await mount();
190 + const retiredChange = screen.changeHandler();
191 retiredChange("old file edit");
192 const nextProps = { ...defaultProps, ...change };
195 - await render(nextProps);
193 + await screen.rerender(nextProps);
194 retiredChange("stale editor contents");
197 - changeHandler()("new file edit");
195 + screen.changeHandler()("new file edit");
196 await vi.runAllTimersAsync();
197 expect(writeFile.mock.calls.map(([request]) => request)).toEqual([
198 {
@@ -213,12 +211,14 @@ describe("file-save React lifecycle", () => {
211 });
212
213 it("does not reactivate a retired callback when the same file mounts again", async () => {
216 - await mount();
217 - const retiredChange = changeHandler();
218 - await unmountSurface();
219 - await mount();
214 + setup();
215 + using _timers = fakeTimers();
216 + await using screen = await mount();
217 + const retiredChange = screen.changeHandler();
218 + await screen.unmount();
219 + await using reopened = await mount();
220 retiredChange("stale contents");
221 - changeHandler()("current contents");
221 + reopened.changeHandler()("current contents");
222 await vi.runAllTimersAsync();
223 expect(writeFile).toHaveBeenCalledTimes(1);
224 expect(writeFile.mock.calls[0]![0].input.contents).toBe("current contents");
apps/web/src/components/media/AttachmentImage.browser.test.tsx
+44 -51
@@ -1,6 +1,5 @@
1 -import { act, type ReactNode } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
1 +import { act, render, stubGlobal, type Screen } from "../../../test/render";
2 +import { expect, it, vi } from "vite-plus/test";
3 import { AttachmentImage } from "./AttachmentImage";
4 import { prepareImageForAttachment } from "../../lib/imageCompression";
5
@@ -9,52 +8,27 @@ vi.mock("../../lib/imageCompression", async (importOriginal) => ({
8 prepareImageForAttachment: vi.fn(),
9 }));
10
12 -let root: Root | undefined;
13 -let container: HTMLDivElement | undefined;
11 const fetchImage = vi.fn();
12 const revokeUrl = vi.fn();
13 const jpeg = new File(["jpeg"], "photo.jpg", { type: "image/jpeg" });
14
18 -beforeEach(() => {
19 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
20 - vi.stubGlobal("fetch", fetchImage);
21 - vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:jpeg");
22 - vi.spyOn(URL, "revokeObjectURL").mockImplementation(revokeUrl);
23 - fetchImage.mockResolvedValue(new Response(new Blob(["heic"])));
24 - vi.mocked(prepareImageForAttachment).mockResolvedValue({
25 - ok: true,
26 - file: jpeg,
27 - recompressed: true,
28 - });
29 -});
30 -
31 -afterEach(async () => {
32 - await act(() => root?.unmount());
33 - container?.remove();
34 - root = undefined;
35 - container = undefined;
36 - vi.restoreAllMocks();
37 - vi.unstubAllGlobals();
38 - vi.clearAllMocks();
39 -});
40 -
41 -async function render(element: ReactNode) {
42 - if (!container) {
43 - container = document.body.appendChild(document.createElement("div"));
44 - root = createRoot(container);
45 - }
46 - await act(() => root!.render(element));
15 +function setup() {
16 + fetchImage.mockReset().mockResolvedValue(new Response(new Blob(["heic"])));
17 + revokeUrl.mockReset();
18 + vi.mocked(prepareImageForAttachment)
19 + .mockReset()
20 + .mockResolvedValue({ ok: true, file: jpeg, recompressed: true });
21 }
22
49 -function image() {
50 - const img = container!.querySelector("img");
23 +function image(screen: Screen) {
24 + const img = screen.container.querySelector("img");
25 expect(img).not.toBeNull();
26 return img!;
27 }
28
29 // Stands in for the browser failing to decode the current source.
56 -async function failDecode() {
57 - const img = image();
30 +async function failDecode(screen: Screen) {
31 + const img = image(screen);
32 await act(() => {
33 img.dispatchEvent(new Event("error"));
34 });
@@ -71,49 +45,68 @@ it.each([
45 ])(
46 "converts $name after native decoding fails and releases its preview",
47 async ({ name, mimeType }) => {
74 - await render(
48 + setup();
49 + using _fetch = stubGlobal("fetch", fetchImage);
50 + using _createUrl = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:jpeg");
51 + using _revokeUrl = vi.spyOn(URL, "revokeObjectURL").mockImplementation(revokeUrl);
52 + await using screen = await render(
53 <AttachmentImage src="https://environment.test/photo" name={name} mimeType={mimeType} />,
54 );
55 expect(fetchImage).not.toHaveBeenCalled();
78 - await failDecode();
79 - expect(image().getAttribute("src")).toBe("blob:jpeg");
56 + await failDecode(screen);
57 + await vi.waitFor(() => expect(image(screen).getAttribute("src")).toBe("blob:jpeg"));
58 expect(prepareImageForAttachment).toHaveBeenCalledWith(
59 expect.objectContaining({ name, type: "image/heic" }),
60 50 * 1024 * 1024,
61 );
84 - await act(() => root!.unmount());
85 - root = undefined;
62 + await screen.unmount();
63 expect(revokeUrl).toHaveBeenCalledWith("blob:jpeg");
64 },
65 );
66
67 it("leaves PNG errors to the caller without fetching or converting", async () => {
68 + setup();
69 + using _fetch = stubGlobal("fetch", fetchImage);
70 + using _createUrl = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:jpeg");
71 + using _revokeUrl = vi.spyOn(URL, "revokeObjectURL").mockImplementation(revokeUrl);
72 const onError = vi.fn();
92 - await render(<AttachmentImage src="blob:png" name="photo.png" onError={onError} />);
93 - expectDecodeErrorFor(onError, await failDecode());
73 + await using screen = await render(
74 + <AttachmentImage src="blob:png" name="photo.png" onError={onError} />,
75 + );
76 + expectDecodeErrorFor(onError, await failDecode(screen));
77 expect(fetchImage).not.toHaveBeenCalled();
78 });
79
80 it("reports failed HEIC conversion through the existing error handler", async () => {
81 + setup();
82 + using _fetch = stubGlobal("fetch", fetchImage);
83 + using _createUrl = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:jpeg");
84 + using _revokeUrl = vi.spyOn(URL, "revokeObjectURL").mockImplementation(revokeUrl);
85 const onError = vi.fn();
86 vi.mocked(prepareImageForAttachment).mockResolvedValue({ ok: false, reason: "unreadable" });
100 - await render(<AttachmentImage src="blob:heic" name="photo.heif" onError={onError} />);
101 - expectDecodeErrorFor(onError, await failDecode());
87 + await using screen = await render(
88 + <AttachmentImage src="blob:heic" name="photo.heif" onError={onError} />,
89 + );
90 + expectDecodeErrorFor(onError, await failDecode(screen));
91 expect(URL.createObjectURL).not.toHaveBeenCalled();
92 });
93
94 it("discards an old decode when navigating to a different source", async () => {
95 + setup();
96 + using _fetch = stubGlobal("fetch", fetchImage);
97 + using _createUrl = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:jpeg");
98 + using _revokeUrl = vi.spyOn(URL, "revokeObjectURL").mockImplementation(revokeUrl);
99 let finishDecode!: (result: Awaited<ReturnType<typeof prepareImageForAttachment>>) => void;
100 vi.mocked(prepareImageForAttachment).mockReturnValue(
101 new Promise((resolve) => {
102 finishDecode = resolve;
103 }),
104 );
112 - await render(<AttachmentImage src="blob:first" name="photo.heic" />);
113 - await failDecode();
114 - await render(<AttachmentImage src="blob:second" name="photo.heic" />);
105 + await using screen = await render(<AttachmentImage src="blob:first" name="photo.heic" />);
106 + await failDecode(screen);
107 + await screen.rerender(<AttachmentImage src="blob:second" name="photo.heic" />);
108 await act(() => finishDecode({ ok: true, file: jpeg, recompressed: true }));
116 - expect(image().getAttribute("src")).toBe("blob:second");
109 + expect(image(screen).getAttribute("src")).toBe("blob:second");
110 expect(URL.createObjectURL).not.toHaveBeenCalled();
111 expect(fetchImage.mock.calls[0]?.[1].signal.aborted).toBe(true);
112 });
apps/web/src/components/onboarding/WelcomeWizard.browser.test.tsx
+29 -37
@@ -1,7 +1,6 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
1 +import { act, render, stubGlobal } from "../../../test/render";
2 import { EnvironmentId, ProjectId } from "@t3tools/contracts";
4 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
3 +import { expect, it, vi } from "vite-plus/test";
4
5 const mocks = vi.hoisted(() => ({
6 importThreads: vi.fn(),
@@ -97,39 +96,28 @@ vi.mock("../ui/toast", () => ({
96
97 import { WelcomeWizard } from "./WelcomeWizard";
98
100 -let root: Root;
101 -let container: HTMLDivElement;
102 -
103 -beforeEach(() => {
99 +function setup() {
100 + using stack = new DisposableStack();
101 vi.clearAllMocks();
105 - vi.stubGlobal(
106 - "ResizeObserver",
107 - class {
108 - observe() {}
109 - unobserve() {}
110 - disconnect() {}
111 - },
102 + stack.use(
103 + stubGlobal(
104 + "ResizeObserver",
105 + class {
106 + observe() {}
107 + unobserve() {}
108 + disconnect() {}
109 + },
110 + ),
111 );
113 - Object.defineProperty(Element.prototype, "getAnimations", {
114 - configurable: true,
115 - value: () => [],
116 - });
112 + stack.use(vi.spyOn(Element.prototype, "getAnimations").mockReturnValue([]));
113 mocks.projects = [{ id: "test-project", environmentId: "test-env", workspaceRoot: "/project" }];
118 - mocks.complete.mockResolvedValue(undefined);
119 - mocks.refresh.mockResolvedValue(undefined);
120 - mocks.importThreads.mockResolvedValue({
121 - _tag: "Success",
122 - value: { importedCount: 28, skippedCount: 1 },
123 - });
124 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
125 - container = document.createElement("div");
126 - document.body.append(container);
127 - root = createRoot(container);
128 -});
129 -afterEach(async () => {
130 - await act(async () => root.unmount());
131 - container.remove();
132 -});
114 + mocks.complete.mockReset().mockResolvedValue(undefined);
115 + mocks.refresh.mockReset().mockResolvedValue(undefined);
116 + mocks.importThreads
117 + .mockReset()
118 + .mockResolvedValue({ _tag: "Success", value: { importedCount: 28, skippedCount: 1 } });
119 + return stack.move();
120 +}
121
122 async function click(label: string) {
123 const button = [...document.querySelectorAll("button")].find(
@@ -140,12 +128,13 @@ async function click(label: string) {
128 }
129
130 it("enters the workspace after a partial import and warns after navigation finishes", async () => {
131 + using _setup = setup();
132 let finishNavigation = () => {};
133 const navigation = new Promise<void>((resolve) => {
134 finishNavigation = resolve;
135 });
136 const onDone = vi.fn(() => navigation);
148 - await act(async () => root.render(<WelcomeWizard localAvailable onDone={onDone} />));
137 + await using _screen = await render(<WelcomeWizard localAvailable onDone={onDone} />);
138 await click("Continue");
139 await click("Continue");
140 await click("Import 1 project");
@@ -175,12 +164,13 @@ it.each([
164 ] as const)(
165 "finishes setup with %i imported and %i skipped threads",
166 async (importedCount, skippedCount, warning) => {
167 + using _setup = setup();
168 mocks.importThreads.mockResolvedValue({
169 _tag: "Success",
170 value: { importedCount, skippedCount },
171 });
172 const onDone = vi.fn();
183 - await act(async () => root.render(<WelcomeWizard localAvailable onDone={onDone} />));
173 + await using _screen = await render(<WelcomeWizard localAvailable onDone={onDone} />);
174 await click("Continue");
175 await click("Continue");
176 await click("Import 1 project");
@@ -201,9 +191,10 @@ it.each([
191 );
192
193 it("keeps setup open when saving completion fails and preserves the import warning on retry", async () => {
194 + using _setup = setup();
195 mocks.complete.mockRejectedValueOnce(new Error("settings unavailable"));
196 const onDone = vi.fn();
206 - await act(async () => root.render(<WelcomeWizard localAvailable onDone={onDone} />));
197 + await using _screen = await render(<WelcomeWizard localAvailable onDone={onDone} />);
198 await click("Continue");
199 await click("Continue");
200 await click("Import 1 project");
@@ -223,8 +214,9 @@ it("keeps setup open when saving completion fails and preserves the import warni
214 });
215
216 it("requires explicit Close to complete local setup", async () => {
217 + using _setup = setup();
218 const onDone = vi.fn();
227 - await act(async () => root.render(<WelcomeWizard localAvailable onDone={onDone} />));
219 + await using _screen = await render(<WelcomeWizard localAvailable onDone={onDone} />);
220 await act(async () => {
221 document.activeElement?.dispatchEvent(
222 new KeyboardEvent("keydown", { key: "Escape", bubbles: true }),
apps/web/src/components/onboarding/WelcomeWizard.import.browser.test.tsx
+23 -24
@@ -9,11 +9,10 @@ import {
9 type AuthSessionState,
10 } from "@t3tools/contracts";
11 import { AsyncResult, Atom } from "effect/reactivity";
12 -import { act } from "react";
13 -import { createRoot, type Root } from "react-dom/client";
14 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
12 +import { expect, it, vi } from "vite-plus/test";
13
14 import "~/index.css";
15 +import { act, render } from "../../../test/render";
16
17 type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
18 type Project = { id: ProjectId; environmentId: EnvironmentId; workspaceRoot: string };
@@ -136,7 +135,6 @@ import { WelcomeWizard } from "./WelcomeWizard";
135 const primaryId = EnvironmentId.make("primary");
136 const remoteId = EnvironmentId.make("remote");
137 const permissionMessage = "This connection cannot import projects or thread history.";
139 -const roots: Root[] = [];
138
139 function session(scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState {
140 return {
@@ -217,12 +215,9 @@ function projectCheckboxes() {
215
216 async function mountImport(remote = false) {
217 state.selectedEnvironment = remote ? "remote" : "primary";
220 - const container = document.createElement("div");
221 - document.body.append(container);
222 - const root = createRoot(container);
223 - roots.push(root);
224 - await act(async () =>
225 - root.render(
218 + await using stack = new AsyncDisposableStack();
219 + const screen = stack.use(
220 + await render(
221 <RegistryContext.Provider value={appAtomRegistry}>
222 <WelcomeWizard localAvailable={!remote} onDone={state.onDone} />
223 </RegistryContext.Provider>,
@@ -231,9 +226,13 @@ async function mountImport(remote = false) {
226 await click("Continue");
227 await click("Continue");
228 expect(pageText()).toContain("Import your projects");
229 + stack.move();
230 + return screen;
231 }
232
236 -beforeEach(() => {
233 +// The mocked modules read `state`, so every test starts by replacing all of it.
234 +function setup() {
235 + state.sessions.clear();
236 for (const id of [primaryId, remoteId]) {
237 state.sessions.set(
238 id,
@@ -258,17 +257,12 @@ beforeEach(() => {
257 state.onDone.mockReset();
258 state.scan.mockReset();
259 state.refreshScan.mockReset();
261 -});
262 -
263 -afterEach(async () => {
264 - for (const root of roots.splice(0)) await act(async () => root.unmount());
265 - document.body.replaceChildren();
266 - state.sessions.clear();
267 -});
260 +}
261
262 it("keeps scanning, choosing and skipping available to a paired read-only environment", async () => {
263 + setup();
264 setGrant(remoteId, false);
271 - await mountImport(true);
265 + await using _screen = await mountImport(true);
266 expect(state.scan).toHaveBeenCalledWith(expect.objectContaining({ environmentId: remoteId }));
267 expect(pageText()).toContain("/projects/first");
268 expect(button("Import 2 projects").disabled).toBe(true);
@@ -281,8 +275,9 @@ it("keeps scanning, choosing and skipping available to a paired read-only enviro
275 });
276
277 it("waits for the selected grant and enables import when it arrives", async () => {
278 + setup();
279 appAtomRegistry.set(sessionAtom(primaryId), AsyncResult.initial());
285 - await mountImport();
280 + await using _screen = await mountImport();
281 expect(button("Import 2 projects").disabled).toBe(true);
282 await act(async () => setGrant(primaryId, true));
283 await click("Import 2 projects");
@@ -292,7 +287,8 @@ it("waits for the selected grant and enables import when it arrives", async () =
287 });
288
289 it("preserves selections and denies a click that lands as the paired environment's grant is revoked", async () => {
295 - await mountImport(true);
290 + setup();
291 + await using _screen = await mountImport(true);
292 await act(async () => projectCheckboxes()[1]!.click());
293 expect(projectCheckboxes()[1]!.getAttribute("aria-checked")).toBe("false");
294 const importButton = button("Import 1 project");
@@ -320,12 +316,13 @@ it("preserves selections and denies a click that lands as the paired environment
316 });
317
318 it("rechecks after project creation and can retry its history without recreating the project", async () => {
319 + setup();
320 const creation = deferred<void>();
321 state.createProject.mockImplementationOnce(async (input: CreateProjectInput) => {
322 await creation.promise;
323 return recordProject(input);
324 });
328 - await mountImport();
325 + await using _screen = await mountImport();
326 await click("Import 2 projects");
327 expect(state.createProject).toHaveBeenCalledOnce();
328 await act(async () => {
@@ -348,6 +345,7 @@ it("rechecks after project creation and can retry its history without recreating
345 it.each([false, true])(
346 "rechecks after history import before the next project write (existing: %s)",
347 async (existing) => {
348 + setup();
349 if (existing) {
350 const projectId = ProjectId.make("second-existing");
351 state.candidates[1] = { ...state.candidates[1]!, projectId };
@@ -359,7 +357,7 @@ it.each([false, true])(
357 state.importThreads.mockImplementationOnce(async () =>
358 AsyncResult.success(await imported.promise),
359 );
362 - await mountImport();
360 + await using _screen = await mountImport();
361 await click("Import 2 projects");
362 expect(state.createProject).toHaveBeenCalledOnce();
363 expect(state.importThreads).toHaveBeenCalledOnce();
@@ -382,12 +380,13 @@ it.each([false, true])(
380 );
381
382 it("completes accepted imports when permission is revoked after the final server write", async () => {
383 + setup();
384 state.candidates = state.candidates.slice(0, 1);
385 const imported = deferred<{ importedCount: number; skippedCount: number }>();
386 state.importThreads.mockImplementationOnce(async () =>
387 AsyncResult.success(await imported.promise),
388 );
390 - await mountImport();
389 + await using _screen = await mountImport();
390 await click("Import 1 project");
391 await act(async () => {
392 setGrant(primaryId, false);
apps/web/src/components/onboarding/WelcomeWizard.terminal.browser.test.tsx
+34 -32
@@ -1,3 +1,4 @@
1 +import { act, render, type Screen } from "../../../test/render";
2 import { RegistryContext } from "@effect/atom-react";
3 import {
4 BearerConnectionTarget,
@@ -21,9 +22,7 @@ import {
22 import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
23 import * as Cause from "effect/Cause";
24 import { AsyncResult, Atom } from "effect/reactivity";
24 -import { act } from "react";
25 -import { createRoot, type Root } from "react-dom/client";
26 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
25 +import { describe, expect, it, vi } from "vite-plus/test";
26
27 import "~/index.css";
28
@@ -206,7 +205,7 @@ function deferred<T>() {
205 });
206 return { promise, resolve };
207 }
209 -const roots: Root[] = [];
208 +
209 function pageText() {
210 return document.body.textContent ?? "";
211 }
@@ -225,23 +224,20 @@ async function click(label: string) {
224 function hasViewport() {
225 return document.querySelector("[data-terminal-viewport]") !== null;
226 }
228 -async function enterRemoteAgents() {
229 - const container = document.createElement("div");
230 - document.body.append(container);
231 - const root = createRoot(container);
232 - roots.push(root);
233 - await act(async () =>
234 - root.render(
235 - <RegistryContext.Provider value={appAtomRegistry}>
236 - <WelcomeWizard localAvailable onDone={state.done} />
237 - </RegistryContext.Provider>,
238 - ),
227 +async function enterRemoteAgents(screen: Screen) {
228 + await screen.rerender(
229 + <RegistryContext.Provider value={appAtomRegistry}>
230 + <WelcomeWizard localAvailable onDone={state.done} />
231 + </RegistryContext.Provider>,
232 );
233 await click("Continue");
234 expect(pageText()).toContain("Paired computer");
235 }
236
244 -beforeEach(() => {
237 +function setup() {
238 + state.sessions.clear();
239 + state.providers.clear();
240 + state.configs.clear();
241 for (const id of [primaryId, remoteId]) {
242 state.sessions.set(
243 id,
@@ -280,20 +276,14 @@ beforeEach(() => {
276 state.pair.mockReset().mockResolvedValue(AsyncResult.success(remoteId));
277 state.complete.mockReset().mockResolvedValue(undefined);
278 state.done.mockReset();
283 -});
284 -
285 -afterEach(async () => {
286 - for (const root of roots.splice(0)) await act(async () => root.unmount());
287 - document.body.replaceChildren();
288 - state.sessions.clear();
289 - state.providers.clear();
290 - state.configs.clear();
291 -});
279 +}
280
281 describe("welcome agent terminal setup", () => {
282 it("disables both setup actions for the paired read-only connection and preserves local completion", async () => {
283 + setup();
284 + await using screen = await render(null);
285 setAccess(remoteId, false);
296 - await enterRemoteAgents();
286 + await enterRemoteAgents(screen);
287 expect(button("Install").disabled).toBe(true);
288 expect(button("Sign in").disabled).toBe(true);
289 expect(pageText()).toContain("This connection cannot control terminals.");
@@ -311,8 +301,10 @@ describe("welcome agent terminal setup", () => {
301 });
302
303 it("rejects a retained install action after revocation and allows a terminal-only regrant", async () => {
304 + setup();
305 + await using screen = await render(null);
306 setAccess(primaryId, false);
315 - await enterRemoteAgents();
307 + await enterRemoteAgents(screen);
308 const install = button("Install");
309 // The click reaches the still-enabled button before React re-renders the revocation.
310 await act(async () => {
@@ -354,8 +346,10 @@ describe("welcome agent terminal setup", () => {
346 });
347
348 it("pretypes the selected provider's sign-in command without executing it", async () => {
349 + setup();
350 + await using screen = await render(null);
351 setAccess(primaryId, false);
358 - await enterRemoteAgents();
352 + await enterRemoteAgents(screen);
353 await click("Sign in");
354 expect(state.open).toHaveBeenCalledExactlyOnceWith({
355 environmentId: remoteId,
@@ -378,8 +372,10 @@ describe("welcome agent terminal setup", () => {
372 });
373
374 it("checks access when a queued retry starts and recovers after regrant", async () => {
375 + setup();
376 + await using screen = await render(null);
377 state.open.mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Could not open"))));
382 - await enterRemoteAgents();
378 + await enterRemoteAgents(screen);
379 await click("Install");
380 const closing = deferred<CommandResult>();
381 state.close.mockReturnValueOnce(closing.promise);
@@ -401,9 +397,11 @@ describe("welcome agent terminal setup", () => {
397 });
398
399 it("keeps an accepted terminal visible without pretyping when access is revoked during open", async () => {
400 + setup();
401 + await using screen = await render(null);
402 const opening = deferred<CommandResult>();
403 state.open.mockReturnValueOnce(opening.promise);
406 - await enterRemoteAgents();
404 + await enterRemoteAgents(screen);
405 await click("Install");
406 await act(async () => {
407 setAccess(remoteId, false);
@@ -426,9 +424,11 @@ describe("welcome agent terminal setup", () => {
424 });
425
426 it("settles accepted pretyping locally after revocation without closing the PTY", async () => {
427 + setup();
428 + await using screen = await render(null);
429 const writing = deferred<CommandResult>();
430 state.write.mockReturnValueOnce(writing.promise);
431 - await enterRemoteAgents();
431 + await enterRemoteAgents(screen);
432 await click("Sign in");
433 await act(async () => {
434 setAccess(remoteId, false);
@@ -447,9 +447,11 @@ describe("welcome agent terminal setup", () => {
447 });
448
449 it("rechecks the original environment when cleanup runs after pending pretyping", async () => {
450 + setup();
451 + await using screen = await render(null);
452 const writing = deferred<CommandResult>();
453 state.write.mockReturnValueOnce(writing.promise);
452 - await enterRemoteAgents();
454 + await enterRemoteAgents(screen);
455 await click("Install");
456 await click("Connect, step 1");
457 expect(state.close).not.toHaveBeenCalled();
apps/web/src/components/permissions/usePermissionStatus.browser.test.tsx
+44 -43
@@ -1,6 +1,6 @@
1 -import { act, useEffect } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
1 +import { act, render, fakeTimers } from "../../../test/render";
2 +import { useEffect } from "react";
3 +import { expect, it, vi } from "vite-plus/test";
4
5 import { usePermissionStatus } from "./usePermissionStatus";
6
@@ -15,49 +15,32 @@ function deferred<T>() {
15 return { promise, resolve };
16 }
17
18 -let root: Root | null;
19 -let current: ReturnType<typeof usePermissionStatus<keyof Status>>;
20 -let visibility: DocumentVisibilityState;
21 -
22 -function Probe() {
23 - const status = usePermissionStatus(check, { screen: false, accessibility: false });
24 - useEffect(() => {
25 - current = status;
26 - });
27 - return null;
18 +async function start(
19 + onStatus: (status: ReturnType<typeof usePermissionStatus<keyof Status>>) => void,
20 +) {
21 + function Probe() {
22 + const status = usePermissionStatus(check, { screen: false, accessibility: false });
23 + useEffect(() => onStatus(status));
24 + return null;
25 + }
26 + return render(<Probe />, { router: false });
27 }
29 -
30 -beforeEach(() => {
31 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
32 - vi.useFakeTimers();
33 - visibility = "visible";
34 - Object.defineProperty(document, "visibilityState", {
35 - configurable: true,
36 - get: () => visibility,
37 - });
28 +function setup() {
29 check.mockReset().mockResolvedValue({ screen: false, accessibility: false });
39 - root = null;
40 -});
41 -afterEach(async () => {
42 - await unmount();
43 - vi.useRealTimers();
44 - vi.unstubAllGlobals();
45 - Reflect.deleteProperty(document, "visibilityState");
46 -});
47 -
48 -async function start() {
49 - root = createRoot(document.createElement("div"));
50 - await act(async () => root!.render(<Probe />));
51 -}
52 -async function unmount() {
53 - const mounted = root;
54 - root = null;
55 - if (mounted) await act(async () => mounted.unmount());
30 }
31 const tick = (ms: number) => act(() => vi.advanceTimersByTimeAsync(ms));
32
33 it("unlocks Continue only for required grants and relocks on revocation", async () => {
60 - await start();
34 + setup();
35 + using _timers = fakeTimers();
36 + let current!: ReturnType<typeof usePermissionStatus<keyof Status>>;
37 + let visibility: DocumentVisibilityState = "visible";
38 + using _visibility = vi
39 + .spyOn(document, "visibilityState", "get")
40 + .mockImplementation(() => visibility);
41 + await using _screen = await start((status) => {
42 + current = status;
43 + });
44 expect(current.isReady(["screen"])).toBe(false);
45 check.mockResolvedValue({ screen: true, accessibility: false });
46 await tick(1500);
@@ -72,22 +55,40 @@ it("unlocks Continue only for required grants and relocks on revocation", async
55 });
56
57 it("does not overlap checks and discards completion after closing", async () => {
58 + setup();
59 + using _timers = fakeTimers();
60 + let current!: ReturnType<typeof usePermissionStatus<keyof Status>>;
61 + let visibility: DocumentVisibilityState = "visible";
62 + using _visibility = vi
63 + .spyOn(document, "visibilityState", "get")
64 + .mockImplementation(() => visibility);
65 const pending = deferred<Status>();
66 check.mockReturnValue(pending.promise);
77 - await start();
67 + await using screen = await start((status) => {
68 + current = status;
69 + });
70 await tick(4500);
71 window.dispatchEvent(new Event("focus"));
72 expect(check).toHaveBeenCalledTimes(1);
73 const last = current;
82 - await unmount();
74 + await screen.unmount();
75 await act(async () => pending.resolve({ screen: true, accessibility: true }));
76 expect(last.isReady(["screen"])).toBe(false);
77 expect(vi.getTimerCount()).toBe(0);
78 });
79
80 it("pauses in the background and blocks stale grants after a check failure", async () => {
81 + setup();
82 + using _timers = fakeTimers();
83 + let current!: ReturnType<typeof usePermissionStatus<keyof Status>>;
84 + let visibility: DocumentVisibilityState = "visible";
85 + using _visibility = vi
86 + .spyOn(document, "visibilityState", "get")
87 + .mockImplementation(() => visibility);
88 check.mockResolvedValue({ screen: true, accessibility: true });
90 - await start();
89 + await using _screen = await start((status) => {
90 + current = status;
91 + });
92 expect(current.isReady(["screen"])).toBe(true);
93 visibility = "hidden";
94 await tick(3000);
apps/web/src/components/preview/PreviewEmptyState.browser.test.tsx
+31 -43
@@ -1,7 +1,6 @@
1 +import { act, render, type Screen } from "../../../test/render";
2 import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 -import { act } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 +import { describe, expect, it, vi } from "vite-plus/test";
4
5 import type { PreviewableServer } from "./useDiscoveredLocalServers";
6
@@ -19,9 +18,6 @@ const threadRef = { environmentId, threadId: ThreadId.make("thread-1") };
18 const onOpenUrl = vi.fn();
19 const onRemoveRecent = vi.fn();
20
22 -let root: Root;
23 -let container: HTMLDivElement;
24 -
21 function server(port: number): PreviewableServer {
22 return {
23 host: "localhost",
@@ -35,39 +31,27 @@ function server(port: number): PreviewableServer {
31 } as PreviewableServer;
32 }
33
38 -beforeEach(() => {
39 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
34 +function setup() {
35 vi.clearAllMocks();
36 mocks.servers = [];
42 - container = document.createElement("div");
43 - document.body.append(container);
44 - root = createRoot(container);
45 -});
46 -
47 -afterEach(async () => {
48 - await act(async () => root.unmount());
49 - container.remove();
50 - vi.unstubAllGlobals();
51 -});
37 +}
38
53 -async function render(
39 +async function renderPreview(
40 recentEntries: Array<{ url: string; lastVisitedAt: number; title?: string }>,
41 ) {
56 - await act(async () =>
57 - root.render(
58 - <PreviewEmptyState
59 - threadRef={threadRef}
60 - environmentId={environmentId}
61 - recentEntries={recentEntries}
62 - onRemoveRecent={onRemoveRecent}
63 - onOpenUrl={onOpenUrl}
64 - />,
65 - ),
42 + return render(
43 + <PreviewEmptyState
44 + threadRef={threadRef}
45 + environmentId={environmentId}
46 + recentEntries={recentEntries}
47 + onRemoveRecent={onRemoveRecent}
48 + onOpenUrl={onOpenUrl}
49 + />,
50 );
51 }
52
69 -function button(name: string) {
70 - const match = [...container.querySelectorAll("button")].find(
53 +function button(screen: Screen, name: string) {
54 + const match = [...screen.container.querySelectorAll("button")].find(
55 (element) => element.getAttribute("aria-label") === name || element.textContent?.includes(name),
56 );
57 expect(match, `button ${name}`).toBeDefined();
@@ -76,38 +60,42 @@ function button(name: string) {
60
61 describe("PreviewEmptyState", () => {
62 it("lists a recent entry and a live server matching its host:port, and opens or forgets entries", async () => {
63 + setup();
64 mocks.servers = [server(5173)];
80 - await render([
65 + await using screen = await renderPreview([
66 { url: "https://myapp.test/admin#users", lastVisitedAt: Date.now(), title: "Admin" },
67 { url: "http://localhost:5173/", lastVisitedAt: Date.now(), title: "Recent Local" },
68 ]);
84 - const text = container.textContent;
69 + const text = screen.container.textContent;
70 expect(text).toContain("Recently used");
71 expect(text).toContain("Local servers");
72 expect(text).toContain("Recent Local");
73 expect(text).toContain("node");
74
90 - await act(async () => button("Admin").click());
75 + await act(async () => button(screen, "Admin").click());
76 expect(onOpenUrl).toHaveBeenCalledExactlyOnceWith("https://myapp.test/admin#users");
77
93 - await act(async () => button("Remove myapp.test/admin#users from history").click());
78 + await act(async () => button(screen, "Remove myapp.test/admin#users from history").click());
79 expect(onRemoveRecent).toHaveBeenCalledExactlyOnceWith("https://myapp.test/admin#users");
80 });
81
82 it("shows only the recents group when no servers are found", async () => {
98 - await render([{ url: "https://myapp.test/", lastVisitedAt: 0 }]);
99 - expect(container.textContent).toContain("Recently used");
100 - expect(container.textContent).not.toContain("Local servers");
83 + setup();
84 + await using screen = await renderPreview([{ url: "https://myapp.test/", lastVisitedAt: 0 }]);
85 + expect(screen.container.textContent).toContain("Recently used");
86 + expect(screen.container.textContent).not.toContain("Local servers");
87 });
88
89 it("keeps the original empty state when both groups are empty", async () => {
104 - await render([]);
105 - expect(container.textContent).toContain("No preview yet");
90 + setup();
91 + await using screen = await renderPreview([]);
92 + expect(screen.container.textContent).toContain("No preview yet");
93 });
94
95 it("shows an entry with an out-of-range lastVisitedAt instead of crashing", async () => {
109 - await render([{ url: "https://myapp.test/", lastVisitedAt: 1e20 }]);
110 - expect(container.textContent).toContain("myapp.test");
111 - button("Remove myapp.test from history");
96 + setup();
97 + await using screen = await renderPreview([{ url: "https://myapp.test/", lastVisitedAt: 1e20 }]);
98 + expect(screen.container.textContent).toContain("myapp.test");
99 + button(screen, "Remove myapp.test from history");
100 });
101 });
apps/web/src/components/preview/PreviewFaviconIcon.browser.test.tsx
+10 -30
@@ -1,36 +1,18 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
1 +import { act, render } from "../../../test/render";
2 +import { expect, it } from "vite-plus/test";
3
4 import { FaviconImage } from "./PreviewFaviconIcon";
5
7 -const GIF = "data:image/gif;base64,R0lGODlhAQABAAAAACw=";
6 +const GIF = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
7 const captured = `${GIF}#captured`;
8 const remote = `${GIF}#remote`;
9
11 -let root: Root;
12 -let container: HTMLDivElement;
13 -
14 -beforeEach(() => {
15 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
16 - container = document.createElement("div");
17 - document.body.append(container);
18 - root = createRoot(container);
19 -});
20 -
21 -afterEach(async () => {
22 - await act(async () => root.unmount());
23 - container.remove();
24 - vi.unstubAllGlobals();
25 -});
26 -
27 -const image = () => container.querySelector("img");
28 -const failImage = () => act(async () => image()!.dispatchEvent(new Event("error")));
29 -
10 it("falls through failed favicon sources and retries when the source list changes", async () => {
31 - await act(async () =>
32 - root.render(<FaviconImage sources={[captured, remote]} fallback={<span>fallback</span>} />),
11 + await using screen = await render(
12 + <FaviconImage sources={[captured, remote]} fallback={<span>fallback</span>} />,
13 );
14 + const image = () => screen.container.querySelector("img");
15 + const failImage = () => act(async () => image()!.dispatchEvent(new Event("error")));
16 expect(image()?.getAttribute("src")).toBe(captured);
17
18 await failImage();
@@ -38,12 +20,10 @@ it("falls through failed favicon sources and retries when the source list change
20
21 await failImage();
22 expect(image()).toBeNull();
41 - expect(container.textContent).toBe("fallback");
23 + expect(screen.container.textContent).toBe("fallback");
24
43 - await act(async () =>
44 - root.render(
45 - <FaviconImage sources={[captured, `${GIF}#new-icon`]} fallback={<span>fallback</span>} />,
46 - ),
25 + await screen.rerender(
26 + <FaviconImage sources={[captured, `${GIF}#new-icon`]} fallback={<span>fallback</span>} />,
27 );
28 expect(image()?.getAttribute("src")).toBe(captured);
29 });
apps/web/src/components/preview/PreviewPanelShell.a11y.browser.test.tsx
+64 -74
@@ -1,70 +1,52 @@
1 +import { act, render, type Screen } from "../../../test/render";
2 import { Dialog } from "@base-ui/react/dialog";
2 -import { act } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 +import { describe, expect, it } from "vite-plus/test";
4 import { userEvent } from "vite-plus/test/browser";
5
6 import { PanelLayoutControls } from "../chat/PanelLayoutControls";
7 import { PreviewPanelShell, type PreviewPanelMode } from "./PreviewPanelShell";
8
10 -let root: Root;
11 -let container: HTMLDivElement;
12 -
13 -beforeEach(() => {
14 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
15 - container = document.createElement("div");
16 - document.body.append(container);
17 - root = createRoot(container);
18 -});
19 -
20 -afterEach(async () => {
21 - await act(async () => root.unmount());
22 - container.remove();
23 - vi.unstubAllGlobals();
24 -});
25 -
9 async function renderPanel(
10 + screen: Screen,
11 open: boolean | undefined,
12 mode: PreviewPanelMode = "inline",
13 present = true,
14 ) {
31 - await act(async () => {
32 - root.render(
33 - <Dialog.Root open>
34 - <Dialog.Portal>
35 - <Dialog.Popup aria-label="Workspace" finalFocus={false}>
36 - {present ? (
37 - <PreviewPanelShell mode={mode} {...(open === undefined ? {} : { open })}>
38 - <input aria-label="Preview URL" />
39 - <button type="button">Reload preview</button>
40 - </PreviewPanelShell>
41 - ) : null}
42 - <button type="button" data-testid="outside">
43 - Send message
44 - </button>
45 - <div key={present ? "root-controls" : "header-controls"}>
46 - <PanelLayoutControls
47 - showTerminalControl={false}
48 - showThreadPanelControl={false}
49 - terminalAvailable={false}
50 - terminalOpen={false}
51 - terminalShortcutLabel={null}
52 - threadPanelOpen={false}
53 - threadPanelPresentation="inline"
54 - threadPanelShortcutLabel={null}
55 - rightPanelAvailable
56 - rightPanelOpen={open ?? true}
57 - rightPanelShortcutLabel={null}
58 - onToggleTerminal={() => {}}
59 - onToggleThreadPanel={() => {}}
60 - onToggleRightPanel={() => {}}
61 - />
62 - </div>
63 - </Dialog.Popup>
64 - </Dialog.Portal>
65 - </Dialog.Root>,
66 - );
67 - });
15 + await screen.rerender(
16 + <Dialog.Root open>
17 + <Dialog.Portal>
18 + <Dialog.Popup aria-label="Workspace" finalFocus={false}>
19 + {present ? (
20 + <PreviewPanelShell mode={mode} {...(open === undefined ? {} : { open })}>
21 + <input aria-label="Preview URL" />
22 + <button type="button">Reload preview</button>
23 + </PreviewPanelShell>
24 + ) : null}
25 + <button type="button" data-testid="outside">
26 + Send message
27 + </button>
28 + <div key={present ? "root-controls" : "header-controls"}>
29 + <PanelLayoutControls
30 + showTerminalControl={false}
31 + showThreadPanelControl={false}
32 + terminalAvailable={false}
33 + terminalOpen={false}
34 + terminalShortcutLabel={null}
35 + threadPanelOpen={false}
36 + threadPanelPresentation="inline"
37 + threadPanelShortcutLabel={null}
38 + rightPanelAvailable
39 + rightPanelOpen={open ?? true}
40 + rightPanelShortcutLabel={null}
41 + onToggleTerminal={() => {}}
42 + onToggleThreadPanel={() => {}}
43 + onToggleRightPanel={() => {}}
44 + />
45 + </div>
46 + </Dialog.Popup>
47 + </Dialog.Portal>
48 + </Dialog.Root>,
49 + );
50 await act(nextFrame);
51 }
52
@@ -83,89 +65,97 @@ async function enterFocusScope() {
65
66 describe("right panel keyboard access", () => {
67 it("skips collapsed controls and restores access after reopening", async () => {
86 - await renderPanel(false);
68 + await using screen = await render(null);
69 + await renderPanel(screen, false);
70 const outside = document.querySelector<HTMLElement>('[data-testid="outside"]')!;
71 expect(document.activeElement).toBe(outside);
72 await enterFocusScope();
73 expect(document.activeElement).toBe(outside);
74
92 - await renderPanel(true);
75 + await renderPanel(screen, true);
76 await enterFocusScope();
77 expect(document.activeElement).toBe(document.querySelector('[aria-label="Preview URL"]'));
78
96 - await renderPanel(false);
79 + await renderPanel(screen, false);
80 await enterFocusScope();
81 expect(document.activeElement).toBe(outside);
82 });
83
84 it("returns focus to the right-panel toggle when a focused panel closes", async () => {
102 - await renderPanel(true);
85 + await using screen = await render(null);
86 + await renderPanel(screen, true);
87 const input = document.querySelector<HTMLInputElement>('[aria-label="Preview URL"]')!;
88 await act(async () => input.focus());
105 - await renderPanel(false);
89 + await renderPanel(screen, false);
90 expect(document.activeElement).toBe(
91 document.querySelector('[aria-label="Toggle right panel"]'),
92 );
109 - await renderPanel(true);
93 + await renderPanel(screen, true);
94 await enterFocusScope();
95 expect(document.activeElement).toBe(input);
96 });
97
98 it("retains focus after the closing animation relocates the toggle", async () => {
115 - await renderPanel(true);
99 + await using screen = await render(null);
100 + await renderPanel(screen, true);
101 await act(async () => {
102 document.querySelector<HTMLInputElement>('[aria-label="Preview URL"]')!.focus();
103 });
119 - await renderPanel(false);
104 + await renderPanel(screen, false);
105 const closingToggle = document.querySelector('[aria-label="Toggle right panel"]');
106 expect(document.activeElement).toBe(closingToggle);
122 - await renderPanel(false, "inline", false);
107 + await renderPanel(screen, false, "inline", false);
108 const settledToggle = document.querySelector('[aria-label="Toggle right panel"]');
109 expect(settledToggle).not.toBe(closingToggle);
110 expect(document.activeElement).toBe(settledToggle);
111 });
112
113 it("returns focus when the panel closes without an animation", async () => {
129 - await renderPanel(true);
114 + await using screen = await render(null);
115 + await renderPanel(screen, true);
116 await act(async () => {
117 document.querySelector<HTMLInputElement>('[aria-label="Preview URL"]')!.focus();
118 });
133 - await renderPanel(false, "inline", false);
119 + await renderPanel(screen, false, "inline", false);
120 expect(document.activeElement).toBe(
121 document.querySelector('[aria-label="Toggle right panel"]'),
122 );
123 });
124
125 it("preserves focus moved outside while the closing animation settles", async () => {
140 - await renderPanel(true);
126 + await using screen = await render(null);
127 + await renderPanel(screen, true);
128 await act(async () => {
129 document.querySelector<HTMLInputElement>('[aria-label="Preview URL"]')!.focus();
130 });
144 - await renderPanel(false);
131 + await renderPanel(screen, false);
132 const outside = document.querySelector<HTMLButtonElement>('[data-testid="outside"]')!;
133 await act(async () => outside.focus());
147 - await renderPanel(false, "inline", false);
134 + await renderPanel(screen, false, "inline", false);
135 expect(document.activeElement).toBe(outside);
136 });
137
138 it("preserves focus outside the panel when it closes", async () => {
152 - await renderPanel(true);
139 + await using screen = await render(null);
140 + await renderPanel(screen, true);
141 const outside = document.querySelector<HTMLButtonElement>('[data-testid="outside"]')!;
142 await act(async () => outside.focus());
155 - await renderPanel(false);
143 + await renderPanel(screen, false);
144 expect(document.activeElement).toBe(outside);
145 });
146
147 it.each(["sheet", "sidebar", "embedded"] as const)(
148 "keeps %s controls reachable when the inline open flag is false",
149 async (mode) => {
162 - await renderPanel(false, mode);
150 + await using screen = await render(null);
151 + await renderPanel(screen, false, mode);
152 expect(document.activeElement).toBe(document.querySelector('[aria-label="Preview URL"]'));
153 },
154 );
155
156 it("keeps non-collapsible inline controls reachable", async () => {
168 - await renderPanel(undefined);
157 + await using screen = await render(null);
158 + await renderPanel(screen, undefined);
159 expect(document.activeElement).toBe(document.querySelector('[aria-label="Preview URL"]'));
160 });
161 });
apps/web/src/components/preview/PreviewView.browser.test.tsx
+55 -60
@@ -7,12 +7,12 @@ import {
7 FILL_PREVIEW_VIEWPORT,
8 ThreadId,
9 } from "@t3tools/contracts";
10 -import { act, Profiler, type ComponentProps, type ReactNode } from "react";
11 -import { createRoot, type Root } from "react-dom/client";
12 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
10 +import { Profiler, type ComponentProps } from "react";
11 +import { describe, expect, it, vi } from "vite-plus/test";
12 import { page, userEvent } from "vite-plus/test/browser";
13
14 import "~/index.css";
15 +import { act, fakeTimers, render, stubGlobal } from "../../../test/render";
16
17 import type { PreviewableServer } from "./useDiscoveredLocalServers";
18
@@ -170,13 +170,6 @@ const TEST_THREAD_REF = {
170 } as const;
171 const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
172
173 -const roots: Root[] = [];
174 -let root: Root;
175 -
176 -async function render(node: ReactNode) {
177 - await act(async () => root.render(node));
178 -}
179 -
173 function view(onSendAnnotation?: ComponentProps<typeof PreviewView>["onSendAnnotation"]) {
174 return (
175 <PreviewView
@@ -214,41 +207,32 @@ function hasCursor() {
207 return document.querySelector("svg.lucide-mouse-pointer2") !== null;
208 }
209
217 -describe("PreviewView", () => {
218 - beforeEach(() => {
219 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
220 - vi.clearAllMocks();
221 - mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
222 - mocks.setAnnotationSendEnabled.mockReset().mockResolvedValue(undefined);
223 - mocks.pickElement.mockReset();
224 - mocks.pictureInPicture = false;
225 - mocks.showEmptyState = false;
226 - mocks.loading = false;
227 - mocks.nativeServerTab = false;
228 - mocks.serverEpoch = null;
229 - mocks.servers = [];
230 - mocks.recordingTabIds = new Set();
231 - mocks.recordingRuntimeTabId = null;
232 - useComposerDraftStore.setState({
233 - addPreviewAnnotation: mocks.addPreviewAnnotation,
234 - addImage: mocks.addImage,
235 - });
236 - usePreviewMiniPlayerStore.setState({ byThreadKey: {} });
237 - useBrowserPointerStore.setState({ byTabId: {} });
238 - const container = document.createElement("div");
239 - document.body.append(container);
240 - root = createRoot(container);
241 - roots.push(root);
242 - });
243 -
244 - afterEach(async () => {
245 - for (const each of roots.splice(0)) await act(async () => each.unmount());
246 - document.body.replaceChildren();
247 - vi.useRealTimers();
248 - vi.unstubAllGlobals();
210 +// The mocked modules and stores are shared by the whole file, so every test starts by
211 +// resetting them.
212 +function setup() {
213 + vi.clearAllMocks();
214 + mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
215 + mocks.setAnnotationSendEnabled.mockReset().mockResolvedValue(undefined);
216 + mocks.pickElement.mockReset();
217 + mocks.pictureInPicture = false;
218 + mocks.showEmptyState = false;
219 + mocks.loading = false;
220 + mocks.nativeServerTab = false;
221 + mocks.serverEpoch = null;
222 + mocks.servers = [];
223 + mocks.recordingTabIds = new Set();
224 + mocks.recordingRuntimeTabId = null;
225 + useComposerDraftStore.setState({
226 + addPreviewAnnotation: mocks.addPreviewAnnotation,
227 + addImage: mocks.addImage,
228 });
229 + usePreviewMiniPlayerStore.setState({ byThreadKey: {} });
230 + useBrowserPointerStore.setState({ byTabId: {} });
231 +}
232
233 +describe("PreviewView", () => {
234 it("shows the cursor in a replacement browser while the old instance still records", async () => {
235 + setup();
236 mocks.recordingTabIds.add(TEST_RUNTIME_TAB_ID);
237 mocks.recordingRuntimeTabId = TEST_RUNTIME_TAB_ID;
238 const replacementTabId = previewRuntimeTabId(TEST_THREAD_REF, "replacement-server", "tab-1");
@@ -260,10 +244,10 @@ describe("PreviewView", () => {
244 ]),
245 ),
246 });
263 - await render(view());
247 + await using screen = await render(view());
248 expect(hasCursor()).toBe(false);
249 mocks.serverEpoch = "replacement-server";
266 - await render(view());
250 + await screen.rerender(view());
251 expect(hasCursor()).toBe(true);
252 expect(mocks.recordingTabIds.has(TEST_RUNTIME_TAB_ID)).toBe(true);
253 });
@@ -271,15 +255,16 @@ describe("PreviewView", () => {
255 it.each([false, true])(
256 "aligns the cursor and responsive viewport after host zoom changes (native server tab: %s)",
257 async (nativeServerTab) => {
258 + setup();
259 mocks.nativeServerTab = nativeServerTab;
260 let windowZoom = 1;
276 - vi.stubGlobal("desktopBridge", {
261 + using _bridge = stubGlobal("desktopBridge", {
262 getWindowZoomFactor: () => windowZoom,
263 getLocalEnvironmentBootstraps: () => [],
264 });
265 const commit = vi.mocked(commitBrowserViewportChange).mockResolvedValueOnce(undefined);
266 try {
282 - await render(view());
267 + await using _screen = await render(view());
268 await act(() => {
269 const surfaces = useBrowserSurfaceStore.getState();
270 const slot = document.querySelector<HTMLElement>("[data-browser-surface-slot]")!;
@@ -330,10 +315,11 @@ describe("PreviewView", () => {
315 );
316
317 it("does not rerender while loading time passes", async () => {
333 - vi.useFakeTimers();
318 + setup();
319 + using _timers = fakeTimers();
320 mocks.loading = true;
321 const onRender = vi.fn();
336 - await render(
322 + await using _screen = await render(
323 <Profiler id="preview" onRender={onRender}>
324 {view()}
325 </Profiler>,
@@ -352,7 +338,8 @@ describe("PreviewView", () => {
338 ])(
339 "preserves a direct localhost URL %s in a WSL environment and records it",
340 async (submitted, expected) => {
355 - await render(view());
341 + setup();
342 + await using _screen = await render(view());
343 await submitAddress(submitted);
344 await vi.waitFor(() =>
345 expect(mocks.navigate).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID, expected),
@@ -363,6 +350,7 @@ describe("PreviewView", () => {
350 );
351
352 it("maps an empty-state localhost server onto the WSL host", async () => {
353 + setup();
354 mocks.showEmptyState = true;
355 mocks.servers = [
356 {
@@ -376,7 +364,7 @@ describe("PreviewView", () => {
364 source: "scanner",
365 } as unknown as PreviewableServer,
366 ];
379 - await render(view());
367 + await using _screen = await render(view());
368 await userEvent.click(page.getByRole("button", { name: /vite/ }));
369
370 await vi.waitFor(() =>
@@ -399,7 +387,8 @@ describe("PreviewView", () => {
387 });
388
389 it("opens and closes a thread-scoped floating preview for the active tab", async () => {
402 - await render(view());
390 + setup();
391 + await using _screen = await render(view());
392 await userEvent.click(page.getByRole("button", { name: "Float preview over chat" }));
393 expect(usePreviewMiniPlayerStore.getState().byThreadKey).toMatchObject({
394 "environment-1:thread-1": { source: { kind: "browser", tabId: "tab-1" } },
@@ -411,7 +400,8 @@ describe("PreviewView", () => {
400 });
401
402 it("keeps the native preview window as a secondary menu action", async () => {
414 - await render(view());
403 + setup();
404 + await using screen = await render(view());
405 await userEvent.click(page.getByRole("button", { name: "Preview menu" }));
406 await userEvent.click(page.getByRole("menuitem", { name: "Open separate preview window" }));
407 await vi.waitFor(() =>
@@ -420,7 +410,7 @@ describe("PreviewView", () => {
410 await vi.waitFor(() => expect(document.querySelector('[role="menu"]')).toBeNull());
411
412 mocks.pictureInPicture = true;
423 - await render(view());
413 + await screen.rerender(view());
414 await userEvent.click(page.getByRole("button", { name: "Preview menu" }));
415 await userEvent.click(page.getByRole("menuitem", { name: "Close separate preview window" }));
416 await vi.waitFor(() =>
@@ -429,10 +419,11 @@ describe("PreviewView", () => {
419 });
420
421 it("forwards Cmd/Ctrl+Enter annotations to the composer send path", async () => {
422 + setup();
423 const picked = annotation("annotation-1");
424 const onSendAnnotation = vi.fn();
425 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
435 - await render(view(onSendAnnotation));
426 + await using _screen = await render(view(onSendAnnotation));
427 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
428
429 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
@@ -440,6 +431,7 @@ describe("PreviewView", () => {
431 });
432
433 it("retains the annotation locally when its own environment loses access during capture", async () => {
434 + setup();
435 const picked = annotation("annotation-revoked");
436 const onSendAnnotation = vi.fn();
437 let submitPick: (() => void) | undefined;
@@ -449,7 +441,7 @@ describe("PreviewView", () => {
441 submitPick = () => resolve({ annotation: picked, submission: "send" });
442 }),
443 );
452 - await render(view(onSendAnnotation));
444 + await using screen = await render(view(onSendAnnotation));
445 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
446 await vi.waitFor(() => expect(submitPick).toBeDefined());
447 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
@@ -457,7 +449,7 @@ describe("PreviewView", () => {
449 mocks.readEnvironmentScope.mockImplementation(
450 (environmentId?: unknown) => environmentId !== TEST_THREAD_REF.environmentId,
451 );
460 - await render(view(onSendAnnotation));
452 + await screen.rerender(view(onSendAnnotation));
453 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, false);
454 await act(async () => submitPick!());
455 await vi.waitFor(() =>
@@ -467,13 +459,14 @@ describe("PreviewView", () => {
459
460 mocks.readEnvironmentScope.mockReturnValue(true);
461 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
470 - await render(view(onSendAnnotation));
462 + await screen.rerender(view(onSendAnnotation));
463 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
464 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
465 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
466 });
467
468 it("does not reopen a cancelled picker after the permission update finishes", async () => {
469 + setup();
470 let finishUpdate: (() => void) | undefined;
471 mocks.setAnnotationSendEnabled.mockImplementationOnce(
472 () =>
@@ -481,7 +474,7 @@ describe("PreviewView", () => {
474 finishUpdate = resolve;
475 }),
476 );
484 - await render(view());
477 + await using _screen = await render(view());
478 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
479 await vi.waitFor(() => expect(finishUpdate).toBeDefined());
480 expect(mocks.pickElement).not.toHaveBeenCalled();
@@ -493,6 +486,7 @@ describe("PreviewView", () => {
486 });
487
488 it("warns when main dropped the crop before handing over the pick", async () => {
489 + setup();
490 const picked = annotation("annotation-3");
491 const onSendAnnotation = vi.fn();
492 mocks.pickElement.mockResolvedValue({
@@ -500,7 +494,7 @@ describe("PreviewView", () => {
494 submission: "send",
495 screenshotFailed: true,
496 });
503 - await render(view(onSendAnnotation));
497 + await using _screen = await render(view(onSendAnnotation));
498 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
499
500 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
@@ -508,6 +502,7 @@ describe("PreviewView", () => {
502 });
503
504 it("still sends annotation text when the picked element's crop is malformed", async () => {
505 + setup();
506 const picked = annotation("annotation-2", {
507 dataUrl: "data:image/png;base64,%%%",
508 width: 10,
@@ -516,7 +511,7 @@ describe("PreviewView", () => {
511 });
512 const onSendAnnotation = vi.fn();
513 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
519 - await render(view(onSendAnnotation));
514 + await using _screen = await render(view(onSendAnnotation));
515 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
516
517 const sent = { ...picked, screenshot: null };
apps/web/src/components/projectScriptEditor.browser.test.tsx
+35 -38
@@ -1,9 +1,9 @@
1 +import { act, render, type Screen } from "../../test/render";
2 import { EnvironmentId } from "@t3tools/contracts";
3 import * as Cause from "effect/Cause";
4 import { AsyncResult } from "effect/reactivity";
4 -import { act, StrictMode } from "react";
5 -import { createRoot, type Root } from "react-dom/client";
6 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5 +import { StrictMode } from "react";
6 +import { describe, expect, it, vi } from "vite-plus/test";
7
8 vi.mock(import("~/state/session"), async (original) => ({
9 ...(await original()),
@@ -21,8 +21,6 @@ import {
21 const onSubmit = vi.fn<Parameters<typeof ProjectScriptEditorDialog>[0]["onSubmit"]>();
22 const onClose = vi.fn();
23 const onDelete = vi.fn();
24 -let root: Root;
25 -let mounted: boolean;
24
25 function request(name: string, error?: string): ProjectScriptEditorRequest {
26 return {
@@ -32,20 +30,18 @@ function request(name: string, error?: string): ProjectScriptEditorRequest {
30 };
31 }
32
35 -const open = (nextRequest: ProjectScriptEditorRequest) =>
36 - act(async () =>
37 - root.render(
38 - <StrictMode>
39 - <ProjectScriptEditorDialog
40 - environmentId={EnvironmentId.make("test")}
41 - request={nextRequest}
42 - scripts={[]}
43 - onSubmit={onSubmit}
44 - onClose={onClose}
45 - onDelete={onDelete}
46 - />
47 - </StrictMode>,
48 - ),
33 +const open = (screen: Screen, nextRequest: ProjectScriptEditorRequest) =>
34 + screen.rerender(
35 + <StrictMode>
36 + <ProjectScriptEditorDialog
37 + environmentId={EnvironmentId.make("test")}
38 + request={nextRequest}
39 + scripts={[]}
40 + onSubmit={onSubmit}
41 + onClose={onClose}
42 + onDelete={onDelete}
43 + />
44 + </StrictMode>,
45 );
46
47 const submit = () => document.querySelector("form")!.requestSubmit();
@@ -65,25 +61,19 @@ function deferredSave() {
61 return { promise, resolve, reject };
62 }
63
68 -beforeEach(() => {
69 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
64 +function setup() {
65 onSubmit.mockReset();
66 onClose.mockReset();
67 onDelete.mockReset();
73 - root = createRoot(document.createElement("div"));
74 - mounted = true;
75 -});
76 -
77 -afterEach(async () => {
78 - if (mounted) await act(async () => root.unmount());
79 - vi.unstubAllGlobals();
80 -});
68 +}
69
70 describe("project action editor save lifecycle", () => {
71 it("blocks repeated submits and edits until the current save completes", async () => {
72 + setup();
73 + await using screen = await render(null);
74 const save = deferredSave();
75 onSubmit.mockReturnValue(save.promise);
86 - await open(request("build"));
76 + await open(screen, request("build"));
77
78 await act(async () => {
79 submit();
@@ -101,13 +91,15 @@ describe("project action editor save lifecycle", () => {
91 });
92
93 it("does not close a replacement request or release its in-flight save", async () => {
94 + setup();
95 + await using screen = await render(null);
96 const first = deferredSave();
97 const second = deferredSave();
98 onSubmit.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
107 - await open(request("build"));
99 + await open(screen, request("build"));
100 await act(async () => submit());
101
110 - await open(request("test"));
102 + await open(screen, request("test"));
103 expect(saveButton().disabled).toBe(false);
104 expect(document.querySelector<HTMLInputElement>("#script-name")!.value).toBe("test");
105 await act(async () => submit());
@@ -124,12 +116,14 @@ describe("project action editor save lifecycle", () => {
116 it.each(["failure", "rejection"] as const)(
117 "ignores a stale %s after the request changes",
118 async (outcome) => {
119 + setup();
120 + await using screen = await render(null);
121 const save = deferredSave();
122 onSubmit.mockReturnValue(save.promise);
129 - await open(request("build"));
123 + await open(screen, request("build"));
124 await act(async () => submit());
125
132 - await open(request("test", "New request error"));
126 + await open(screen, request("test", "New request error"));
127 await act(async () => {
128 if (outcome === "failure")
129 save.resolve(AsyncResult.failure(Cause.fail(new Error("Old save error"))));
@@ -144,9 +138,11 @@ describe("project action editor save lifecycle", () => {
138 );
139
140 it("shows a current save error and allows retry", async () => {
141 + setup();
142 + await using screen = await render(null);
143 onSubmit.mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Save failed"))));
144 onSubmit.mockResolvedValueOnce(AsyncResult.success(undefined));
149 - await open(request("build"));
145 + await open(screen, request("build"));
146
147 await act(async () => saveButton().click());
148 expect(messages()).toContain("Save failed");
@@ -160,16 +156,17 @@ describe("project action editor save lifecycle", () => {
156 });
157
158 it.each(["cancel", "unmount"] as const)("ignores save completion after %s", async (exit) => {
159 + setup();
160 + await using screen = await render(null);
161 const save = deferredSave();
162 onSubmit.mockReturnValue(save.promise);
165 - await open(request("build"));
163 + await open(screen, request("build"));
164 await act(async () => submit());
165
166 await act(async () => {
167 if (exit === "cancel") button("Cancel").click();
168 else {
171 - root.unmount();
172 - mounted = false;
169 + await screen.unmount();
170 }
171 });
172 onClose.mockClear();
apps/web/src/components/projectScriptEditor.permissions.browser.test.tsx
+50 -37
@@ -1,3 +1,4 @@
1 +import { act, render, type Screen } from "../../test/render";
2 import {
3 AuthOrchestrationOperateScope,
4 AuthSettingsWriteScope,
@@ -6,9 +7,7 @@ import {
7 } from "@t3tools/contracts";
8 import * as Cause from "effect/Cause";
9 import { AsyncResult } from "effect/reactivity";
9 -import { act } from "react";
10 -import { createRoot, type Root } from "react-dom/client";
11 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
10 +import { describe, expect, it, vi } from "vite-plus/test";
11 import { userEvent } from "vite-plus/test/browser";
12
13 const permissions = vi.hoisted(() => ({
@@ -61,22 +60,14 @@ const request: ProjectScriptEditorRequest = {
60 };
61
62 describe("ProjectScriptEditorDialog", () => {
64 - let root: Root;
65 -
66 - beforeEach(() => {
67 - root = createRoot(document.createElement("div"));
63 + function setup() {
64 permissions.canWriteSettings = false;
65 permissions.canEditProject = true;
70 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
71 - });
72 -
73 - afterEach(async () => {
74 - await act(async () => root.unmount());
75 - vi.restoreAllMocks();
76 - vi.unstubAllGlobals();
77 - });
66 + permissions.listeners.clear();
67 + }
68
69 async function openEditor(
70 + screen: Screen,
71 onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined)),
72 editorRequest = request,
73 actions = { onDelete: vi.fn(), onClose: vi.fn() },
@@ -84,18 +75,16 @@ describe("ProjectScriptEditorDialog", () => {
75 | typeof AuthOrchestrationOperateScope
76 | typeof AuthSettingsWriteScope = AuthOrchestrationOperateScope,
77 ) {
87 - await act(async () =>
88 - root.render(
89 - <ProjectScriptEditorDialog
90 - environmentId={EnvironmentId.make("script-editor-test")}
91 - editScope={editScope}
92 - request={editorRequest}
93 - scripts={[]}
94 - onSubmit={onSubmit}
95 - onDelete={actions.onDelete}
96 - onClose={actions.onClose}
97 - />,
98 - ),
78 + await screen.rerender(
79 + <ProjectScriptEditorDialog
80 + environmentId={EnvironmentId.make("script-editor-test")}
81 + editScope={editScope}
82 + request={editorRequest}
83 + scripts={[]}
84 + onSubmit={onSubmit}
85 + onDelete={actions.onDelete}
86 + onClose={actions.onClose}
87 + />,
88 );
89 }
90
@@ -119,10 +108,18 @@ describe("ProjectScriptEditorDialog", () => {
108 it.each([null, "test"])(
109 "saves a settings action without task access (id: %s)",
110 async (scriptId) => {
111 + setup();
112 + await using screen = await render(null);
113 permissions.canEditProject = false;
114 permissions.canWriteSettings = true;
115 const onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
125 - await openEditor(onSubmit, { ...request, scriptId }, undefined, AuthSettingsWriteScope);
116 + await openEditor(
117 + screen,
118 + onSubmit,
119 + { ...request, scriptId },
120 + undefined,
121 + AuthSettingsWriteScope,
122 + );
123 permissions.canWriteSettings = false;
124 await submit();
125 expect(onSubmit).not.toHaveBeenCalled();
@@ -136,10 +133,12 @@ describe("ProjectScriptEditorDialog", () => {
133 );
134
135 it("rechecks settings access before deleting a settings action", async () => {
136 + setup();
137 + await using screen = await render(null);
138 permissions.canEditProject = false;
139 permissions.canWriteSettings = true;
140 const actions = { onDelete: vi.fn(), onClose: vi.fn() };
142 - await openEditor(undefined, request, actions, AuthSettingsWriteScope);
141 + await openEditor(screen, undefined, request, actions, AuthSettingsWriteScope);
142 await click("Delete");
143 permissions.canWriteSettings = false;
144 await click("Delete action");
@@ -153,13 +152,15 @@ describe("ProjectScriptEditorDialog", () => {
152 });
153
154 it("clears an old shortcut when adding an action with no shortcut", async () => {
155 + setup();
156 + await using screen = await render(null);
157 permissions.canWriteSettings = true;
158 let persistedKeybinding: string | null = "mod+k";
159 const onSubmit = vi.fn(async (_id: string | null, input: NewProjectScriptInput) => {
160 if (input.keybinding !== undefined) persistedKeybinding = input.keybinding;
161 return AsyncResult.success(undefined);
162 });
162 - await openEditor(onSubmit, {
163 + await openEditor(screen, onSubmit, {
164 scriptId: null,
165 initial: { ...request.initial, keybinding: null },
166 });
@@ -173,6 +174,8 @@ describe("ProjectScriptEditorDialog", () => {
174 it.each([false, true])(
175 "re-adds a deleted action while preserving its shortcut without settings access (revoked: %s)",
176 async (revokeBeforeSubmit) => {
177 + setup();
178 + await using screen = await render(null);
179 permissions.canWriteSettings = revokeBeforeSubmit;
180 const persisted = { name: null as string | null, keybinding: "mod+k" as string | null };
181 const onSubmit = vi.fn(async (_id: string | null, input: NewProjectScriptInput) => {
@@ -185,7 +188,7 @@ describe("ProjectScriptEditorDialog", () => {
188 if (input.keybinding !== undefined) persisted.keybinding = input.keybinding;
189 return AsyncResult.success(undefined);
190 });
188 - await openEditor(onSubmit, {
191 + await openEditor(screen, onSubmit, {
192 scriptId: null,
193 initial: { ...request.initial, keybinding: null },
194 });
@@ -201,15 +204,17 @@ describe("ProjectScriptEditorDialog", () => {
204 it.each([false, true])(
205 "requires settings access to override a retained shortcut when re-adding an action (revoked: %s)",
206 async (revokeBeforeSubmit) => {
207 + setup();
208 + await using screen = await render(null);
209 permissions.canWriteSettings = true;
205 - vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
210 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
211 const persisted = { name: null as string | null, keybinding: "mod+k" as string | null };
212 const onSubmit = vi.fn(async (_id: string | null, input: NewProjectScriptInput) => {
213 persisted.name = input.name;
214 if (input.keybinding !== undefined) persisted.keybinding = input.keybinding;
215 return AsyncResult.success(undefined);
216 });
212 - await openEditor(onSubmit, {
217 + await openEditor(screen, onSubmit, {
218 scriptId: null,
219 initial: { ...request.initial, keybinding: null },
220 });
@@ -228,6 +233,8 @@ describe("ProjectScriptEditorDialog", () => {
233 it.each([false, true])(
234 "preserves a concurrent shortcut change when saving only the script (settings access: %s)",
235 async (canWriteSettings) => {
236 + setup();
237 + await using screen = await render(null);
238 permissions.canWriteSettings = canWriteSettings;
239 const persisted = { name: request.initial.name, keybinding: request.initial.keybinding };
240 const onSubmit = vi.fn(async (_id: string | null, input: NewProjectScriptInput) => {
@@ -235,7 +242,7 @@ describe("ProjectScriptEditorDialog", () => {
242 if (input.keybinding !== undefined) persisted.keybinding = input.keybinding;
243 return AsyncResult.success(undefined);
244 });
238 - await openEditor(onSubmit);
245 + await openEditor(screen, onSubmit);
246
247 persisted.keybinding = "mod+j";
248 const name = document.querySelector<HTMLInputElement>("#script-name")!;
@@ -251,9 +258,11 @@ describe("ProjectScriptEditorDialog", () => {
258 it.each([false, true])(
259 "enforces settings access when submitting an explicit shortcut clear (revoked: %s)",
260 async (revokeBeforeSubmit) => {
261 + setup();
262 + await using screen = await render(null);
263 permissions.canWriteSettings = true;
264 const onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
256 - await openEditor(onSubmit);
265 + await openEditor(screen, onSubmit);
266 await pressInShortcutField("{Backspace}");
267 if (revokeBeforeSubmit) permissions.canWriteSettings = false;
268 await submit();
@@ -272,10 +281,12 @@ describe("ProjectScriptEditorDialog", () => {
281 it.each([false, true])(
282 "requires project access to save even with settings access (revoked: %s)",
283 async (revokeBeforeSubmit) => {
284 + setup();
285 + await using screen = await render(null);
286 permissions.canEditProject = revokeBeforeSubmit;
287 permissions.canWriteSettings = true;
288 const onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
278 - await openEditor(onSubmit);
289 + await openEditor(screen, onSubmit);
290
291 permissions.canEditProject = false;
292 await submit();
@@ -288,8 +299,10 @@ describe("ProjectScriptEditorDialog", () => {
299 );
300
301 it("rechecks project access before deleting from an already open confirmation", async () => {
302 + setup();
303 + await using screen = await render(null);
304 const actions = { onDelete: vi.fn(), onClose: vi.fn() };
292 - await openEditor(undefined, request, actions);
305 + await openEditor(screen, undefined, request, actions);
306 await click("Delete");
307
308 permissions.canEditProject = false;
apps/web/src/components/pullRequest/PullRequestCandidatePicker.browser.test.tsx
+29 -48
@@ -1,61 +1,42 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { act, render } from "../../../test/render";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3 import { userEvent } from "vite-plus/test/browser";
4
5 import { PullRequestCandidatePicker } from "./PullRequestCandidatePicker";
6
8 -let root: Root;
9 -let container: HTMLDivElement;
10 -
11 -beforeEach(() => {
12 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
13 - container = document.createElement("div");
14 - document.body.append(container);
15 - root = createRoot(container);
16 -});
17 -
18 -afterEach(async () => {
19 - await act(async () => root.unmount());
20 - container.remove();
21 - vi.unstubAllGlobals();
22 -});
23 -
7 describe("disabled candidate picker", () => {
8 it.each(["keyboard", "pointer"])(
9 "shows the refusal reason for %s without opening the picker",
10 async (input) => {
11 const onOpenChange = vi.fn();
12 const onSelect = vi.fn();
30 - await act(async () => {
31 - root.render(
32 - <PullRequestCandidatePicker
33 - icon="+"
34 - label="Request reviewers"
35 - allowed={false}
36 - disabledReason="Only collaborators can request reviewers."
37 - open={false}
38 - onOpenChange={onOpenChange}
39 - query=""
40 - onQueryChange={() => {}}
41 - searchLabel="Search reviewers"
42 - isPending={false}
43 - error={null}
44 - candidates={["alex"]}
45 - emptyLabel="No reviewers"
46 - noMatchLabel="No matching reviewers"
47 - errorLabel="Unable to load reviewers"
48 - truncated={false}
49 - truncatedLabel="More reviewers available"
50 - candidateKey={(candidate) => candidate}
51 - disabled={false}
52 - onSelect={onSelect}
53 - >
54 - {(candidate) => candidate}
55 - </PullRequestCandidatePicker>,
56 - );
57 - });
58 - const trigger = container.querySelector<HTMLButtonElement>(
13 + await using screen = await render(
14 + <PullRequestCandidatePicker
15 + icon="+"
16 + label="Request reviewers"
17 + allowed={false}
18 + disabledReason="Only collaborators can request reviewers."
19 + open={false}
20 + onOpenChange={onOpenChange}
21 + query=""
22 + onQueryChange={() => {}}
23 + searchLabel="Search reviewers"
24 + isPending={false}
25 + error={null}
26 + candidates={["alex"]}
27 + emptyLabel="No reviewers"
28 + noMatchLabel="No matching reviewers"
29 + errorLabel="Unable to load reviewers"
30 + truncated={false}
31 + truncatedLabel="More reviewers available"
32 + candidateKey={(candidate) => candidate}
33 + disabled={false}
34 + onSelect={onSelect}
35 + >
36 + {(candidate) => candidate}
37 + </PullRequestCandidatePicker>,
38 + );
39 + const trigger = screen.container.querySelector<HTMLButtonElement>(
40 'button[aria-label="Request reviewers"]',
41 )!;
42 if (input === "keyboard") {
apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx
+89 -91
@@ -10,15 +10,15 @@ import {
10 type ThreadPullRequestLink,
11 } from "@t3tools/contracts";
12 import * as Cause from "effect/Cause";
13 -import { act, type ComponentProps } from "react";
14 -import { createRoot, type Root } from "react-dom/client";
15 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13 +import type { ComponentProps } from "react";
14 +import { describe, expect, it, vi } from "vite-plus/test";
15 import { page, userEvent } from "vite-plus/test/browser";
16 import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
17 import { selectActiveRightPanelSurface, useRightPanelStore } from "~/rightPanelStore";
18 import { RightPanelSurfaceContent } from "../chat/RightPanelSurfaceContent";
19
20 import "~/index.css";
21 +import { act, render as renderUi } from "../../../test/render";
22
23 const {
24 newThread,
@@ -251,31 +251,30 @@ const shortcutContext = () => ({
251 isDesktop: false,
252 });
253
254 -const roots: Root[] = [];
255 -
256 -function render(props: Partial<ComponentProps<typeof PullRequestDetailPanel>> = {}) {
254 +function panelContainer() {
255 const container = document.createElement("div");
256 container.className = "flex h-[700px] w-[900px]";
259 - document.body.append(container);
260 - const root = createRoot(container);
261 - roots.push(root);
262 - return act(async () =>
263 - root.render(
264 - <PullRequestDetailPanel
265 - environmentId={threadRef.environmentId}
266 - reference={detail}
267 - context="page"
268 - shortcutsEnabled={false}
269 - getShortcutContext={shortcutContext}
270 - {...props}
271 - />,
272 - ),
257 + return container;
258 +}
259 +
260 +function render(props: Partial<ComponentProps<typeof PullRequestDetailPanel>> = {}) {
261 + return renderUi(
262 + <PullRequestDetailPanel
263 + environmentId={threadRef.environmentId}
264 + reference={detail}
265 + context="page"
266 + shortcutsEnabled={false}
267 + getShortcutContext={shortcutContext}
268 + {...props}
269 + />,
270 + { container: panelContainer() },
271 );
272 }
273
276 -beforeEach(() => {
274 +// The mocked modules and stores are shared by the whole file, so every test starts by
275 +// resetting them.
276 +function setup() {
277 activityDetail = null;
278 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
278 currentDetail = detail;
279 useComposerDraftStore.setState({ draftsByThreadKey: {} });
280 useRightPanelStore.setState({ byThreadKey: {} });
@@ -292,12 +291,7 @@ beforeEach(() => {
291 value: { branch: "feature", worktreePath: "/workspace/pr" },
292 });
293 update.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
295 -});
296 -afterEach(async () => {
297 - for (const root of roots.splice(0)) await act(async () => root.unmount());
298 - document.body.replaceChildren();
299 - vi.unstubAllGlobals();
300 -});
294 +}
295
296 const surface = { projectId: detail.projectId, repository: detail.repository, number: 1 };
297 const link = (number: number, source: ThreadPullRequestLink["source"]): ThreadPullRequestLink => ({
@@ -337,7 +331,8 @@ it.each([
331 { isComposing: true, keyCode: 13 },
332 { isComposing: false, keyCode: 229 },
333 ])("does not save the PR title during IME composition (%j)", async ({ isComposing, keyCode }) => {
340 - await render();
334 + setup();
335 + await using _screen = await render();
336 await page.getByRole("button", { name: "Edit title" }).click();
337 const titleInput = page.getByRole("textbox", { name: "Pull request title" });
338 const title = "日本語のタイトル";
@@ -395,7 +390,8 @@ describe.each([
390 render({ context, ...(target ? { composerDraftTarget: target, threadRef } : {}) });
391
392 it(`${thread === stackThread ? "hides" : "offers"} the checkout`, async () => {
398 - await renderPanel();
393 + setup();
394 + await using _screen = await renderPanel();
395 await expect.element(page.getByText("Test pull request").first()).toBeVisible();
396 expect(page.getByRole("button", { name: "Check out" }).elements()).toHaveLength(
397 thread === stackThread ? 0 : 1,
@@ -410,6 +406,7 @@ describe.each([
406 "Fix check",
407 "Add to agent",
408 ])("%s writes to the correct composer", async (action) => {
409 + setup();
410 // Cover both a host without inline comments and an account that cannot write them.
411 currentDetail =
412 thread === stackThread
@@ -422,7 +419,7 @@ describe.each([
419 }
420 : { ...detail, viewerPermissions: { ...detail.viewerPermissions, comment: true } };
421 if (target) useComposerDraftStore.getState().setPrompt(target, "Keep my draft");
425 - await renderPanel();
422 + await using _screen = await renderPanel();
423 await runAction(target ? action : action.replace("in this thread", "in a thread"));
424 const draft = () => useComposerDraftStore.getState().getComposerDraft(target ?? newDraftId);
425 await vi.waitFor(() => {
@@ -462,6 +459,7 @@ describe.each([
459 });
460
461 it("offers both selection actions and queues a permitted host review locally", async () => {
462 + setup();
463 currentDetail = {
464 ...detail,
465 capabilities: {
@@ -470,7 +468,7 @@ it("offers both selection actions and queues a permitted host review locally", a
468 },
469 viewerPermissions: { ...detail.viewerPermissions, comment: true },
470 };
473 - await render({ composerDraftTarget: draftId, threadRef });
471 + await using _screen = await render({ composerDraftTarget: draftId, threadRef });
472 await tab("Code").click();
473 await page.getByRole("button", { name: "Expand all files", exact: true }).click();
474 await selectFirstLine();
@@ -492,7 +490,8 @@ it("offers both selection actions and queues a permitted host review locally", a
490 });
491
492 it("cancels an agent-only selection and submits a fresh one with the keyboard without a host review", async () => {
495 - await render({ composerDraftTarget: draftId, threadRef });
493 + setup();
494 + await using _screen = await render({ composerDraftTarget: draftId, threadRef });
495 await tab("Code").click();
496 await page.getByRole("button", { name: "Expand all files", exact: true }).click();
497 await selectFirstLine();
@@ -518,7 +517,8 @@ it("cancels an agent-only selection and submits a fresh one with the keyboard wi
517 });
518
519 it("folds the title only for the active tab's own scroller", async () => {
521 - await render();
520 + setup();
521 + await using _screen = await render();
522 const title = page.getByRole("heading", { level: 1, name: "Test pull request" });
523 await expect.element(title).toBeVisible();
524 const titleFold = () => title.element().closest("[inert]") !== null;
@@ -563,66 +563,61 @@ it("folds the title only for the active tab's own scroller", async () => {
563 });
564
565 it("restores the selected PR tab when switching threads and remounting the right panel", async () => {
566 + setup();
567 const otherThread = { ...threadRef, threadId: ThreadId.make("thread-2") };
568 useRightPanelStore.getState().openPullRequest(threadRef, surface);
569 useRightPanelStore.getState().openPullRequest(otherThread, surface);
570 const codeTab = () => page.getByRole("button", { name: "Expand all files", exact: true });
570 - const container = document.createElement("div");
571 - container.className = "flex h-[700px] w-[900px]";
572 - document.body.append(container);
573 - const root = createRoot(container);
574 - roots.push(root);
575 - const show = (ref: ScopedThreadRef) => {
571 + const content = (ref: ScopedThreadRef) => {
572 const selected = selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, ref);
577 - return act(async () => {
578 - root.render(
579 - <RightPanelSurfaceContent
580 - surface={selected}
581 - activeSurfaceId={selected?.id ?? null}
582 - threadRef={ref}
583 - environmentId={ref.environmentId}
584 - visible
585 - composerDraftTarget={ref}
586 - keybindings={[]}
587 - configuredPreviewUrls={[]}
588 - workspaceMutationId={null}
589 - getShortcutContext={shortcutContext}
590 - onSendAnnotation={() => {}}
591 - onCloseSurface={() => {}}
592 - terminal={{
593 - launchContext: null,
594 - focusRequestId: 0,
595 - keybindings: [],
596 - onAddTerminalContext: () => {},
597 - onSplitTerminal: () => {},
598 - onSplitTerminalVertical: () => {},
599 - onNewTerminal: () => {},
600 - onActiveTerminalChange: () => {},
601 - onCloseTerminal: () => {},
602 - }}
603 - pullRequest={{
604 - capabilityKnown: true,
605 - supported: true,
606 - projectId: detail.projectId,
607 - pullRequests: [],
608 - linkedPullRequest: null,
609 - branchPullRequest: null,
610 - onBack: undefined,
611 - }}
612 - files={{
613 - projectName: null,
614 - workspaceRoot: undefined,
615 - availableEditors: [],
616 - pendingSurfaceIds: new Set(),
617 - onOpenFile: () => {},
618 - onPendingChange: () => {},
619 - }}
620 - />,
621 - );
622 - });
573 + return (
574 + <RightPanelSurfaceContent
575 + surface={selected}
576 + activeSurfaceId={selected?.id ?? null}
577 + threadRef={ref}
578 + environmentId={ref.environmentId}
579 + visible
580 + composerDraftTarget={ref}
581 + keybindings={[]}
582 + configuredPreviewUrls={[]}
583 + workspaceMutationId={null}
584 + getShortcutContext={shortcutContext}
585 + onSendAnnotation={() => {}}
586 + onCloseSurface={() => {}}
587 + terminal={{
588 + launchContext: null,
589 + focusRequestId: 0,
590 + keybindings: [],
591 + onAddTerminalContext: () => {},
592 + onSplitTerminal: () => {},
593 + onSplitTerminalVertical: () => {},
594 + onNewTerminal: () => {},
595 + onActiveTerminalChange: () => {},
596 + onCloseTerminal: () => {},
597 + }}
598 + pullRequest={{
599 + capabilityKnown: true,
600 + supported: true,
601 + projectId: detail.projectId,
602 + pullRequests: [],
603 + linkedPullRequest: null,
604 + branchPullRequest: null,
605 + onBack: undefined,
606 + }}
607 + files={{
608 + projectName: null,
609 + workspaceRoot: undefined,
610 + availableEditors: [],
611 + pendingSurfaceIds: new Set(),
612 + onOpenFile: () => {},
613 + onPendingChange: () => {},
614 + }}
615 + />
616 + );
617 };
618 + await using screen = await renderUi(content(threadRef), { container: panelContainer() });
619 + const show = (ref: ScopedThreadRef) => screen.rerender(content(ref));
620
625 - await show(threadRef);
621 await expect.element(page.getByTestId("summary-scroller")).toBeVisible();
622 await tab("Code").click();
623 await expect.element(codeTab()).toBeVisible();
@@ -640,7 +635,7 @@ it("restores the selected PR tab when switching threads and remounting the right
635 await show(threadRef);
636 await expect.element(codeTab()).toBeVisible();
637
643 - await act(async () => root.render(null));
638 + await screen.rerender(null);
639 useRightPanelStore.getState().openPullRequest(threadRef, { ...surface, url: detail.url });
640 await show(threadRef);
641 await expect.element(codeTab()).toBeVisible();
@@ -651,7 +646,8 @@ it("restores the selected PR tab when switching threads and remounting the right
646 });
647
648 it("stays collapsed at the bottom after native scroll clamping and reopens at the top", async () => {
654 - await render();
649 + setup();
650 + await using _screen = await render();
651 const title = page.getByRole("heading", { level: 1, name: "Test pull request" });
652 await expect.element(title).toBeVisible();
653 const scroller = page.getByTestId("summary-scroller").element() as HTMLElement;
@@ -688,6 +684,7 @@ it("stays collapsed at the bottom after native scroll clamping and reopens at th
684 });
685
686 it("shows the current checkout recovery detail on the first failure and on retry", async () => {
687 + setup();
688 const first = new GitManagerError({
689 cwd: "/workspace",
690 operation: "preparePullRequestThread",
@@ -699,7 +696,7 @@ it("shows the current checkout recovery detail on the first failure and on retry
696 command: "git worktree add",
697 detail: "The worktree directory already exists. Choose another directory.",
698 });
702 - await render();
699 + await using _screen = await render();
700
701 for (const [index, error] of [first, second].entries()) {
702 prepareThread.mockImplementationOnce(async () => {
@@ -717,6 +714,7 @@ it("shows the current checkout recovery detail on the first failure and on retry
714 });
715
716 it("keeps discussion counts and Timeline expansion in sync with activity refreshes", async () => {
717 + setup();
718 activityDetail = {
719 ...detail,
720 provider: SourceControlProviderKind.make("gitlab"),
@@ -751,7 +749,7 @@ it("keeps discussion counts and Timeline expansion in sync with activity refresh
749 },
750 ],
751 };
754 - await render({ reference: activityDetail });
752 + await using _screen = await render({ reference: activityDetail });
753 await expect.element(page.getByText("Discussion finding", { exact: true })).toBeVisible();
754 await expect.element(page.getByText("Discussion reply", { exact: true })).toBeVisible();
755 expect
apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx
+44 -53
@@ -1,7 +1,6 @@
1 +import { act, render, type Screen } from "../../../test/render";
2 import { AuthSourceControlWriteScope, EnvironmentId } from "@t3tools/contracts";
2 -import { act } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
3 +import { expect, it, vi } from "vite-plus/test";
4 import { userEvent } from "vite-plus/test/browser";
5
6 const permissions = vi.hoisted(() => ({
@@ -33,52 +32,38 @@ const primary = EnvironmentId.make("primary");
32 const secondary = EnvironmentId.make("secondary");
33 const onSave = vi.fn<(next: string) => void>();
34 const onCancel = vi.fn<() => void>();
36 -let root: Root;
37 -let container: HTMLDivElement;
35
39 -beforeEach(() => {
40 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
36 +function setup() {
37 permissions.allowed.clear();
38 permissions.listeners.clear();
39 onSave.mockReset();
40 onCancel.mockReset();
45 - container = document.createElement("div");
46 - document.body.append(container);
47 - root = createRoot(container);
48 -});
49 -
50 -afterEach(async () => {
51 - await act(async () => root.unmount());
52 - container.remove();
53 - vi.unstubAllGlobals();
54 -});
41 +}
42
43 async function openEditor(options?: { value?: string; allowEmpty?: boolean }) {
57 - await act(async () =>
58 - root.render(
59 - <PullRequestMarkdownEditor
60 - value={options?.value ?? "Original description"}
61 - cwd="/repo"
62 - environmentId={secondary}
63 - label="Pull request description"
64 - saving={false}
65 - allowEmpty={options?.allowEmpty ?? false}
66 - onSave={onSave}
67 - onCancel={onCancel}
68 - />,
69 - ),
44 + return render(
45 + <PullRequestMarkdownEditor
46 + value={options?.value ?? "Original description"}
47 + cwd="/repo"
48 + environmentId={secondary}
49 + label="Pull request description"
50 + saving={false}
51 + allowEmpty={options?.allowEmpty ?? false}
52 + onSave={onSave}
53 + onCancel={onCancel}
54 + />,
55 );
56 }
57
73 -function button(label: string) {
74 - const match = [...container.querySelectorAll("button")].find(
58 +function button(screen: Screen, label: string) {
59 + const match = [...screen.container.querySelectorAll("button")].find(
60 (element) => element.textContent === label,
61 );
62 expect(match, `button ${label}`).toBeDefined();
63 return match!;
64 }
65
81 -const clickSave = () => act(async () => button("Save").click());
66 +const clickSave = (screen: Screen) => act(async () => button(screen, "Save").click());
67
68 async function grant(allowed: boolean) {
69 await act(async () => {
@@ -89,69 +74,75 @@ async function grant(allowed: boolean) {
74 }
75
76 it("does not save a secondary environment's description using the primary grant", async () => {
77 + setup();
78 permissions.allowed.add(primary);
93 - await openEditor();
79 + await using screen = await openEditor();
80
95 - expect(button("Save").disabled).toBe(true);
96 - await clickSave();
81 + expect(button(screen, "Save").disabled).toBe(true);
82 + await clickSave(screen);
83
84 expect(onSave).not.toHaveBeenCalled();
85 });
86
87 it("rejects a Save click when the grant changes before React updates", async () => {
88 + setup();
89 permissions.allowed.add(secondary);
103 - await openEditor();
90 + await using screen = await openEditor();
91 permissions.allowed.delete(secondary);
92
106 - expect(button("Save").disabled).toBe(false);
107 - await clickSave();
93 + expect(button(screen, "Save").disabled).toBe(false);
94 + await clickSave(screen);
95
96 expect(onSave).not.toHaveBeenCalled();
97 });
98
99 it("keeps an edited draft through revocation and saves it after access returns without remounting", async () => {
100 + setup();
101 permissions.allowed.add(secondary);
114 - await openEditor();
115 - const textarea = container.querySelector("textarea")!;
102 + await using screen = await openEditor();
103 + const textarea = screen.container.querySelector("textarea")!;
104 await userEvent.clear(textarea);
105 await userEvent.type(textarea, "Keep these unsaved edits");
106
107 await grant(false);
120 - expect(button("Save").disabled).toBe(true);
121 - expect(container.querySelector("textarea")).toBe(textarea);
108 + expect(button(screen, "Save").disabled).toBe(true);
109 + expect(screen.container.querySelector("textarea")).toBe(textarea);
110
111 await grant(true);
124 - await clickSave();
112 + await clickSave(screen);
113 expect(onSave).toHaveBeenCalledExactlyOnceWith("Keep these unsaved edits");
114 });
115
116 it("saves with source-control permission alone, from the button or Cmd/Ctrl+Enter", async () => {
117 + setup();
118 permissions.allowed.add(secondary);
130 - await openEditor();
119 + await using screen = await openEditor();
120
132 - await clickSave();
121 + await clickSave(screen);
122 expect(onSave).toHaveBeenCalledExactlyOnceWith("Original description");
123
135 - container.querySelector("textarea")!.focus();
124 + screen.container.querySelector("textarea")!.focus();
125 await userEvent.keyboard("{Control>}{Enter}{/Control}");
126 expect(onSave).toHaveBeenCalledTimes(2);
127 });
128
129 it("allows clearing a description only after a pending grant becomes available", async () => {
141 - await openEditor({ value: "", allowEmpty: true });
142 - await clickSave();
130 + setup();
131 + await using screen = await openEditor({ value: "", allowEmpty: true });
132 + await clickSave(screen);
133 expect(onSave).not.toHaveBeenCalled();
134
135 await grant(true);
146 - await clickSave();
136 + await clickSave(screen);
137 expect(onSave).toHaveBeenCalledExactlyOnceWith("");
138 });
139
140 it("keeps cancelling a local edit available without a write grant", async () => {
151 - await openEditor();
141 + setup();
142 + await using screen = await openEditor();
143
153 - await act(async () => button("Cancel").click());
154 - container.querySelector("textarea")!.focus();
144 + await act(async () => button(screen, "Cancel").click());
145 + screen.container.querySelector("textarea")!.focus();
146 await userEvent.keyboard("{Escape}");
147
148 expect(onCancel).toHaveBeenCalledTimes(2);
apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx
+87 -90
@@ -5,9 +5,7 @@ import {
5 type PullRequestDetailView,
6 type PullRequestComment,
7 } from "@t3tools/contracts";
8 -import { act } from "react";
9 -import { createRoot, type Root } from "react-dom/client";
10 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
8 +import { expect, it, vi } from "vite-plus/test";
9 import { userEvent } from "vite-plus/test/browser";
10
11 vi.mock(import("~/state/use-atom-command"), async (original) => ({
@@ -15,6 +13,7 @@ vi.mock(import("~/state/use-atom-command"), async (original) => ({
13 useAtomCommand: (() => vi.fn()) as never,
14 }));
15
16 +import { act, render as renderUi, type Screen } from "../../../test/render";
17 import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
18
19 const detail: PullRequestDetailView = {
@@ -69,78 +68,71 @@ const detail: PullRequestDetailView = {
68 },
69 };
70
72 -let root: Root;
73 -let container: HTMLDivElement;
74 -beforeEach(() => {
75 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
76 - container = document.createElement("div");
77 - document.body.append(container);
78 - root = createRoot(container);
79 -});
80 -afterEach(async () => {
81 - await act(async () => root.unmount());
82 - container.remove();
71 +// The comment filter persists to localStorage, so tests that touch it start and end empty.
72 +function emptyLocalStorage(): Disposable {
73 localStorage.clear();
84 - vi.unstubAllGlobals();
85 -});
74 + return { [Symbol.dispose]: () => localStorage.clear() };
75 +}
76
87 -const render = (value = detail) =>
88 - act(async () =>
89 - root.render(
90 - <PullRequestSummaryTab
91 - scrollerRef={() => {}}
92 - environmentId={EnvironmentId.make("environment")}
93 - threadRef={null}
94 - reference={value}
95 - detail={value}
96 - activityPending={false}
97 - activityError={null}
98 - onRefresh={() => {}}
99 - />,
100 - ),
101 - );
77 +const tab = (value = detail) => (
78 + <PullRequestSummaryTab
79 + scrollerRef={() => {}}
80 + environmentId={EnvironmentId.make("environment")}
81 + threadRef={null}
82 + reference={value}
83 + detail={value}
84 + activityPending={false}
85 + activityError={null}
86 + onRefresh={() => {}}
87 + />
88 +);
89
103 -function heading(title: string) {
104 - const section = container.querySelector(`section[aria-label="${title}"]`);
105 - expect(section, `section ${title}`).not.toBeNull();
106 - return [...section!.querySelectorAll("button")].find(
107 - (button) => button.querySelector("span")?.textContent === title,
108 - )!;
90 +async function render(value = detail) {
91 + const screen = await renderUi(tab(value));
92 + const { container } = screen;
93 + const heading = (title: string) => {
94 + const section = container.querySelector(`section[aria-label="${title}"]`);
95 + expect(section, `section ${title}`).not.toBeNull();
96 + return [...section!.querySelectorAll("button")].find(
97 + (button) => button.querySelector("span")?.textContent === title,
98 + )!;
99 + };
100 + return Object.assign(screen, {
101 + click: (title: string) => act(async () => heading(title).click()),
102 + expanded: (title: string) => heading(title).getAttribute("aria-expanded"),
103 + visibleText: () => container.innerText,
104 + });
105 }
106
111 -const click = (title: string) => act(async () => heading(title).click());
112 -const expanded = (title: string) => heading(title).getAttribute("aria-expanded");
113 -const visibleText = () => container.innerText;
114 -
107 it("toggles checks from their heading and resets sections for another pull request", async () => {
116 - await render();
117 - expect(visibleText()).not.toContain("Unit tests");
118 - await click("Checks");
119 - expect(visibleText()).toContain("Unit tests");
120 - await click("Checks");
121 - expect(expanded("Checks")).toBe("false");
122 - await click("Checks");
123 - await click("Description");
124 - await render({ ...detail, url: "https://github.com/owner/repo/pull/2", number: 2 });
125 - expect(expanded("Checks")).toBe("false");
126 - expect(expanded("Description")).toBe("true");
108 + await using screen = await render();
109 + expect(screen.visibleText()).not.toContain("Unit tests");
110 + await screen.click("Checks");
111 + expect(screen.visibleText()).toContain("Unit tests");
112 + await screen.click("Checks");
113 + expect(screen.expanded("Checks")).toBe("false");
114 + await screen.click("Checks");
115 + await screen.click("Description");
116 + await screen.rerender(tab({ ...detail, url: "https://github.com/owner/repo/pull/2", number: 2 }));
117 + expect(screen.expanded("Checks")).toBe("false");
118 + expect(screen.expanded("Description")).toBe("true");
119 });
120
121 it("keeps an unsaved description when collapsed and reopened", async () => {
130 - await render();
122 + await using screen = await render();
123 await act(async () =>
132 - container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),
124 + screen.container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),
125 );
134 - const textarea = container.querySelector("textarea")!;
126 + const textarea = screen.container.querySelector("textarea")!;
127 await userEvent.clear(textarea);
128 await userEvent.type(textarea, "Unsaved description");
137 - await click("Description");
138 - expect(expanded("Description")).toBe("false");
139 - await click("Description");
140 - expect(container.querySelector("textarea")!.value).toBe("Unsaved description");
129 + await screen.click("Description");
130 + expect(screen.expanded("Description")).toBe("false");
131 + await screen.click("Description");
132 + expect(screen.container.querySelector("textarea")!.value).toBe("Unsaved description");
133 });
134
143 -function commentTexts() {
135 +function commentTexts({ container }: Screen) {
136 const section = [...container.querySelectorAll("section")].find((element) =>
137 element.getAttribute("aria-label")?.startsWith("Comments"),
138 )!;
@@ -149,7 +141,7 @@ function commentTexts() {
141 .map((p) => p.textContent ?? "");
142 }
143
152 -const filterButton = () =>
144 +const filterButton = ({ container }: Screen) =>
145 container.querySelector<HTMLButtonElement>('[aria-label="Filter comments"]')!;
146
147 function filterItem(label: string) {
@@ -160,12 +152,15 @@ function filterItem(label: string) {
152 return item!;
153 }
154
163 -async function toggleFilter(label: string) {
164 - if (!document.querySelector('[role="menuitemcheckbox"]')) await userEvent.click(filterButton());
155 +async function toggleFilter(screen: Screen, label: string) {
156 + if (!document.querySelector('[role="menuitemcheckbox"]')) {
157 + await userEvent.click(filterButton(screen));
158 + }
159 await userEvent.click(filterItem(label));
160 }
161
162 it("hides bot and resolved comments until the filter shows them, and remembers the choice", async () => {
163 + using _storage = emptyLocalStorage();
164 const comment = (index: number, login: string, body: string, isBot = false) => ({
165 id: `comment-${index}`,
166 kind: "issue-comment" as const,
@@ -202,30 +197,32 @@ it("hides bot and resolved comments until the filter shows them, and remembers t
197 },
198 ],
199 };
205 - await render(value);
206 - expect(commentTexts()).toEqual(["Human comment"]);
207 - expect(filterButton().textContent).toContain("13 hidden");
200 + await using screen = await render(value);
201 + expect(commentTexts(screen)).toEqual(["Human comment"]);
202 + expect(filterButton(screen).textContent).toContain("13 hidden");
203
209 - await toggleFilter("Bot comments");
210 - expect(commentTexts().filter((text) => text.startsWith("Bot report"))).toHaveLength(9);
211 - expect(commentTexts()).toContain("Human comment");
212 - expect(commentTexts()).not.toContain("Bot report 0");
204 + await toggleFilter(screen, "Bot comments");
205 + expect(commentTexts(screen).filter((text) => text.startsWith("Bot report"))).toHaveLength(9);
206 + expect(commentTexts(screen)).toContain("Human comment");
207 + expect(commentTexts(screen)).not.toContain("Bot report 0");
208
214 - await toggleFilter("Resolved or dismissed");
209 + await toggleFilter(screen, "Resolved or dismissed");
210 await userEvent.keyboard("{Escape}");
211 expect(
217 - [...container.querySelectorAll("button")].some((button) => button.textContent === "Resolved"),
212 + [...screen.container.querySelectorAll("button")].some(
213 + (button) => button.textContent === "Resolved",
214 + ),
215 ).toBe(true);
216
220 - await act(async () => root.unmount());
221 - root = createRoot(container);
222 - await render({ ...value, url: `${value.url}0`, number: 10 });
223 - expect(commentTexts()).toContain("Bot report 11");
224 - await userEvent.click(filterButton());
217 + await screen[Symbol.asyncDispose]();
218 + await using remounted = await render({ ...value, url: `${value.url}0`, number: 10 });
219 + expect(commentTexts(remounted)).toContain("Bot report 11");
220 + await userEvent.click(filterButton(remounted));
221 expect(filterItem("Bot comments").getAttribute("aria-checked")).toBe("true");
222 });
223
224 it("reveals whole older conversations with honest partial reply counts and a host link", async () => {
225 + using _storage = emptyLocalStorage();
226 const comment = (index: number): PullRequestComment => ({
227 id: `comment-${index}`,
228 kind: "issue-comment",
@@ -254,32 +251,32 @@ it("reveals whole older conversations with honest partial reply counts and a hos
251 commentCount: 15,
252 reviewThreads: [{ ...thread, commentCount: 5 }],
253 };
257 - await render(value);
258 - await toggleFilter("Resolved or dismissed");
254 + await using screen = await render(value);
255 + await toggleFilter(screen, "Resolved or dismissed");
256 await userEvent.keyboard("{Escape}");
260 - const older = [...container.querySelectorAll("button")].find((button) =>
257 + const older = [...screen.container.querySelectorAll("button")].find((button) =>
258 button.textContent?.startsWith("Show 1 older"),
259 )!;
260 expect(older).toBeDefined();
261 expect.soft(older.textContent).toMatch(/1 older conversation.*1 hidden/);
265 - expect(commentTexts()).not.toContain(reply.body);
262 + expect(commentTexts(screen)).not.toContain(reply.body);
263 await userEvent.click(older);
267 - const resolved = [...container.querySelectorAll("button")].find(
264 + const resolved = [...screen.container.querySelectorAll("button")].find(
265 (button) => button.textContent === "Resolved",
266 )!;
267 expect(resolved.getAttribute("aria-expanded")).toBe("false");
271 - expect(commentTexts()).not.toContain(reply.body);
272 - expect.soft(visibleText()).toContain("4 replies");
268 + expect(commentTexts(screen)).not.toContain(reply.body);
269 + expect.soft(screen.visibleText()).toContain("4 replies");
270 await userEvent.click(resolved);
274 - expect(commentTexts().slice(-2)).toEqual([finding.body, reply.body]);
275 - expect.soft(visibleText()).toContain("3 more replies");
276 - const hostLink = [...container.querySelectorAll("a")].find(
271 + expect(commentTexts(screen).slice(-2)).toEqual([finding.body, reply.body]);
272 + expect.soft(screen.visibleText()).toContain("3 more replies");
273 + const hostLink = [...screen.container.querySelectorAll("a")].find(
274 (link) =>
275 link.href === finding.url && /host/i.test(link.textContent ?? "") && link.checkVisibility(),
276 );
277 expect.soft(hostLink, "visible link to the unloaded replies on the host").toBeDefined();
278
282 - await render({ ...value, reviewThreads: [thread] });
283 - expect.soft(visibleText()).toMatch(/more replies/i);
284 - expect(visibleText()).not.toContain("3 more replies");
279 + await screen.rerender(tab({ ...value, reviewThreads: [thread] }));
280 + expect.soft(screen.visibleText()).toMatch(/more replies/i);
281 + expect(screen.visibleText()).not.toContain("3 more replies");
282 });
apps/web/src/components/pullRequest/usePullRequestFilesViewed.browser.test.tsx
+52 -47
@@ -1,3 +1,4 @@
1 +import { act, render, fakeTimers } from "../../../test/render";
2 import {
3 EnvironmentId,
4 ProjectId,
@@ -6,9 +7,8 @@ import {
7 } from "@t3tools/contracts";
8 import * as Cause from "effect/Cause";
9 import { AsyncResult } from "effect/reactivity";
9 -import { act, StrictMode, useEffect } from "react";
10 -import { createRoot, type Root } from "react-dom/client";
11 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
10 +import { StrictMode, useEffect } from "react";
11 +import { describe, expect, it, vi } from "vite-plus/test";
12
13 const { host, setFilesViewed, toastAdd } = vi.hoisted(() => ({
14 host: { data: null as unknown, refresh: vi.fn() },
@@ -57,51 +57,44 @@ function answer(state: "unviewed" | "viewed" | "dismissed"): PullRequestFilesVie
57 };
58 }
59
60 -let root: Root;
61 -let current: PullRequestFilesViewedView;
62 -
63 -function Surface() {
64 - const view = usePullRequestFilesViewed({ environmentId, reference, enabled: true });
65 - useEffect(() => {
66 - current = view;
67 - });
68 - return null;
69 -}
70 -
71 -const view = () => current;
72 -const render = () =>
73 - act(async () =>
74 - root.render(
75 - <StrictMode>
76 - <Surface />
77 - </StrictMode>,
78 - ),
79 - );
80 -
81 -async function reads(state: "unviewed" | "viewed" | "dismissed") {
82 - host.data = answer(state);
83 - await render();
84 -}
85 -
86 -beforeEach(async () => {
87 - vi.useFakeTimers();
88 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
60 +function setup() {
61 host.data = answer("unviewed");
62 host.refresh.mockReset();
63 toastAdd.mockReset();
64 setFilesViewed.mockReset().mockResolvedValue(AsyncResult.success(undefined));
93 - root = createRoot(document.createElement("div"));
94 - await render();
95 -});
96 -
97 -afterEach(async () => {
98 - await act(async () => root.unmount());
99 - vi.useRealTimers();
100 - vi.unstubAllGlobals();
101 -});
65 +}
66 +async function renderSurface() {
67 + let current!: PullRequestFilesViewedView;
68 + function Surface() {
69 + const view = usePullRequestFilesViewed({ environmentId, reference, enabled: true });
70 + useEffect(() => {
71 + current = view;
72 + });
73 + return null;
74 + }
75 + const ui = () => (
76 + <StrictMode>
77 + <Surface />
78 + </StrictMode>
79 + );
80 + const screen = await render(ui(), { router: false });
81 + return {
82 + view: () => current,
83 + reads: async (state: "unviewed" | "viewed" | "dismissed") => {
84 + host.data = answer(state);
85 + await screen.rerender(ui());
86 + },
87 + rerender: () => screen.rerender(ui()),
88 + [Symbol.asyncDispose]: () => screen[Symbol.asyncDispose](),
89 + };
90 +}
91
92 describe("a mark whose file was pushed to before the read that followed it", () => {
93 it("gives way to the host and shows the file as changed", async () => {
94 + setup();
95 + using _timers = fakeTimers();
96 + await using screen = await renderSurface();
97 + const { view, reads } = screen;
98 view().setViewed("a.ts", true);
99 await act(async () => vi.advanceTimersByTimeAsync(500));
100 expect(setFilesViewed).toHaveBeenCalledExactlyOnceWith({
@@ -117,6 +110,10 @@ describe("a mark whose file was pushed to before the read that followed it", ()
110 });
111
112 it("stays given way to on every later read, having nothing left to recover", async () => {
113 + setup();
114 + using _timers = fakeTimers();
115 + await using screen = await renderSurface();
116 + const { view, reads } = screen;
117 view().setViewed("a.ts", true);
118 await act(async () => vi.advanceTimersByTimeAsync(500));
119 await reads("dismissed");
@@ -131,6 +128,10 @@ describe("a mark whose file was pushed to before the read that followed it", ()
128
129 describe("a mark the host has not answered for yet", () => {
130 it("holds the press while the write is still out", async () => {
131 + setup();
132 + using _timers = fakeTimers();
133 + await using screen = await renderSurface();
134 + const { view, reads } = screen;
135 let land = (_result: unknown) => {};
136 setFilesViewed.mockReturnValueOnce(new Promise((resolve) => (land = resolve)));
137
@@ -145,6 +146,10 @@ describe("a mark the host has not answered for yet", () => {
146 });
147
148 it("holds a press made since the read that would otherwise answer for it", async () => {
149 + setup();
150 + using _timers = fakeTimers();
151 + await using screen = await renderSurface();
152 + const { view, reads } = screen;
153 view().setViewed("a.ts", true);
154 await act(async () => vi.advanceTimersByTimeAsync(500));
155
@@ -158,22 +163,22 @@ describe("a mark the host has not answered for yet", () => {
163
164 describe("a failed batch that the host partly applied", () => {
165 it("refreshes the host and accepts the applied marks", async () => {
166 + setup();
167 + using _timers = fakeTimers();
168 + await using screen = await renderSurface();
169 + const { view } = screen;
170 setFilesViewed.mockResolvedValueOnce(
171 AsyncResult.failure(Cause.fail(new Error("partial batch"))),
172 );
173 host.refresh.mockImplementation(() => {
174 host.data = answer("viewed");
166 - root.render(
167 - <StrictMode>
168 - <Surface />
169 - </StrictMode>,
170 - );
175 });
172 - act(() => {
176 + await act(() => {
177 view().setViewed("a.ts", true);
178 view().setViewed("b.ts", true);
179 });
180 await act(async () => vi.advanceTimersByTimeAsync(500));
181 + await screen.rerender();
182 expect(view().isViewed("a.ts")).toBe(true);
183 expect(view().isViewed("b.ts")).toBe(false);
184 });
apps/web/src/components/search/ProjectContentSearchDialog.browser.test.tsx
+35 -45
@@ -1,8 +1,8 @@
1 import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2 import { AuthFilesystemReadScope, EnvironmentId, ThreadId } from "@t3tools/contracts";
3 -import { act } from "react";
4 -import { createRoot, type Root } from "react-dom/client";
5 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
3 +import { expect, it, vi } from "vite-plus/test";
4 +
5 +import { act, render, type Screen } from "../../../test/render";
6
7 const state = vi.hoisted(() => ({
8 readScope: vi.fn(),
@@ -75,79 +75,69 @@ vi.mock(import("~/state/queries"), async (original) => {
75 import { useRightPanelStore } from "~/rightPanelStore";
76 import { ProjectContentSearchDialog } from "./ProjectContentSearchDialog";
77
78 -let root: Root;
79 -let container: HTMLDivElement;
80 -const onOpenChange = vi.fn();
81 -const openFile = vi.fn();
82 -
83 -beforeEach(() => {
78 +function setup() {
79 state.access = { canReadFiles: true, isCheckingAccess: false };
80 state.listeners.clear();
81 state.readScope.mockReset().mockReturnValue(true);
87 - openFile.mockClear();
88 - onOpenChange.mockClear();
89 - vi.spyOn(useRightPanelStore.getState(), "openFile").mockImplementation(openFile);
90 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
91 - container = document.createElement("div");
92 - document.body.append(container);
93 - root = createRoot(container);
94 -});
95 -
96 -afterEach(async () => {
97 - await act(() => root.unmount());
98 - container.remove();
99 - vi.restoreAllMocks();
100 - vi.unstubAllGlobals();
101 -});
82 + const openFile = vi.fn();
83 + const onOpenChange = vi.fn();
84 + const openFileSpy = vi
85 + .spyOn(useRightPanelStore.getState(), "openFile")
86 + .mockImplementation(openFile);
87 + return { openFile, onOpenChange, [Symbol.dispose]: () => openFileSpy.mockRestore() };
88 +}
89
103 -const input = () => container.querySelector("input")!;
104 -const result = () => container.querySelector<HTMLButtonElement>("[data-content-search-result]");
90 +const input = (screen: Screen) => screen.container.querySelector("input")!;
91 +const result = (screen: Screen) =>
92 + screen.container.querySelector<HTMLButtonElement>("[data-content-search-result]");
93
106 -async function openSearch() {
107 - await act(() => root.render(<ProjectContentSearchDialog onOpenChange={onOpenChange} />));
94 +function openSearch(onOpenChange: (open: boolean) => void) {
95 + return render(<ProjectContentSearchDialog onOpenChange={onOpenChange} />);
96 }
97
110 -async function type(text: string) {
98 +async function type(screen: Screen, text: string) {
99 await act(async () => {
100 const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
113 - setValue.call(input(), text);
114 - input().dispatchEvent(new Event("input", { bubbles: true }));
101 + setValue.call(input(screen), text);
102 + input(screen).dispatchEvent(new Event("input", { bubbles: true }));
103 });
104 }
105
106 it("enables search after access resolves and opens a result in its own environment", async () => {
107 + using env = setup();
108 state.access = { canReadFiles: false, isCheckingAccess: true };
120 - await openSearch();
121 - expect(input().disabled).toBe(true);
122 - expect(container.textContent).toContain("Checking file access…");
109 + await using screen = await openSearch(env.onOpenChange);
110 + expect(input(screen).disabled).toBe(true);
111 + expect(screen.container.textContent).toContain("Checking file access…");
112
113 await act(() => setAccess({ canReadFiles: true, isCheckingAccess: false }));
125 - expect(input().disabled).toBe(false);
126 - await type("match");
127 - await act(async () => result()!.click());
114 + expect(input(screen).disabled).toBe(false);
115 + await type(screen, "match");
116 + await act(async () => result(screen)!.click());
117
118 expect(state.readScope).toHaveBeenCalledWith(target.environmentId, AuthFilesystemReadScope);
130 - expect(openFile).toHaveBeenCalledWith(target.threadRef, "src/index.ts", 3);
131 - expect(onOpenChange).toHaveBeenCalledWith(false);
119 + expect(env.openFile).toHaveBeenCalledWith(target.threadRef, "src/index.ts", 3);
120 + expect(env.onOpenChange).toHaveBeenCalledWith(false);
121 });
122
123 it.each(["pointer", "keyboard"])(
124 "rechecks access before a retained %s action opens a result",
125 async (action) => {
137 - await openSearch();
138 - await type("match");
126 + using env = setup();
127 + await using screen = await openSearch(env.onOpenChange);
128 + await type(screen, "match");
129
130 state.readScope.mockReturnValue(false);
131 await act(async () => {
142 - if (action === "pointer") result()!.click();
132 + if (action === "pointer") result(screen)!.click();
133 else
144 - input().dispatchEvent(
134 + input(screen).dispatchEvent(
135 new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }),
136 );
137 });
138
139 expect(state.readScope).toHaveBeenCalled();
150 - expect(openFile).not.toHaveBeenCalled();
151 - expect(onOpenChange).not.toHaveBeenCalled();
140 + expect(env.openFile).not.toHaveBeenCalled();
141 + expect(env.onOpenChange).not.toHaveBeenCalled();
142 },
143 );
apps/web/src/components/settings/AcpRegistryIcon.browser.test.tsx
+37 -42
@@ -1,71 +1,66 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
1 +import { expect, it, vi } from "vite-plus/test";
2
3 +import { render, stubGlobal, type Screen } from "../../../test/render";
4 import { AcpRegistryAgentIcon } from "./AcpRegistryIcon";
5
6 const url = "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg";
8 -const fetchIcon = vi.fn<typeof fetch>();
9 -let root: Root;
10 -let container: HTMLDivElement;
7
12 -beforeEach(() => {
13 - vi.stubGlobal("caches", undefined);
14 - vi.stubGlobal("fetch", fetchIcon);
15 - fetchIcon.mockReset();
16 - container = document.createElement("div");
17 - document.body.append(container);
18 - root = createRoot(container);
19 -});
20 -afterEach(async () => {
21 - await act(async () => root.unmount());
22 - container.remove();
23 - vi.unstubAllGlobals();
24 -});
8 +function setup() {
9 + const fetchIcon = vi.fn<typeof fetch>();
10 + const stack = new DisposableStack();
11 + stack.use(stubGlobal("caches", undefined));
12 + stack.use(stubGlobal("fetch", fetchIcon));
13 + return { fetchIcon, [Symbol.dispose]: () => stack.dispose() };
14 +}
15
26 -const image = () => container.querySelector("img");
27 -const fallback = () => container.querySelector('[data-slot="acp-icon-fallback"]');
16 +const image = (screen: Screen) => screen.container.querySelector("img");
17 +const fallback = (screen: Screen) =>
18 + screen.container.querySelector('[data-slot="acp-icon-fallback"]');
19
20 it("falls back to the raw allowlisted CDN URL when the validating fetch is blocked", async () => {
21 + using env = setup();
22 // The official CDN serves no CORS headers, so the fetch can reject even
23 // though native <img> loading works.
32 - fetchIcon.mockRejectedValue(new TypeError("Failed to fetch"));
33 - await act(async () => root.render(<AcpRegistryAgentIcon icon={url} />));
24 + env.fetchIcon.mockRejectedValue(new TypeError("Failed to fetch"));
25 + await using screen = await render(<AcpRegistryAgentIcon icon={url} />);
26
35 - await vi.waitFor(() => expect(image()?.getAttribute("src")).toBe(url));
36 - expect(image()?.referrerPolicy).toBe("no-referrer");
37 - expect(fallback()).not.toBeNull();
27 + await vi.waitFor(() => expect(image(screen)?.getAttribute("src")).toBe(url));
28 + expect(image(screen)?.referrerPolicy).toBe("no-referrer");
29 + expect(fallback(screen)).not.toBeNull();
30 });
31
40 -function serve(body: string) {
32 +function serve(fetchIcon: ReturnType<typeof setup>["fetchIcon"], body: string) {
33 fetchIcon.mockResolvedValue(
34 new Response(body, { status: 200, headers: { "content-type": "image/svg+xml" } }),
35 );
36 }
37
38 it("swaps the fallback for the validated blob once the image loads", async () => {
47 - serve('<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"/>');
48 - await act(async () => root.render(<AcpRegistryAgentIcon icon={url} />));
39 + using env = setup();
40 + serve(env.fetchIcon, '<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"/>');
41 + await using screen = await render(<AcpRegistryAgentIcon icon={url} />);
42
50 - await vi.waitFor(() => expect(fallback()).toBeNull());
51 - expect(image()?.src).toMatch(/^blob:/);
52 - expect(image()?.checkVisibility()).toBe(true);
43 + await vi.waitFor(() => expect(fallback(screen)).toBeNull());
44 + expect(image(screen)?.src).toMatch(/^blob:/);
45 + expect(image(screen)?.checkVisibility()).toBe(true);
46 });
47
48 it("keeps the fallback and drops the image when the validated blob fails to decode", async () => {
56 - serve("not an svg");
57 - await act(async () => root.render(<AcpRegistryAgentIcon icon={url} />));
49 + using env = setup();
50 + serve(env.fetchIcon, "not an svg");
51 + await using screen = await render(<AcpRegistryAgentIcon icon={url} />);
52
59 - await vi.waitFor(() => expect(fetchIcon).toHaveBeenCalledOnce());
60 - await vi.waitFor(() => expect(image()).toBeNull());
61 - expect(fallback()).not.toBeNull();
53 + await vi.waitFor(() => expect(env.fetchIcon).toHaveBeenCalledOnce());
54 + await vi.waitFor(() => expect(image(screen)).toBeNull());
55 + expect(fallback(screen)).not.toBeNull();
56 });
57
58 it("never renders an icon from outside the official CDN", async () => {
65 - await act(async () =>
66 - root.render(<AcpRegistryAgentIcon icon="https://cdn.agentclientprotocol.com.evil/icon.svg" />),
59 + using env = setup();
60 + await using screen = await render(
61 + <AcpRegistryAgentIcon icon="https://cdn.agentclientprotocol.com.evil/icon.svg" />,
62 );
68 - expect(fetchIcon).not.toHaveBeenCalled();
69 - expect(image()).toBeNull();
70 - expect(fallback()).not.toBeNull();
63 + expect(env.fetchIcon).not.toHaveBeenCalled();
64 + expect(image(screen)).toBeNull();
65 + expect(fallback(screen)).not.toBeNull();
66 });
apps/web/src/components/settings/AcpRegistrySearchStep.browser.test.tsx
+45 -52
@@ -5,11 +5,11 @@ import {
5 type AcpRegistrySearchInput,
6 } from "@t3tools/contracts";
7 import * as Cause from "effect/Cause";
8 -import { act } from "react";
9 -import { createRoot, type Root } from "react-dom/client";
10 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
8 +import { expect, it, vi } from "vite-plus/test";
9 import { page, userEvent } from "vite-plus/test/browser";
10
11 +import { act, fakeTimers, render } from "../../../test/render";
12 +
13 const state = vi.hoisted(() => ({
14 result: null as { readonly agents: ReadonlyArray<AcpRegistrySearchAgent> } | null,
15 error: null as string | null,
@@ -69,31 +69,26 @@ const gemini: AcpRegistrySearchAgent = {
69 integrity: "registry",
70 };
71
72 -const roots: Root[] = [];
73 -let root: Root;
74 -
75 -function render(options?: {
72 +function step(options?: {
73 readonly configured?: boolean;
74 readonly onPrepared?: (agent: AcpRegistrySearchAgent) => void;
75 }) {
79 - return act(async () =>
80 - root.render(
81 - <AcpRegistrySearchStep
82 - environmentId={environmentId}
83 - providerInstances={
84 - options?.configured
85 - ? {
86 - acpRegistry_gemini: {
87 - driver: ProviderDriverKind.make("acpRegistry"),
88 - config: { agentId: "gemini" },
89 - },
90 - }
91 - : {}
92 - }
93 - onPrepared={options?.onPrepared ?? vi.fn()}
94 - onManualConfiguration={vi.fn()}
95 - />,
96 - ),
76 + return (
77 + <AcpRegistrySearchStep
78 + environmentId={environmentId}
79 + providerInstances={
80 + options?.configured
81 + ? {
82 + acpRegistry_gemini: {
83 + driver: ProviderDriverKind.make("acpRegistry"),
84 + config: { agentId: "gemini" },
85 + },
86 + }
87 + : {}
88 + }
89 + onPrepared={options?.onPrepared ?? vi.fn()}
90 + onManualConfiguration={vi.fn()}
91 + />
92 );
93 }
94
@@ -109,7 +104,7 @@ function deferred<T>() {
104 return { promise, resolve };
105 }
106
112 -beforeEach(() => {
107 +function setup() {
108 state.canManage = true;
109 state.result = null;
110 state.error = null;
@@ -120,19 +115,10 @@ beforeEach(() => {
115 _tag: "Success",
116 value: { agentId: "gemini", version: "1.2.3", distribution: "npx", prepared: true },
117 });
123 - const container = document.createElement("div");
124 - document.body.append(container);
125 - root = createRoot(container);
126 - roots.push(root);
127 -});
128 -
129 -afterEach(async () => {
130 - vi.useRealTimers();
131 - for (const mounted of roots.splice(0)) await act(async () => mounted.unmount());
132 - document.body.replaceChildren();
133 -});
118 +}
119
120 it("shows the full catalog initially and after clearing a debounced search", async () => {
121 + setup();
122 const agents = Array.from({ length: 25 }, (_, index) => ({
123 ...gemini,
124 id: `gemini-${index}`,
@@ -146,11 +132,11 @@ it("shows the full catalog initially and after clearing a debounced search", asy
132 };
133 });
134 const addButtons = () => page.getByRole("button", { name: /^Add Gemini CLI / }).elements();
149 - await render();
135 + await using _screen = await render(step());
136 expect(addButtons()).toHaveLength(25);
137 await expect.element(page.getByRole("button", { name: "Add Gemini CLI 25" })).toBeEnabled();
138
153 - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
139 + using _timers = fakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
140 await userEvent.fill(searchBox(), " Gemini ");
141 await act(async () => vi.advanceTimersByTime(200));
142 await userEvent.fill(searchBox(), " Gemini CLI ");
@@ -166,38 +152,40 @@ it("shows the full catalog initially and after clearing a debounced search", asy
152 });
153
154 it("shows the loading, error, and empty states", async () => {
155 + setup();
156 state.isPending = true;
170 - await render();
157 + await using screen = await render(step());
158 await expect.element(page.getByText("Searching the registry...")).toBeVisible();
159
160 state.isPending = false;
161 state.error = "Registry unavailable.";
175 - await render();
162 + await screen.rerender(step());
163 await expect.element(page.getByText("Registry unavailable.")).toBeVisible();
164
165 state.error = null;
166 state.result = { agents: [] };
180 - await render();
167 + await screen.rerender(step());
168 await expect.element(page.getByText("No compatible agents found")).toBeVisible();
169 });
170
171 it("submits a typed query at once and refreshes when the same query is submitted again", async () => {
185 - await render();
172 + setup();
173 + await using screen = await render(step());
174 // A slow runner must not let the typing debounce submit the query before Enter does.
187 - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
175 + using _timers = fakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
176 await userEvent.fill(searchBox(), "Codex");
177 await userEvent.keyboard("{Enter}");
178 expect(lastQuery()).toBe("Codex");
179 expect(state.refresh).not.toHaveBeenCalled();
180
181 state.result = { agents: [gemini] };
194 - await render();
182 + await screen.rerender(step());
183 await userEvent.click(searchBox());
184 await userEvent.keyboard("{Enter}");
185 expect(state.refresh).toHaveBeenCalledOnce();
186
187 state.isPending = true;
200 - await render();
188 + await screen.rerender(step());
189 await expect
190 .element(page.getByRole("status").filter({ hasText: "Refreshing ACP Registry results." }))
191 .toBeInTheDocument();
@@ -205,13 +193,14 @@ it("submits a typed query at once and refreshes when the same query is submitted
193 });
194
195 it("prepares a result before handing it back to the wizard", async () => {
196 + setup();
197 state.prepare.mockResolvedValueOnce({
198 _tag: "Success",
199 value: { agentId: "gemini", version: "2.0.0", distribution: "binary", prepared: true },
200 });
201 state.result = { agents: [gemini] };
202 const onPrepared = vi.fn();
214 - await render({ onPrepared });
203 + await using _screen = await render(step({ onPrepared }));
204
205 await page.getByRole("button", { name: "Add Gemini CLI" }).click();
206
@@ -226,10 +215,11 @@ it("prepares a result before handing it back to the wizard", async () => {
215 });
216
217 it("shows progress, locks the step while an agent prepares, and reports a failure", async () => {
218 + setup();
219 const pending = deferred<unknown>();
220 state.prepare.mockReturnValueOnce(pending.promise);
221 state.result = { agents: [{ ...gemini, distribution: "binary" }] };
232 - await render();
222 + await using _screen = await render(step());
223
224 await page.getByRole("button", { name: "Add Gemini CLI" }).click();
225 await expect.element(page.getByRole("button", { name: "Downloading Gemini CLI" })).toBeDisabled();
@@ -243,9 +233,10 @@ it("shows progress, locks the step while an agent prepares, and reports a failur
233 });
234
235 it("rechecks the grant before preparing an agent", async () => {
236 + setup();
237 state.result = { agents: [gemini] };
238 const onPrepared = vi.fn();
248 - await render({ onPrepared });
239 + await using _screen = await render(step({ onPrepared }));
240 state.canManage = false;
241
242 await page.getByRole("button", { name: "Add Gemini CLI" }).click();
@@ -255,14 +246,15 @@ it("rechecks the grant before preparing an agent", async () => {
246 });
247
248 it("ignores prepare completion after unmount", async () => {
249 + setup();
250 const pending = deferred<unknown>();
251 state.prepare.mockReturnValueOnce(pending.promise);
252 state.result = { agents: [gemini] };
253 const onPrepared = vi.fn();
262 - await render({ onPrepared });
254 + await using screen = await render(step({ onPrepared }));
255
256 await page.getByRole("button", { name: "Add Gemini CLI" }).click();
265 - await act(async () => root.unmount());
257 + await screen.unmount();
258 await act(async () =>
259 pending.resolve({
260 _tag: "Success",
@@ -274,8 +266,9 @@ it("ignores prepare completion after unmount", async () => {
266 });
267
268 it("shows an existing registry configuration as already added", async () => {
269 + setup();
270 state.result = { agents: [gemini] };
278 - await render({ configured: true });
271 + await using _screen = await render(step({ configured: true }));
272 await expect
273 .element(page.getByRole("button", { name: "Already added Gemini CLI" }))
274 .toBeDisabled();
apps/web/src/components/settings/AcpSessionManagementSection.browser.test.tsx
+62 -65
@@ -6,9 +6,9 @@ import {
6 ThreadId,
7 type ServerProvider,
8 } from "@t3tools/contracts";
9 -import { act } from "react";
10 -import { createRoot, type Root } from "react-dom/client";
11 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
9 +import { describe, expect, it, vi } from "vite-plus/test";
10 +
11 +import { act, render } from "../../../test/render";
12
13 const commands = vi.hoisted(() => ({
14 list: vi.fn(),
@@ -85,33 +85,30 @@ function deferred<T>() {
85 return { promise, resolve };
86 }
87
88 -let root: Root;
89 -let container: HTMLDivElement;
90 -
91 -function render(readOnly = false) {
92 - return act(async () =>
93 - root.render(
94 - <AcpSessionManagementSection
95 - environmentId={environmentId}
96 - instanceId={instanceId}
97 - provider={provider}
98 - projects={[{ id: projectId, title: "Antigravity", workspaceRoot: session.cwd }]}
99 - readOnly={readOnly}
100 - />,
101 - ),
88 +async function renderSection(readOnly = false) {
89 + const screen = await render(
90 + <AcpSessionManagementSection
91 + environmentId={environmentId}
92 + instanceId={instanceId}
93 + provider={provider}
94 + projects={[{ id: projectId, title: "Antigravity", workspaceRoot: session.cwd }]}
95 + readOnly={readOnly}
96 + />,
97 );
98 + const button = (label: string) => {
99 + const found = [...screen.container.querySelectorAll("button")].find(
100 + (element) => element.textContent === label,
101 + );
102 + expect(found, `button ${label}`).toBeDefined();
103 + return found!;
104 + };
105 + return Object.assign(screen, {
106 + button,
107 + click: (label: string) => act(async () => button(label).click()),
108 + });
109 }
104 -function button(label: string) {
105 - const found = [...container.querySelectorAll("button")].find(
106 - (element) => element.textContent === label,
107 - );
108 - expect(found, `button ${label}`).toBeDefined();
109 - return found!;
110 -}
111 -const click = (label: string) => act(async () => button(label).click());
110
113 -beforeEach(() => {
114 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
111 +function setup() {
112 grants.scopes = new Set(["orchestration:read", "orchestration:operate", "providers:manage"]);
113 commands.list.mockReset().mockResolvedValue({
114 _tag: "Success",
@@ -157,29 +154,21 @@ beforeEach(() => {
154 value: { loggedOut: true },
155 });
156 dialogs.confirm.mockReset().mockResolvedValue(true);
160 - container = document.createElement("div");
161 - document.body.append(container);
162 - root = createRoot(container);
163 -});
164 -
165 -afterEach(async () => {
166 - await act(async () => root.unmount());
167 - container.remove();
168 - vi.unstubAllGlobals();
169 -});
157 +}
158
159 describe("AcpSessionManagementSection", () => {
160 it("lists and imports native sessions through the owning environment", async () => {
173 - await render();
174 - await click("List sessions");
161 + setup();
162 + await using screen = await renderSection();
163 + await screen.click("List sessions");
164
165 expect(commands.list).toHaveBeenCalledWith({
166 environmentId,
167 input: { instanceId, projectId },
168 });
180 - expect(container.textContent).toContain(session.title);
169 + expect(screen.container.textContent).toContain(session.title);
170
182 - await click("Import");
171 + await screen.click("Import");
172
173 expect(commands.import).toHaveBeenCalledWith({
174 environmentId,
@@ -191,12 +180,13 @@ describe("AcpSessionManagementSection", () => {
180 updatedAt: session.updatedAt,
181 },
182 });
194 - expect(button("Imported").disabled).toBe(true);
183 + expect(screen.button("Imported").disabled).toBe(true);
184 });
185
186 it("logs out the provider instance through the owning environment", async () => {
198 - await render();
199 - await click("Log out");
187 + setup();
188 + await using screen = await renderSection();
189 + await screen.click("Log out");
190
191 expect(commands.logout).toHaveBeenCalledWith({
192 environmentId,
@@ -205,9 +195,10 @@ describe("AcpSessionManagementSection", () => {
195 });
196
197 it("deletes unimported native sessions after destructive confirmation", async () => {
208 - await render();
209 - await click("List sessions");
210 - await click("Delete");
198 + setup();
199 + await using screen = await renderSection();
200 + await screen.click("List sessions");
201 + await screen.click("Delete");
202
203 expect(dialogs.confirm).toHaveBeenCalledOnce();
204 expect(commands.delete).toHaveBeenCalledWith({
@@ -217,17 +208,18 @@ describe("AcpSessionManagementSection", () => {
208 });
209
210 it("locks the project picker while a project-scoped request is pending", async () => {
211 + setup();
212 const pending = deferred<{
213 readonly _tag: "Success";
214 readonly value: { readonly providers: [] };
215 }>();
216 commands.listProviders.mockReturnValueOnce(pending.promise);
225 - await render();
217 + await using screen = await renderSection();
218 const picker = () =>
227 - container.querySelector<HTMLElement>('[aria-label="Project for ACP sessions"]')!;
219 + screen.container.querySelector<HTMLElement>('[aria-label="Project for ACP sessions"]')!;
220 expect(picker().hasAttribute("data-disabled")).toBe(false);
221
230 - await click("List providers");
222 + await screen.click("List providers");
223
224 expect(picker().hasAttribute("data-disabled")).toBe(true);
225 await act(async () => pending.resolve({ _tag: "Success", value: { providers: [] } }));
@@ -235,17 +227,19 @@ describe("AcpSessionManagementSection", () => {
227 });
228
229 it("lists, saves, and disables configurable ACP providers", async () => {
238 - await render();
239 - await click("List providers");
230 + setup();
231 + await using screen = await renderSection();
232 + await screen.click("List providers");
233
234 expect(commands.listProviders).toHaveBeenCalledWith({
235 environmentId,
236 input: { instanceId, projectId },
237 });
238 expect(
246 - container.querySelector<HTMLInputElement>('input[aria-label="google base URL"]')?.value,
239 + screen.container.querySelector<HTMLInputElement>('input[aria-label="google base URL"]')
240 + ?.value,
241 ).toBe("https://api.example.test/v1");
248 - await click("Save");
242 + await screen.click("Save");
243 expect(commands.setProvider).toHaveBeenCalledWith({
244 environmentId,
245 input: {
@@ -257,7 +251,7 @@ describe("AcpSessionManagementSection", () => {
251 },
252 });
253
260 - await click("Disable");
254 + await screen.click("Disable");
255 expect(commands.disableProvider).toHaveBeenCalledWith({
256 environmentId,
257 input: { instanceId, projectId, providerId: "google" },
@@ -266,29 +260,32 @@ describe("AcpSessionManagementSection", () => {
260 });
261
262 it("imports with task access even when provider configuration is read-only", async () => {
263 + setup();
264 grants.scopes.delete("providers:manage");
270 - await render(true);
271 - await click("List sessions");
272 - await click("Import");
265 + await using screen = await renderSection(true);
266 + await screen.click("List sessions");
267 + await screen.click("Import");
268 expect(commands.import).toHaveBeenCalledOnce();
269 });
270
271 it("does not import with provider management alone", async () => {
272 + setup();
273 grants.scopes.delete("orchestration:operate");
278 - await render();
279 - await click("List sessions");
280 - expect(button("Import").disabled).toBe(true);
281 - await click("Import");
274 + await using screen = await renderSection();
275 + await screen.click("List sessions");
276 + expect(screen.button("Import").disabled).toBe(true);
277 + await screen.click("Import");
278 expect(commands.import).not.toHaveBeenCalled();
279 });
280
281 it("rechecks task access after confirming deletion", async () => {
286 - await render();
287 - await click("List sessions");
282 + setup();
283 + await using screen = await renderSection();
284 + await screen.click("List sessions");
285 dialogs.confirm.mockImplementationOnce(async () => {
286 grants.scopes.delete("orchestration:operate");
287 return true;
288 });
292 - await click("Delete");
289 + await screen.click("Delete");
290 expect(commands.delete).not.toHaveBeenCalled();
291 });
apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx
+46 -45
@@ -1,8 +1,8 @@
1 import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts";
2 -import { act } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
2 import { userEvent } from "vite-plus/test/browser";
5 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 +import { describe, expect, it, vi } from "vite-plus/test";
4 +
5 +import { act, render } from "../../../test/render";
6
7 const actions = vi.hoisted(() => ({
8 toast: vi.fn(),
@@ -100,20 +100,14 @@ function deferred<T>() {
100 return { promise, resolve };
101 }
102
103 -let root: Root;
104 -
105 -function render(onOpenChange = actions.onOpenChange) {
106 - return act(async () =>
107 - root.render(
108 - <AddProviderInstanceDialog
109 - open
110 - environmentId={remoteEnvironmentId}
111 - environmentLabel="Remote device"
112 - onOpenChange={onOpenChange}
113 - />,
114 - ),
115 - );
116 -}
103 +const dialog = () => (
104 + <AddProviderInstanceDialog
105 + open
106 + environmentId={remoteEnvironmentId}
107 + environmentLabel="Remote device"
108 + onOpenChange={actions.onOpenChange}
109 + />
110 +);
111 function button(label: string) {
112 const found = [...document.querySelectorAll("button")].find(
113 (element) => element.textContent?.trim() === label,
@@ -134,30 +128,28 @@ async function type(selector: string, value: string) {
128 const signInStep = () => document.querySelector('[aria-label="Sign-in step"]');
129
130 async function prepareCodexInstance() {
137 - await render();
131 + await using stack = new AsyncDisposableStack();
132 + const screen = stack.use(await render(dialog()));
133 await click("Configure manually");
134 await type("#add-provider-label", "Work");
135 await click("Next");
136 + stack.move();
137 + return screen;
138 }
139
143 -describe("AddProviderInstanceDialog environment routing", () => {
144 - beforeEach(() => {
145 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
146 - actions.canManageProviders = true;
147 - actions.toast.mockReset();
148 - actions.onOpenChange.mockReset();
149 - settingsHooks.read.mockReset().mockReturnValue({ providerInstances: {} });
150 - settingsHooks.mutate.mockReset().mockResolvedValue({ _tag: "Success", value: {} });
151 - settingsHooks.useMutation.mockReset().mockReturnValue(settingsHooks.mutate);
152 - root = createRoot(document.createElement("div"));
153 - });
154 - afterEach(async () => {
155 - await act(async () => root.unmount());
156 - vi.unstubAllGlobals();
157 - });
140 +function setup() {
141 + actions.canManageProviders = true;
142 + actions.toast.mockReset();
143 + actions.onOpenChange.mockReset();
144 + settingsHooks.read.mockReset().mockReturnValue({ providerInstances: {} });
145 + settingsHooks.mutate.mockReset().mockResolvedValue({ _tag: "Success", value: {} });
146 + settingsHooks.useMutation.mockReset().mockReturnValue(settingsHooks.mutate);
147 +}
148
149 +describe("AddProviderInstanceDialog environment routing", () => {
150 it("creates a provider with its default identity without typing", async () => {
160 - await render();
151 + setup();
152 + await using _screen = await render(dialog());
153 const grok = [...document.querySelectorAll('[role="radio"]')].find((radio) =>
154 radio.textContent?.includes("Grok"),
155 ) as HTMLElement;
@@ -173,10 +165,11 @@ describe("AddProviderInstanceDialog environment routing", () => {
165 });
166
167 it("chooses an unused identity for another account without replacing configured instances", async () => {
168 + setup();
169 settingsHooks.read.mockReturnValue({
170 providerInstances: { codex_2: { driver: "codex", enabled: false } },
171 });
179 - await render();
172 + await using _screen = await render(dialog());
173 await click("Configure manually");
174 await click("Next");
175 await click("Add instance");
@@ -193,16 +186,18 @@ describe("AddProviderInstanceDialog environment routing", () => {
186 });
187
188 it("reads and writes settings through the supplied environment", async () => {
196 - await render();
189 + setup();
190 + await using _screen = await render(dialog());
191
192 expect(settingsHooks.read).toHaveBeenCalledWith(remoteEnvironmentId);
193 expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);
194 });
195
196 it("awaits an atomic create before closing and retains prepared ACP metadata", async () => {
197 + setup();
198 const mutation = deferred<{ readonly _tag: "Success"; readonly value: unknown }>();
199 settingsHooks.mutate.mockReturnValueOnce(mutation.promise);
205 - await render();
200 + await using _screen = await render(dialog());
201 await click("Use Kilo Code");
202
203 expect(document.body.textContent).toContain("v4.2.0 · binary");
@@ -232,7 +227,8 @@ describe("AddProviderInstanceDialog environment routing", () => {
227 });
228
229 it("configures a manually entered registry agent from the first provider screen", async () => {
235 - await render();
230 + setup();
231 + await using _screen = await render(dialog());
232 await click("Enter registry agent");
233 await type("#add-provider-acpRegistry-manual-agentId", "devin");
234 await click("Next");
@@ -250,7 +246,8 @@ describe("AddProviderInstanceDialog environment routing", () => {
246 });
247
248 it("creates a local command in the selected environment without a sign-in step", async () => {
253 - await render();
249 + setup();
250 + await using _screen = await render(dialog());
251 await click("Use local command");
252 await click("Next");
253 expect(document.body.textContent).toContain("Executable is required.");
@@ -295,8 +292,9 @@ describe("AddProviderInstanceDialog environment routing", () => {
292 });
293
294 it("keeps the dialog open when the atomic upsert fails", async () => {
295 + setup();
296 settingsHooks.mutate.mockResolvedValueOnce({ _tag: "Failure", cause: new Error("Conflict") });
299 - await render();
297 + await using _screen = await render(dialog());
298 await click("Use Kilo Code");
299 await click("Continue to sign-in");
300
@@ -308,7 +306,8 @@ describe("AddProviderInstanceDialog environment routing", () => {
306 });
307
308 it("adds an instance with the selected environment's provider grant alone", async () => {
311 - await prepareCodexInstance();
309 + setup();
310 + await using _screen = await prepareCodexInstance();
311 await click("Add instance");
312
313 expect(settingsHooks.mutate).toHaveBeenCalledWith({
@@ -328,7 +327,8 @@ describe("AddProviderInstanceDialog environment routing", () => {
327 });
328
329 it("rejects a queued save after the provider grant is revoked", async () => {
331 - await prepareCodexInstance();
330 + setup();
331 + await using screen = await prepareCodexInstance();
332 const save = button("Add instance");
333 actions.canManageProviders = false;
334 // The rendered button is still enabled; the click must recheck the live grant.
@@ -337,18 +337,19 @@ describe("AddProviderInstanceDialog environment routing", () => {
337 expect(settingsHooks.mutate).not.toHaveBeenCalled();
338 expect(actions.toast).not.toHaveBeenCalled();
339 expect(actions.onOpenChange).not.toHaveBeenCalled();
340 - await render();
340 + await screen.rerender(dialog());
341 expect(button("Add instance").disabled).toBe(true);
342 });
343
344 it("keeps a denied draft available when the provider grant arrives", async () => {
345 + setup();
346 actions.canManageProviders = false;
346 - await prepareCodexInstance();
347 + await using screen = await prepareCodexInstance();
348 expect(button("Add instance").disabled).toBe(true);
349 expect(settingsHooks.mutate).not.toHaveBeenCalled();
350
351 actions.canManageProviders = true;
351 - await render();
352 + await screen.rerender(dialog());
353 expect(button("Add instance").disabled).toBe(false);
354 await click("Add instance");
355 expect(settingsHooks.mutate).toHaveBeenCalledOnce();
apps/web/src/components/settings/CaptureShortcutConfig.browser.test.tsx
+105 -101
@@ -3,10 +3,10 @@ import {
3 type DesktopCaptureConfigPreview,
4 type DesktopSnapShotState,
5 } from "@t3tools/contracts";
6 -import { act } from "react";
7 -import { createRoot, type Root } from "react-dom/client";
6 import { userEvent } from "vite-plus/test/browser";
9 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
7 +import { expect, it, vi } from "vite-plus/test";
8 +
9 +import { act, render } from "../../../test/render";
10
11 const bridge = vi.hoisted(() => ({
12 previewSnapShotConfig: vi.fn(),
@@ -44,10 +44,19 @@ function deferred<T>() {
44 return { promise, resolve };
45 }
46
47 -let root: Root;
48 -let container: HTMLDivElement;
47 +function setup() {
48 + const platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
49 + bridge.setSnapShotShortcutSuppressed.mockReset().mockResolvedValue(undefined);
50 + bridge.previewSnapShotConfig.mockReset().mockResolvedValue(preview);
51 + bridge.applySnapShotConfig
52 + .mockReset()
53 + .mockResolvedValue({ backupPath: "/config/backup", warning: null });
54 + complete.mockReset().mockResolvedValue(undefined);
55 + toast.mockClear();
56 + return { [Symbol.dispose]: () => platform.mockRestore() };
57 +}
58
50 -async function render(desktop: "niri" | "hyprland" = "niri") {
59 +async function renderConfig(desktop: "niri" | "hyprland" = "niri") {
60 const state: DesktopSnapShotState = {
61 mode: "portal",
62 linuxBackend: desktop,
@@ -59,62 +68,46 @@ async function render(desktop: "niri" | "hyprland" = "niri") {
68 shortcutConfigPath: preview.path,
69 shortcutBinding: "manual binding",
70 };
62 - await act(async () => root.render(<CaptureShortcutConfig state={state} onComplete={complete} />));
63 -}
64 -function button(label: string) {
65 - return [...container.querySelectorAll("button")].find((element) => element.textContent === label);
66 -}
67 -async function click(label: string) {
68 - const target = button(label);
69 - expect(target, `button ${label}`).toBeDefined();
70 - await act(async () => target!.click());
71 -}
72 -const recorder = () => container.querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;
73 -const diff = () => container.querySelector('[aria-label="Shortcut changes"]');
74 -const alert = () => container.querySelector('[role="alert"]');
75 -const advanced = () => container.querySelector("details")!;
76 -async function recordKeys(keys: string) {
77 - await act(async () => userEvent.click(recorder()));
78 - await act(async () => userEvent.keyboard(keys));
71 + const screen = await render(<CaptureShortcutConfig state={state} onComplete={complete} />);
72 + const { container } = screen;
73 + const button = (label: string) =>
74 + [...container.querySelectorAll("button")].find((element) => element.textContent === label);
75 + const recorder = () => container.querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;
76 + return Object.assign(screen, {
77 + button,
78 + recorder,
79 + diff: () => container.querySelector('[aria-label="Shortcut changes"]'),
80 + alert: () => container.querySelector('[role="alert"]'),
81 + advanced: () => container.querySelector("details")!,
82 + async click(label: string) {
83 + const target = button(label);
84 + expect(target, `button ${label}`).toBeDefined();
85 + await act(async () => target!.click());
86 + },
87 + async recordKeys(keys: string) {
88 + await act(async () => userEvent.click(recorder()));
89 + await act(async () => userEvent.keyboard(keys));
90 + },
91 + });
92 }
93
81 -beforeEach(() => {
82 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
83 - Object.defineProperty(navigator, "platform", { configurable: true, get: () => "Linux" });
84 - bridge.setSnapShotShortcutSuppressed.mockReset().mockResolvedValue(undefined);
85 - bridge.previewSnapShotConfig.mockReset().mockResolvedValue(preview);
86 - bridge.applySnapShotConfig
87 - .mockReset()
88 - .mockResolvedValue({ backupPath: "/config/backup", warning: null });
89 - complete.mockReset().mockResolvedValue(undefined);
90 - toast.mockClear();
91 - container = document.createElement("div");
92 - document.body.append(container);
93 - root = createRoot(container);
94 -});
95 -afterEach(async () => {
96 - await act(async () => root.unmount());
97 - container.remove();
98 - Reflect.deleteProperty(navigator, "platform");
99 - vi.unstubAllGlobals();
100 -});
101 -
94 it.each(["niri", "hyprland"] as const)(
95 "shows the fallback before review and requires separate read and write approval on %s",
96 async (desktop) => {
105 - await render(desktop);
106 - expect(recorder().getAttribute("aria-label")).toBe(
97 + using _env = setup();
98 + await using screen = await renderConfig(desktop);
99 + expect(screen.recorder().getAttribute("aria-label")).toBe(
100 "Record snapshot shortcut, currently Ctrl+Shift+2",
101 );
109 - expect(advanced().textContent).toContain("manual binding");
102 + expect(screen.advanced().textContent).toContain("manual binding");
103 expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
111 - await click("Review changes");
112 - expect(recorder().getAttribute("aria-label")).toBe(
104 + await screen.click("Review changes");
105 + expect(screen.recorder().getAttribute("aria-label")).toBe(
106 "Record snapshot shortcut, currently Ctrl+Shift+2",
107 );
108 expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
116 - expect(diff()).not.toBeNull();
117 - await click("Save shortcut");
109 + expect(screen.diff()).not.toBeNull();
110 + await screen.click("Save shortcut");
111 expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(preview.id);
112 expect(complete).toHaveBeenCalledOnce();
113 expect(toast).toHaveBeenCalledWith(expect.objectContaining({ type: "success" }));
@@ -124,9 +117,10 @@ it.each(["niri", "hyprland"] as const)(
117 it.each(["niri", "hyprland"] as const)(
118 "lets users choose %s keys without opening Advanced, then approve the matching diff",
119 async (desktop) => {
127 - await render(desktop);
128 - expect(advanced().contains(recorder())).toBe(false);
129 - await recordKeys("{Control>}{Alt>}y{/Alt}{/Control}");
120 + using _env = setup();
121 + await using screen = await renderConfig(desktop);
122 + expect(screen.advanced().contains(screen.recorder())).toBe(false);
123 + await screen.recordKeys("{Control>}{Alt>}y{/Alt}{/Control}");
124 expect(bridge.setSnapShotShortcutSuppressed).toHaveBeenNthCalledWith(1, true);
125 expect(bridge.setSnapShotShortcutSuppressed).toHaveBeenLastCalledWith(false);
126 expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
@@ -137,14 +131,14 @@ it.each(["niri", "hyprland"] as const)(
131 after: preview.after.replace("Ctrl+Shift+2", "Ctrl+Alt+Y"),
132 };
133 bridge.previewSnapShotConfig.mockResolvedValue(custom);
140 - await click("Review changes");
134 + await screen.click("Review changes");
135 expect(bridge.previewSnapShotConfig).toHaveBeenCalledExactlyOnceWith({
136 operation: "install",
137 chooseFile: false,
138 shortcut: "ctrl+alt+y",
139 });
140 expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
147 - await click("Save shortcut");
141 + await screen.click("Save shortcut");
142 expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(custom.id);
143 expect(toast).toHaveBeenCalledWith(
144 expect.objectContaining({ description: "Use Ctrl+Alt+Y from another app." }),
@@ -153,111 +147,121 @@ it.each(["niri", "hyprland"] as const)(
147 );
148
149 it("uses the existing config keys when no replacement was chosen", async () => {
150 + using _env = setup();
151 bridge.previewSnapShotConfig.mockResolvedValue({ ...preview, shortcut: "Super+F8" });
157 - await render();
158 - await click("Review changes");
152 + await using screen = await renderConfig();
153 + await screen.click("Review changes");
154 expect(bridge.previewSnapShotConfig).toHaveBeenCalledExactlyOnceWith({
155 operation: "install",
156 chooseFile: false,
157 });
163 - expect(recorder().getAttribute("aria-label")).toContain("F8");
158 + expect(screen.recorder().getAttribute("aria-label")).toContain("F8");
159 });
160
161 it("requires a new diff after changing keys during review", async () => {
167 - await render();
168 - await click("Review changes");
169 - expect(diff()).not.toBeNull();
170 - await recordKeys("{Meta>}{F8}{/Meta}");
171 - expect(diff()).toBeNull();
162 + using _env = setup();
163 + await using screen = await renderConfig();
164 + await screen.click("Review changes");
165 + expect(screen.diff()).not.toBeNull();
166 + await screen.recordKeys("{Meta>}{F8}{/Meta}");
167 + expect(screen.diff()).toBeNull();
168 expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
169 const replacement = { ...preview, id: "replacement", shortcut: "Super+F8" };
170 bridge.previewSnapShotConfig.mockResolvedValue(replacement);
175 - await click("Review changes");
171 + await screen.click("Review changes");
172 expect(bridge.previewSnapShotConfig).toHaveBeenLastCalledWith({
173 operation: "install",
174 chooseFile: false,
175 shortcut: "meta+f8",
176 });
181 - await click("Save shortcut");
177 + await screen.click("Save shortcut");
178 expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(replacement.id);
179 });
180
181 it.each(["Escape", "blur"])(
182 "keeps the reviewed diff when recording is cancelled with %s",
183 async (cancel) => {
188 - await render();
189 - await click("Review changes");
190 - await act(async () => userEvent.click(recorder()));
191 - expect(button("Save shortcut")?.disabled).toBe(true);
184 + using _env = setup();
185 + await using screen = await renderConfig();
186 + await screen.click("Review changes");
187 + await act(async () => userEvent.click(screen.recorder()));
188 + expect(screen.button("Save shortcut")?.disabled).toBe(true);
189 if (cancel === "Escape") await act(async () => userEvent.keyboard("{Escape}"));
193 - else await act(async () => recorder().blur());
194 - expect(button("Save shortcut")?.disabled).toBe(false);
190 + else await act(async () => screen.recorder().blur());
191 + expect(screen.button("Save shortcut")?.disabled).toBe(false);
192 expect(bridge.previewSnapShotConfig).toHaveBeenCalledOnce();
196 - await click("Save shortcut");
193 + await screen.click("Save shortcut");
194 expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(preview.id);
195 },
196 );
197
198 it("cancelling a reviewed diff does not write or finish setup", async () => {
202 - await render();
203 - await click("Review changes");
204 - await click("Cancel");
205 - expect(recorder().getAttribute("aria-label")).toBe(
199 + using _env = setup();
200 + await using screen = await renderConfig();
201 + await screen.click("Review changes");
202 + await screen.click("Cancel");
203 + expect(screen.recorder().getAttribute("aria-label")).toBe(
204 "Record snapshot shortcut, currently Ctrl+Shift+2",
205 );
208 - expect(button("Review changes")).toBeDefined();
206 + expect(screen.button("Review changes")).toBeDefined();
207 expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
208 expect(complete).not.toHaveBeenCalled();
209 });
210
211 it("shows reading feedback until a proposal arrives", async () => {
212 + using _env = setup();
213 const pending = deferred<DesktopCaptureConfigPreview>();
214 bridge.previewSnapShotConfig.mockReturnValue(pending.promise);
216 - await render();
217 - await click("Review changes");
218 - expect(button("Preparing changes…")?.disabled).toBe(true);
215 + await using screen = await renderConfig();
216 + await screen.click("Review changes");
217 + expect(screen.button("Preparing changes…")?.disabled).toBe(true);
218 await act(async () => pending.resolve(preview));
220 - expect(button("Save shortcut")?.disabled).toBe(false);
219 + expect(screen.button("Save shortcut")?.disabled).toBe(false);
220 });
221
222 it("keeps read failures actionable with technical details in Advanced, then permits retry", async () => {
223 + using _env = setup();
224 bridge.previewSnapShotConfig.mockRejectedValueOnce(new Error("EACCES: /config/niri/config.kdl"));
225 - await render();
226 - await click("Review changes");
227 - expect(alert()?.textContent).toBe("Couldn't prepare the changes. Check Advanced for help.");
228 - expect(advanced().textContent).toContain("EACCES: /config/niri/config.kdl");
229 - await click("Review changes");
230 - expect(alert()).toBeNull();
231 - expect(button("Save shortcut")?.disabled).toBe(false);
225 + await using screen = await renderConfig();
226 + await screen.click("Review changes");
227 + expect(screen.alert()?.textContent).toBe(
228 + "Couldn't prepare the changes. Check Advanced for help.",
229 + );
230 + expect(screen.advanced().textContent).toContain("EACCES: /config/niri/config.kdl");
231 + await screen.click("Review changes");
232 + expect(screen.alert()).toBeNull();
233 + expect(screen.button("Save shortcut")?.disabled).toBe(false);
234 expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
235 });
236
237 it("withdraws a stale diff and requires another read instead of retrying its write", async () => {
236 - await render();
237 - await click("Review changes");
238 + using _env = setup();
239 + await using screen = await renderConfig();
240 + await screen.click("Review changes");
241 bridge.applySnapShotConfig.mockRejectedValue(
242 new Error("Your config changed since this preview."),
243 );
241 - await click("Save shortcut");
242 - expect(alert()?.textContent).toContain("Review the changes and try again");
243 - expect(advanced().textContent).toContain("Your config changed since this preview.");
244 - expect(button("Review changes")).toBeDefined();
245 - expect(diff()).toBeNull();
244 + await screen.click("Save shortcut");
245 + expect(screen.alert()?.textContent).toContain("Review the changes and try again");
246 + expect(screen.advanced().textContent).toContain("Your config changed since this preview.");
247 + expect(screen.button("Review changes")).toBeDefined();
248 + expect(screen.diff()).toBeNull();
249 expect(complete).not.toHaveBeenCalled();
250 });
251
252 it("does not finish or claim success when the desktop could not reload", async () => {
250 - await render();
251 - await click("Review changes");
253 + using _env = setup();
254 + await using screen = await renderConfig();
255 + await screen.click("Review changes");
256 bridge.applySnapShotConfig.mockResolvedValue({
257 backupPath: "/config/backup",
258 warning: "Config saved, but reload failed.",
259 });
256 - await click("Save shortcut");
257 - expect(container.querySelector('[role="status"]')?.textContent).toBe(
260 + await screen.click("Save shortcut");
261 + expect(screen.container.querySelector('[role="status"]')?.textContent).toBe(
262 "Saved, but the shortcut needs attention. Check Advanced for help.",
263 );
260 - expect(advanced().textContent).toContain("Config saved, but reload failed.");
264 + expect(screen.advanced().textContent).toContain("Config saved, but reload failed.");
265 expect(complete).not.toHaveBeenCalled();
266 expect(toast).not.toHaveBeenCalled();
267 });
apps/web/src/components/settings/DeviceToolUpdate.browser.test.tsx
+14 -31
@@ -6,9 +6,10 @@ import {
6 type DeviceServiceState,
7 } from "@t3tools/contracts";
8 import * as Cause from "effect/Cause";
9 -import { act, type ReactNode } from "react";
10 -import { createRoot, type Root } from "react-dom/client";
11 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
9 +import type { ReactNode } from "react";
10 +import { expect, it, vi } from "vite-plus/test";
11 +
12 +import { act, render } from "../../../test/render";
13
14 const { list } = vi.hoisted(() => ({ list: vi.fn() }));
15
@@ -86,20 +87,6 @@ const deviceState = {
87 revision: 1,
88 } satisfies DeviceServiceState;
89
89 -let root: Root | undefined;
90 -let container: HTMLDivElement | undefined;
91 -
92 -beforeEach(() => {
93 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
94 - list.mockReset();
95 -});
96 -
97 -afterEach(async () => {
98 - await act(() => root?.unmount());
99 - container?.remove();
100 - vi.unstubAllGlobals();
101 -});
102 -
90 it.each([
91 {
92 name: "a failed install",
@@ -122,26 +109,22 @@ it.each([
109 ])(
110 "reports $name as the server describes it, not as a network problem",
111 async ({ error, message }) => {
125 - list.mockResolvedValue({ _tag: "Failure", cause: Cause.fail(error) });
126 - container = document.body.appendChild(document.createElement("div"));
127 - root = createRoot(container);
128 - await act(() => {
129 - root!.render(
130 - <DeviceIntegrationControls
131 - environmentId={environmentId}
132 - enabled
133 - agentAccessEnabled={false}
134 - />,
135 - );
136 - });
112 + list.mockReset().mockResolvedValue({ _tag: "Failure", cause: Cause.fail(error) });
113 + await using screen = await render(
114 + <DeviceIntegrationControls
115 + environmentId={environmentId}
116 + enabled
117 + agentAccessEnabled={false}
118 + />,
119 + );
120
138 - const update = [...container.querySelectorAll("button")].find(
121 + const update = [...screen.container.querySelectorAll("button")].find(
122 (button) => button.textContent === "Update to v0.12.0",
123 );
124 expect(update).toBeDefined();
125 await act(async () => update!.click());
126
127 expect(list).toHaveBeenCalledWith({ environmentId, input: { updateTool: "hub" } });
145 - expect(container.querySelector('[role="alert"]')?.textContent).toBe(message);
128 + expect(screen.container.querySelector('[role="alert"]')?.textContent).toBe(message);
129 },
130 );
apps/web/src/components/settings/FontFamilyPicker.browser.test.tsx
+12 -31
@@ -1,8 +1,8 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { describe, expect, it, vi } from "vite-plus/test";
2 import { userEvent } from "vite-plus/test/browser";
3
4 +import { act, render } from "../../../test/render";
5 +
6 const families = vi.hoisted(() => {
7 const families = [
8 "Arial",
@@ -26,24 +26,6 @@ vi.mock("../../appearanceFonts", () => ({
26
27 import { discoverInstalledFonts, FontFamilyPicker } from "./FontFamilyPicker";
28
29 -let root: Root;
30 -let container: HTMLDivElement;
31 -
32 -beforeEach(async () => {
33 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
34 - container = document.createElement("div");
35 - document.body.append(container);
36 - root = createRoot(container);
37 - await act(async () => discoverInstalledFonts());
38 -});
39 -
40 -afterEach(async () => {
41 - await act(() => root.unmount());
42 - container.remove();
43 - vi.restoreAllMocks();
44 - vi.unstubAllGlobals();
45 -});
46 -
29 function highlightedOptions(): string[] {
30 return [...document.querySelectorAll('[role="option"][data-highlighted]')].map(
31 (option) => option.textContent ?? "",
@@ -53,16 +35,15 @@ function highlightedOptions(): string[] {
35 describe("FontFamilyPicker", () => {
36 it("highlights, moves through, and selects matches after filtering", async () => {
37 const onSelect = vi.fn();
56 - await act(async () =>
57 - root.render(
58 - <FontFamilyPicker
59 - ariaLabel="Code font"
60 - defaultFamily="Menlo"
61 - selectedFamily=""
62 - initialOpen
63 - onSelect={onSelect}
64 - />,
65 - ),
38 + await act(() => discoverInstalledFonts());
39 + await using _screen = await render(
40 + <FontFamilyPicker
41 + ariaLabel="Code font"
42 + defaultFamily="Menlo"
43 + selectedFamily=""
44 + initialOpen
45 + onSelect={onSelect}
46 + />,
47 );
48
49 const input = document.querySelector<HTMLInputElement>('input[placeholder="Search fonts…"]');
apps/web/src/components/settings/IntegrationsSettings.browser.test.tsx
+21 -39
@@ -1,16 +1,10 @@
1 import { DEFAULT_CLIENT_SETTINGS, DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts";
2 -import {
3 - createMemoryHistory,
4 - createRootRoute,
5 - createRouter,
6 - RouterProvider,
7 -} from "@tanstack/react-router";
8 -import { act, StrictMode } from "react";
9 -import { createRoot, type Root } from "react-dom/client";
10 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2 +import { StrictMode } from "react";
3 +import { describe, expect, it, vi } from "vite-plus/test";
4 import { page } from "vite-plus/test/browser";
5
6 import "../../index.css";
7 +import { render } from "../../../test/render";
8
9 const { listBrowserImportSources } = vi.hoisted(() => ({
10 listBrowserImportSources: vi.fn().mockResolvedValue([]),
@@ -55,57 +49,45 @@ vi.mock(import("./SettingsScopeContext"), async (original) => ({
49
50 import { IntegrationsSettingsPanel } from "./IntegrationsSettings";
51
58 -let root: Root;
59 -let container: HTMLDivElement;
60 -
61 -beforeEach(() => {
62 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
52 +function setup() {
53 listBrowserImportSources.mockClear();
64 - container = document.createElement("div");
65 - document.body.append(container);
66 - root = createRoot(container);
67 -});
68 -
69 -afterEach(async () => {
70 - await act(async () => root.unmount());
71 - container.remove();
72 - vi.unstubAllGlobals();
73 -});
54 +}
55
56 async function openSettings() {
76 - const router = createRouter({
77 - routeTree: createRootRoute({ component: IntegrationsSettingsPanel }),
78 - history: createMemoryHistory(),
79 - });
80 - await router.load();
81 - await act(async () =>
82 - root.render(
57 + await using stack = new AsyncDisposableStack();
58 + const screen = stack.use(
59 + await render(
60 <StrictMode>
84 - <RouterProvider router={router} />
61 + <IntegrationsSettingsPanel />
62 </StrictMode>,
63 ),
64 );
88 - await vi.waitFor(() => expect(container.querySelector("section#browser")).not.toBeNull());
65 + await vi.waitFor(() => expect(screen.container.querySelector("section#browser")).not.toBeNull());
66 + stack.move();
67 + return screen;
68 }
69
70 describe("Integrations browser discovery", () => {
71 it("keeps agent browser access in the single Browser section", async () => {
93 - await openSettings();
72 + setup();
73 + await using screen = await openSettings();
74
75 expect(page.getByRole("heading", { name: "Browser", exact: true }).elements()).toHaveLength(1);
76 const access = page.getByRole("switch", { name: "Agent browser access", exact: true });
77 await expect.element(access).toBeVisible();
98 - expect(access.element().closest("section")).toBe(container.querySelector("section#browser"));
78 + expect(access.element().closest("section")).toBe(
79 + screen.container.querySelector("section#browser"),
80 + );
81 expect(access.element().closest("#agent-browser-access")).not.toBeNull();
82 });
83
84 it("does not scan browser files when entering or revisiting settings", async () => {
103 - await openSettings();
85 + setup();
86 + await using first = await openSettings();
87 expect(listBrowserImportSources).not.toHaveBeenCalled();
88
106 - await act(async () => root.unmount());
107 - root = createRoot(container);
108 - await openSettings();
89 + await first.unmount();
90 + await using _second = await openSettings();
91 expect(listBrowserImportSources).not.toHaveBeenCalled();
92 });
93 });
apps/web/src/components/settings/KeybindingsSettings.environment.browser.test.tsx
+32 -39
@@ -1,7 +1,7 @@
1 import type { EnvironmentId } from "@t3tools/contracts";
2 -import { act } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3 +
4 +import { act, render, type Screen } from "../../../test/render";
5
6 const state = vi.hoisted(() => ({
7 canOperate: false,
@@ -54,49 +54,39 @@ vi.mock(import("../../editorPreferences"), async (original) => ({
54
55 import { KeybindingsSettingsPanel } from "./KeybindingsSettings";
56
57 -let root: Root;
58 -let container: HTMLDivElement;
57 +function setup() {
58 + state.canOperate = false;
59 + state.canWriteSettings = true;
60 + state.connected = true;
61 + state.openEditor.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
62 +}
63
60 -const render = () => act(async () => root.render(<KeybindingsSettingsPanel />));
61 -const openButton = () => {
62 - const button = container.querySelector<HTMLButtonElement>(
64 +const renderPanel = () => render(<KeybindingsSettingsPanel />);
65 +const openButton = (screen: Screen) => {
66 + const button = screen.container.querySelector<HTMLButtonElement>(
67 'button[aria-label="Open keybindings.json"]',
68 );
69 expect(button).not.toBeNull();
70 return button!;
71 };
72
69 -beforeEach(() => {
70 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
71 - state.canOperate = false;
72 - state.canWriteSettings = true;
73 - state.connected = true;
74 - state.openEditor.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
75 - container = document.createElement("div");
76 - document.body.append(container);
77 - root = createRoot(container);
78 -});
79 -afterEach(async () => {
80 - await act(async () => root.unmount());
81 - container.remove();
82 - vi.unstubAllGlobals();
83 -});
84 -
73 describe("KeybindingsSettings editor permission", () => {
74 it("rejects editor launches when settings writes are the only write grant", async () => {
87 - await render();
88 - expect(openButton().disabled).toBe(true);
89 - await act(async () => openButton().click());
75 + setup();
76 + await using screen = await renderPanel();
77 + expect(openButton(screen).disabled).toBe(true);
78 + await act(async () => openButton(screen).click());
79 expect(state.openEditor).not.toHaveBeenCalled();
80 });
81
82 it("opens the primary environment's file after operate is granted without settings writes", async () => {
83 + setup();
84 state.canWriteSettings = false;
95 - await render();
85 + await using screen = await renderPanel();
86 state.canOperate = true;
97 - await render();
98 - expect(openButton().disabled).toBe(false);
99 - await act(async () => openButton().click());
87 + await screen.rerender(<KeybindingsSettingsPanel />);
88 + expect(openButton(screen).disabled).toBe(false);
89 + await act(async () => openButton(screen).click());
90
91 expect(state.openEditor).toHaveBeenCalledWith({
92 environmentId: "primary-settings",
@@ -105,30 +95,33 @@ describe("KeybindingsSettings editor permission", () => {
95 });
96
97 it("rejects a queued editor launch after operate is revoked", async () => {
98 + setup();
99 state.canOperate = true;
109 - await render();
110 - const button = openButton();
100 + await using screen = await renderPanel();
101 + const button = openButton(screen);
102 state.canOperate = false;
103 // The rendered button is still enabled; the click must recheck the live grant.
104 await act(async () => button.click());
105
106 expect(state.openEditor).not.toHaveBeenCalled();
116 - await render();
117 - expect(openButton().disabled).toBe(true);
107 + await screen.rerender(<KeybindingsSettingsPanel />);
108 + expect(openButton(screen).disabled).toBe(true);
109 });
110 });
111
112 describe("KeybindingsSettings write notice", () => {
113 it("asks for a connected environment when none is connected", async () => {
114 + setup();
115 state.connected = false;
124 - await render();
125 - expect(container.textContent).toContain("Connect an environment to change keybindings.");
116 + await using screen = await renderPanel();
117 + expect(screen.container.textContent).toContain("Connect an environment to change keybindings.");
118 });
119
120 it("names the permission when the connection cannot write settings", async () => {
121 + setup();
122 state.canWriteSettings = false;
130 - await render();
131 - expect(container.textContent).toContain(
123 + await using screen = await renderPanel();
124 + expect(screen.container.textContent).toContain(
125 "This connection can view keybindings but cannot change them.",
126 );
127 });
apps/web/src/components/settings/ProjectFaviconPickerDialog.browser.test.tsx
+40 -51
@@ -1,11 +1,10 @@
1 import { RegistryContext } from "@effect/atom-react";
2 import { EnvironmentId, type AssetCreateUrlResult, type ProjectEntry } from "@t3tools/contracts";
3 import { AsyncResult, Atom } from "effect/reactivity";
4 -import { act } from "react";
5 -import { createRoot, type Root } from "react-dom/client";
6 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
4 +import { expect, it, vi } from "vite-plus/test";
5
6 import "~/index.css";
7 +import { act, render, stubGlobal } from "../../../test/render";
8
9 type AssetResult = AsyncResult.AsyncResult<AssetCreateUrlResult, Error>;
10 const state = vi.hoisted(() => ({
@@ -56,12 +55,8 @@ import {
55 ProjectFaviconPickerDialog,
56 } from "./ProjectFaviconPickerDialog";
57
59 -let root: Root;
60 -let container: HTMLDivElement;
61 -
62 -beforeEach(() => {
63 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
64 - Object.defineProperty(navigator, "platform", { configurable: true, get: () => "MacIntel" });
58 +function setup() {
59 + const platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
60 toast.mockClear();
61 state.entries = [];
62 state.assets.clear();
@@ -69,36 +64,26 @@ beforeEach(() => {
64 state.createUrl
65 .mockReset()
66 .mockImplementation(({ input }) => state.assets.get(input.resource.path)!);
72 - container = document.createElement("div");
73 - document.body.append(container);
74 - root = createRoot(container);
75 -});
76 -afterEach(async () => {
77 - await act(async () => root.unmount());
78 - container.remove();
79 - Reflect.deleteProperty(navigator, "platform");
80 - vi.unstubAllGlobals();
81 -});
67 + return { [Symbol.dispose]: () => platform.mockRestore() };
68 +}
69
70 async function renderPicker(onPickExternal?: () => Promise<string | null>) {
71 const onOpenChange = vi.fn();
72 const onSelect = vi.fn();
86 - await act(async () =>
87 - root.render(
88 - <RegistryContext.Provider value={appAtomRegistry}>
89 - <ProjectFaviconPickerDialog
90 - cwd="/Users/me/project"
91 - environmentId={EnvironmentId.make("local")}
92 - onOpenChange={onOpenChange}
93 - {...(onPickExternal ? { onPickExternal } : {})}
94 - onSelect={onSelect}
95 - open
96 - projectName="Project"
97 - />
98 - </RegistryContext.Provider>,
99 - ),
73 + const screen = await render(
74 + <RegistryContext.Provider value={appAtomRegistry}>
75 + <ProjectFaviconPickerDialog
76 + cwd="/Users/me/project"
77 + environmentId={EnvironmentId.make("local")}
78 + onOpenChange={onOpenChange}
79 + {...(onPickExternal ? { onPickExternal } : {})}
80 + onSelect={onSelect}
81 + open
82 + projectName="Project"
83 + />
84 + </RegistryContext.Provider>,
85 );
101 - return { onOpenChange, onSelect };
86 + return Object.assign(screen, { onOpenChange, onSelect });
87 }
88 async function clickOpenInFinder() {
89 const button = [...document.querySelectorAll("button")].find((element) =>
@@ -109,14 +94,15 @@ async function clickOpenInFinder() {
94 }
95
96 it("selects an image from the native file picker", async () => {
97 + using _env = setup();
98 const onPickExternal = vi.fn().mockResolvedValue("/Users/me/Pictures/icon.png");
113 - const { onOpenChange, onSelect } = await renderPicker(onPickExternal);
99 + await using screen = await renderPicker(onPickExternal);
100
101 await clickOpenInFinder();
102
103 expect(onPickExternal).toHaveBeenCalledTimes(1);
118 - expect(onOpenChange).toHaveBeenCalledWith(false);
119 - expect(onSelect).toHaveBeenCalledWith("/Users/me/Pictures/icon.png");
104 + expect(screen.onOpenChange).toHaveBeenCalledWith(false);
105 + expect(screen.onSelect).toHaveBeenCalledWith("/Users/me/Pictures/icon.png");
106 });
107
108 it("hides the native picker for WSL project paths", () => {
@@ -125,14 +111,13 @@ it("hides the native picker for WSL project paths", () => {
111 });
112
113 it("keeps the dialog open when the native picker fails", async () => {
128 - const { onOpenChange, onSelect } = await renderPicker(
129 - vi.fn().mockRejectedValue(new Error("picker failed")),
130 - );
114 + using _env = setup();
115 + await using screen = await renderPicker(vi.fn().mockRejectedValue(new Error("picker failed")));
116
117 await clickOpenInFinder();
118
134 - expect(onOpenChange).not.toHaveBeenCalled();
135 - expect(onSelect).not.toHaveBeenCalled();
119 + expect(screen.onOpenChange).not.toHaveBeenCalled();
120 + expect(screen.onSelect).not.toHaveBeenCalled();
121 expect(toast).toHaveBeenCalledWith({
122 type: "error",
123 title: "Could not open image picker",
@@ -177,9 +162,10 @@ async function expectPreview(row: HTMLElement) {
162 }
163
164 it("loads previews asynchronously and only acquires offscreen images after scrolling", async () => {
165 + using _env = setup();
166 const paths = Array.from({ length: 40 }, (_, index) => `icons/icon-${index}.svg`);
167 addFiles(paths);
182 - const { onSelect } = await renderPicker();
168 + await using screen = await renderPicker();
169 const first = fileRow("icons/icon-0.svg");
170 const last = fileRow("icons/icon-39.svg");
171
@@ -207,13 +193,14 @@ it("loads previews asynchronously and only acquires offscreen images after scrol
193 await publishUrl("icons/icon-39.svg", imageUrl);
194 await expectPreview(last);
195 await act(async () => last.click());
210 - expect(onSelect).toHaveBeenCalledWith("icons/icon-39.svg");
196 + expect(screen.onSelect).toHaveBeenCalledWith("icons/icon-39.svg");
197 });
198
199 it("loads without IntersectionObserver and recovers a failed image when its URL changes", async () => {
214 - vi.stubGlobal("IntersectionObserver", undefined);
200 + using _env = setup();
201 + using _observer = stubGlobal("IntersectionObserver", undefined);
202 addFiles(["icons/logo.svg"]);
216 - await renderPicker();
203 + await using _screen = await renderPicker();
204 const row = fileRow("icons/logo.svg");
205
206 expect(state.createUrl).toHaveBeenCalledWith({
@@ -236,23 +223,25 @@ it("loads without IntersectionObserver and recovers a failed image when its URL
223 });
224
225 it("keeps denied previews selectable with their file icon", async () => {
239 - vi.stubGlobal("IntersectionObserver", undefined);
226 + using _env = setup();
227 + using _observer = stubGlobal("IntersectionObserver", undefined);
228 state.canReadFiles = false;
229 addFiles(["icons/private.svg"]);
242 - const { onSelect } = await renderPicker();
230 + await using screen = await renderPicker();
231 const row = fileRow("icons/private.svg");
232
233 await act(async () => row.click());
234 expect(row.querySelector("img")).toBeNull();
235 expect(row.querySelector("svg")).not.toBeNull();
236 expect(state.createUrl).not.toHaveBeenCalled();
249 - expect(onSelect).toHaveBeenCalledWith("icons/private.svg");
237 + expect(screen.onSelect).toHaveBeenCalledWith("icons/private.svg");
238 });
239
240 it("keeps the file icon until the image load is acknowledged", async () => {
253 - vi.stubGlobal("IntersectionObserver", undefined);
241 + using _env = setup();
242 + using _observer = stubGlobal("IntersectionObserver", undefined);
243 addFiles(["icons/loading.svg"]);
255 - await renderPicker();
244 + await using _screen = await renderPicker();
245 const row = fileRow("icons/loading.svg");
246 // Hold the load notification so a fast data URL has the same UI state as a slow request.
247 const holdLoad = (event: Event) => {
apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsx
+15 -32
@@ -1,27 +1,10 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { describe, expect, it, vi } from "vite-plus/test";
2 import { userEvent } from "vite-plus/test/browser";
3
4 +import { act, render } from "../../../test/render";
5 import { deriveProjectIdentity } from "../../projectIdentity";
6 import { ProjectIconPickerDialog } from "./ProjectIconPickerDialog";
7
9 -let root: Root;
10 -let container: HTMLDivElement;
11 -
12 -beforeEach(() => {
13 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
14 - container = document.createElement("div");
15 - document.body.append(container);
16 - root = createRoot(container);
17 -});
18 -
19 -afterEach(async () => {
20 - await act(async () => root.unmount());
21 - container.remove();
22 - vi.unstubAllGlobals();
23 -});
24 -
8 function button(name: string) {
9 return vi.waitFor(() => {
10 const match = [...document.querySelectorAll<HTMLElement>("button, [role='radio']")].find(
@@ -41,23 +24,22 @@ async function click(name: string) {
24 async function openPicker() {
25 const onSelect = vi.fn();
26 const onOpenChange = vi.fn();
44 - await act(async () =>
45 - root.render(
46 - <ProjectIconPickerDialog
47 - current={null}
48 - projectName="Test"
49 - open
50 - onOpenChange={onOpenChange}
51 - onSelect={onSelect}
52 - />,
53 - ),
27 + const screen = await render(
28 + <ProjectIconPickerDialog
29 + current={null}
30 + projectName="Test"
31 + open
32 + onOpenChange={onOpenChange}
33 + onSelect={onSelect}
34 + />,
35 );
55 - return { onSelect, onOpenChange };
36 + return Object.assign(screen, { onSelect, onOpenChange });
37 }
38
39 describe("ProjectIconPickerDialog", () => {
40 it("starts an automatic project on icons in its derived color and saves the picked icon", async () => {
60 - const { onSelect, onOpenChange } = await openPicker();
41 + await using screen = await openPicker();
42 + const { onSelect, onOpenChange } = screen;
43 const { color } = deriveProjectIdentity("Test");
44 expect((await button("Icons")).getAttribute("aria-pressed")).toBe("true");
45 expect(
@@ -73,7 +55,8 @@ describe("ProjectIconPickerDialog", () => {
55 });
56
57 it("saves a monogram only once the letters are letters or numbers", async () => {
76 - const { onSelect } = await openPicker();
58 + await using screen = await openPicker();
59 + const { onSelect } = screen;
60 await click("Monogram");
61 const letters = await vi.waitFor(() => {
62 const input = document.querySelector<HTMLInputElement>("#project-monogram");
apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx
+77 -73
@@ -24,11 +24,10 @@ import {
24 } from "@tanstack/react-router";
25 import * as Cause from "effect/Cause";
26 import { AsyncResult, Atom } from "effect/reactivity";
27 -import { act } from "react";
28 -import { createRoot, type Root } from "react-dom/client";
29 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
27 +import { describe, expect, it, vi } from "vite-plus/test";
28 import { page, userEvent } from "vite-plus/test/browser";
29
30 +import { act, render, type Screen } from "../../../test/render";
31 import type { Project } from "../../types";
32
33 type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
@@ -164,15 +163,8 @@ function deferred<T>() {
163 return { promise, resolve };
164 }
165
167 -let root: Root;
168 -let container: HTMLDivElement;
169 -
170 -beforeEach(() => {
171 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
166 +function setup() {
167 vi.clearAllMocks();
173 - container = document.createElement("div");
174 - document.body.append(container);
175 - root = createRoot(container);
168 state.sessions.clear();
169 for (const id of [primaryId, remoteId])
170 state.sessions.set(id, Atom.make<SessionResult>(writable()).pipe(Atom.keepAlive));
@@ -209,13 +201,7 @@ beforeEach(() => {
201 state.delete.mockResolvedValue(AsyncResult.success(undefined));
202 state.confirm.mockResolvedValue(true);
203 useComposerDraftStore.setState({ clearProjectDraftThreadId: state.clearDraft });
212 -});
213 -
214 -afterEach(async () => {
215 - await act(async () => root.unmount());
216 - container.remove();
217 - vi.unstubAllGlobals();
218 -});
204 +}
205
206 function projectKey() {
207 return buildSidebarProjectSnapshots({
@@ -255,15 +241,19 @@ async function mountPanel(search: Omit<SettingsScopeSearch, "project"> = {}) {
241 history: createMemoryHistory({ initialEntries: [`/settings/projects?${query}`] }),
242 });
243 await router.load();
258 - await act(async () =>
259 - root.render(
244 + // The panel's own route tree validates settings search params, which the default router lacks.
245 + await using stack = new AsyncDisposableStack();
246 + const screen = stack.use(
247 + await render(
248 <RegistryContext.Provider value={appAtomRegistry}>
249 <RouterProvider router={router} />
250 </RegistryContext.Provider>,
251 + { router: false },
252 ),
253 );
265 - await vi.waitFor(() => expect(nameInput()).not.toBeNull());
266 - return router;
254 + await vi.waitFor(() => expect(nameInput(screen)).not.toBeNull());
255 + stack.move();
256 + return { ...screen, router };
257 }
258
259 async function mountSettings(search: SettingsScopeSearch) {
@@ -288,21 +278,21 @@ async function mountSettings(search: SettingsScopeSearch) {
278 }),
279 });
280 await router.load();
291 - await act(async () =>
292 - root.render(
293 - <RegistryContext.Provider value={appAtomRegistry}>
294 - <RouterProvider router={router} />
295 - </RegistryContext.Provider>,
296 - ),
281 + const screen = await render(
282 + <RegistryContext.Provider value={appAtomRegistry}>
283 + <RouterProvider router={router} />
284 + </RegistryContext.Provider>,
285 + { router: false },
286 );
298 - return router;
287 + return { ...screen, router };
288 }
289
301 -const nameInput = () => container.querySelector<HTMLInputElement>('[aria-label="Project name"]')!;
302 -const removeCheckout = (root: string) =>
303 - container.querySelector<HTMLButtonElement>(`[aria-label="Remove checkout ${root}"]`)!;
304 -const removeAll = () =>
305 - [...container.querySelectorAll("button")].find((button) =>
290 +const nameInput = (screen: Screen) =>
291 + screen.container.querySelector<HTMLInputElement>('[aria-label="Project name"]')!;
292 +const removeCheckout = (screen: Screen, root: string) =>
293 + screen.container.querySelector<HTMLButtonElement>(`[aria-label="Remove checkout ${root}"]`)!;
294 +const removeAll = (screen: Screen) =>
295 + [...screen.container.querySelectorAll("button")].find((button) =>
296 button.textContent?.includes("Remove all entries"),
297 )!;
298
@@ -310,27 +300,29 @@ async function grant(id: EnvironmentId, result: SessionResult) {
300 await act(async () => appAtomRegistry.set(state.sessions.get(id)!, result));
301 }
302
313 -async function rename(title: string) {
314 - await userEvent.fill(nameInput(), title);
303 +async function rename(screen: Screen, title: string) {
304 + await userEvent.fill(nameInput(screen), title);
305 await userEvent.keyboard("{Enter}");
306 }
307
308 describe("project settings permissions", () => {
309 it("disables shared edits when any member lacks project access", async () => {
310 + setup();
311 await grant(remoteId, AsyncResult.success(session([AuthSettingsWriteScope])));
321 - await mountPanel();
312 + await using screen = await mountPanel();
313
323 - expect(nameInput().disabled).toBe(true);
324 - expect(removeAll().disabled).toBe(true);
325 - expect(container.textContent).toContain(
314 + expect(nameInput(screen).disabled).toBe(true);
315 + expect(removeAll(screen).disabled).toBe(true);
316 + expect(screen.container.textContent).toContain(
317 "Shared settings require permission to change every checkout in this group.",
318 );
319 expect(state.update).not.toHaveBeenCalled();
320 });
321
322 it("renames every member when all have project access without settings access", async () => {
332 - await mountPanel();
333 - await rename("Renamed");
323 + setup();
324 + await using screen = await mountPanel();
325 + await rename(screen, "Renamed");
326 expect(state.update.mock.calls.map(([request]) => request.environmentId)).toEqual([
327 primaryId,
328 remoteId,
@@ -339,10 +331,11 @@ describe("project settings permissions", () => {
331 });
332
333 it("stops before the next member if its grant is revoked during an earlier update", async () => {
334 + setup();
335 const firstUpdate = deferred<AsyncResult.Success<void>>();
336 state.update.mockReturnValueOnce(firstUpdate.promise);
344 - await mountPanel();
345 - await rename("Renamed");
337 + await using screen = await mountPanel();
338 + await rename(screen, "Renamed");
339 expect(state.update).toHaveBeenCalledOnce();
340
341 await grant(remoteId, AsyncResult.success(session([])));
@@ -355,19 +348,21 @@ describe("project settings permissions", () => {
348 });
349
350 it("disables removal for a checkout whose project grant is missing", async () => {
351 + setup();
352 await grant(remoteId, AsyncResult.success(session([])));
359 - await mountPanel();
360 - expect(removeCheckout("/work/remote").disabled).toBe(true);
361 - expect(removeCheckout("/work/primary").disabled).toBe(false);
353 + await using screen = await mountPanel();
354 + expect(removeCheckout(screen, "/work/remote").disabled).toBe(true);
355 + expect(removeCheckout(screen, "/work/primary").disabled).toBe(false);
356 });
357
358 it("removes a writable checkout while removal of the mixed group stays denied", async () => {
359 + setup();
360 await grant(remoteId, AsyncResult.success(session([])));
366 - const router = await mountPanel();
367 - const initialHref = router.state.location.href;
368 - expect(removeAll().disabled).toBe(true);
361 + await using screen = await mountPanel();
362 + const initialHref = screen.router.state.location.href;
363 + expect(removeAll(screen).disabled).toBe(true);
364
370 - await userEvent.click(removeCheckout("/work/primary"));
365 + await userEvent.click(removeCheckout(screen, "/work/primary"));
366 await vi.waitFor(() => expect(state.delete).toHaveBeenCalledOnce());
367 expect(state.delete).toHaveBeenCalledWith({
368 environmentId: primaryId,
@@ -375,14 +370,15 @@ describe("project settings permissions", () => {
370 });
371 await vi.waitFor(() => expect(state.releaseUploads).toHaveBeenCalledOnce());
372 expect(state.clearDraft).toHaveBeenCalledOnce();
378 - expect(router.state.location.href).toBe(initialHref);
373 + expect(screen.router.state.location.href).toBe(initialHref);
374 });
375
376 it("rechecks every removal target after confirmation before deleting or clearing drafts", async () => {
377 + setup();
378 const confirmed = deferred<boolean>();
379 state.confirm.mockReturnValueOnce(confirmed.promise);
384 - await mountPanel();
385 - await userEvent.click(removeAll());
380 + await using screen = await mountPanel();
381 + await userEvent.click(removeAll(screen));
382 expect(state.confirm).toHaveBeenCalledOnce();
383
384 await grant(remoteId, AsyncResult.success(session([])));
@@ -396,16 +392,17 @@ describe("project settings permissions", () => {
392 });
393
394 it("does not save an edit whose grant was revoked mid-edit, and recovers when restored", async () => {
399 - await mountPanel();
400 - await userEvent.fill(nameInput(), "Renamed");
395 + setup();
396 + await using screen = await mountPanel();
397 + await userEvent.fill(nameInput(screen), "Renamed");
398 await grant(remoteId, AsyncResult.success(session([])));
402 - await act(async () => nameInput().blur());
399 + await act(async () => nameInput(screen).blur());
400 expect(state.update).not.toHaveBeenCalled();
404 - expect(nameInput().disabled).toBe(true);
401 + expect(nameInput(screen).disabled).toBe(true);
402
403 await grant(remoteId, writable());
407 - expect(nameInput().disabled).toBe(false);
408 - await rename("Renamed");
404 + expect(nameInput(screen).disabled).toBe(false);
405 + await rename(screen, "Renamed");
406 expect(state.projects.map((project) => project.title)).toEqual(["Renamed", "Renamed"]);
407 });
408
@@ -420,11 +417,12 @@ describe("project settings permissions", () => {
417 ] as const)(
418 "uses the current grant while a member's session is %s",
419 async (_state, result, allowed) => {
420 + setup();
421 await grant(remoteId, result());
424 - await mountPanel();
425 - expect(nameInput().disabled).toBe(!allowed);
422 + await using screen = await mountPanel();
423 + expect(nameInput(screen).disabled).toBe(!allowed);
424 if (!allowed) return;
427 - await rename("Renamed");
425 + await rename(screen, "Renamed");
426 expect(state.update).toHaveBeenCalledTimes(2);
427 },
428 );
@@ -432,9 +430,10 @@ describe("project settings permissions", () => {
430
431 describe("project settings scope", () => {
432 it("offers project checkout environments while keeping unselected and unknown projects recoverable", async () => {
433 + setup();
434 state.projects = state.projects.filter((project) => project.environmentId === primaryId);
435 const key = projectKey();
437 - const router = await mountSettings({});
436 + await using screen = await mountSettings({});
437 const environmentMenu = () => page.getByRole("button", { name: /^Environment scope:/ });
438 const primaryOption = () => page.getByRole("menuitemradio", { name: /^primary/ });
439 const remoteOption = () => page.getByRole("menuitemradio", { name: /^remote/ });
@@ -445,7 +444,7 @@ describe("project settings scope", () => {
444 await act(async () => userEvent.keyboard("{Escape}"));
445
446 await act(async () =>
448 - router.navigate({ to: "/settings/projects", search: () => ({ project: key }) }),
447 + screen.router.navigate({ to: "/settings/projects", search: () => ({ project: key }) }),
448 );
449 await expect.element(page.getByRole("textbox", { name: "Project name" })).toBeVisible();
450 await act(async () => userEvent.click(environmentMenu()));
@@ -454,14 +453,17 @@ describe("project settings scope", () => {
453 await act(async () => userEvent.keyboard("{Escape}"));
454
455 await act(async () =>
457 - router.navigate({ to: "/settings/projects", search: () => ({ project: "removed-project" }) }),
456 + screen.router.navigate({
457 + to: "/settings/projects",
458 + search: () => ({ project: "removed-project" }),
459 + }),
460 );
461 await act(async () => userEvent.click(environmentMenu()));
462 await expect.element(primaryOption()).toBeVisible();
463 await expect.element(remoteOption()).toBeVisible();
464 await act(async () => userEvent.click(remoteOption()));
465 await vi.waitFor(() =>
464 - expect(router.state.location.search).toEqual({
466 + expect(screen.router.state.location.search).toEqual({
467 project: "removed-project",
468 machine: remoteId,
469 }),
@@ -475,9 +477,10 @@ describe("project settings scope", () => {
477 "This checkout is no longer available in the selected project and environment.",
478 ],
479 ])("recovers a stale environment link with checkout %s", async (checkout, message) => {
480 + setup();
481 state.projects = state.projects.filter((project) => project.environmentId === primaryId);
482 const key = projectKey();
480 - const router = await mountSettings({
483 + await using screen = await mountSettings({
484 project: key,
485 machine: remoteId,
486 ...(checkout ? { checkout } : {}),
@@ -495,7 +498,7 @@ describe("project settings scope", () => {
498 await expect
499 .element(page.getByRole("textbox", { name: "Project name" }))
500 .toHaveValue("Shared repo");
498 - expect(router.state.location.search).toEqual({ project: key });
501 + expect(screen.router.state.location.search).toEqual({ project: key });
502 await expect
503 .element(page.getByRole("button", { name: "Environment scope: All environments" }))
504 .toBeVisible();
@@ -507,16 +510,17 @@ describe("project settings scope", () => {
510 });
511
512 it("returns to the project overview after removal, clearing the selection but keeping the environment", async () => {
513 + setup();
514 state.projects = [state.projects[1]!];
511 - const router = await mountPanel({ machine: remoteId, checkout: "remote:/work/remote" });
512 - const removeProject = [...container.querySelectorAll("button")].find(
515 + await using screen = await mountPanel({ machine: remoteId, checkout: "remote:/work/remote" });
516 + const removeProject = [...screen.container.querySelectorAll("button")].find(
517 (button) => button.textContent === "Remove project",
518 )!;
519
520 await act(async () => userEvent.click(removeProject));
521
522 await vi.waitFor(() => {
519 - expect(router.state.location.pathname).toBe("/settings/projects");
520 - expect(router.state.location.search).toEqual({ machine: remoteId });
523 + expect(screen.router.state.location.pathname).toBe("/settings/projects");
524 + expect(screen.router.state.location.search).toEqual({ machine: remoteId });
525 });
526 });
apps/web/src/components/settings/ProviderInstanceCard.browser.test.tsx
+27 -45
@@ -1,27 +1,11 @@
1 import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
2 -import { act, type ComponentProps } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2 +import type { ComponentProps } from "react";
3 +import { describe, expect, it } from "vite-plus/test";
4 import { userEvent } from "vite-plus/test/browser";
5
6 +import { render } from "../../../test/render";
7 import { ProviderInstanceCard } from "./ProviderInstanceCard";
8
9 -let root: Root;
10 -let container: HTMLDivElement;
11 -
12 -beforeEach(() => {
13 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
14 - container = document.createElement("div");
15 - document.body.append(container);
16 - root = createRoot(container);
17 -});
18 -
19 -afterEach(async () => {
20 - await act(async () => root.unmount());
21 - container.remove();
22 - vi.unstubAllGlobals();
23 -});
24 -
9 const driver = ProviderDriverKind.make("codex");
10
11 function provider(overrides: Partial<ServerProvider>): ServerProvider {
@@ -45,50 +29,48 @@ async function renderCard(
29 liveProvider: ServerProvider,
30 mode: ComponentProps<typeof ProviderInstanceCard>["mode"],
31 ) {
48 - await act(async () =>
49 - root.render(
50 - <ProviderInstanceCard
51 - instanceId={liveProvider.instanceId}
52 - instance={{ driver }}
53 - driverOption={undefined}
54 - liveProvider={liveProvider}
55 - mode={mode}
56 - onUpdate={() => undefined}
57 - hiddenModels={[]}
58 - favoriteModels={[]}
59 - modelOrder={[]}
60 - onHiddenModelsChange={() => undefined}
61 - onFavoriteModelsChange={() => undefined}
62 - onToggleFavorite={() => undefined}
63 - onModelOrderChange={() => undefined}
64 - />,
65 - ),
32 + return render(
33 + <ProviderInstanceCard
34 + instanceId={liveProvider.instanceId}
35 + instance={{ driver }}
36 + driverOption={undefined}
37 + liveProvider={liveProvider}
38 + mode={mode}
39 + onUpdate={() => undefined}
40 + hiddenModels={[]}
41 + favoriteModels={[]}
42 + modelOrder={[]}
43 + onHiddenModelsChange={() => undefined}
44 + onFavoriteModelsChange={() => undefined}
45 + onToggleFavorite={() => undefined}
46 + onModelOrderChange={() => undefined}
47 + />,
48 );
49 }
50
51 describe("ProviderInstanceCard", () => {
52 it("hides the account email until the user reveals it, and hides it again", async () => {
71 - await renderCard(
53 + await using screen = await renderCard(
54 provider({ auth: { status: "authenticated", email: "developer@example.com" } }),
55 "editor",
56 );
75 - expect(container.textContent).toContain("Authenticated as");
76 - expect(container.textContent).not.toContain("developer@example.com");
57 + expect(screen.container.textContent).toContain("Authenticated as");
58 + expect(screen.container.textContent).not.toContain("developer@example.com");
59
78 - const toggle = container.querySelector<HTMLButtonElement>(
60 + const toggle = screen.container.querySelector<HTMLButtonElement>(
61 'button[aria-label="Toggle account email visibility"]',
62 )!;
63 await userEvent.click(toggle);
64 expect(toggle.textContent).toBe("developer@example.com");
65
66 await userEvent.click(toggle);
85 - expect(container.textContent).not.toContain("developer@example.com");
67 + expect(screen.container.textContent).not.toContain("developer@example.com");
68 });
69
70 it.each(["list", "editor"] as const)(
71 "surfaces a failed probe message in the %s",
72 async (mode) => {
91 - await renderCard(
73 + await using screen = await renderCard(
74 provider({
75 version: null,
76 status: "error",
@@ -98,8 +80,8 @@ describe("ProviderInstanceCard", () => {
80 }),
81 mode,
82 );
101 - expect(container.textContent).toContain("Unavailable");
102 - expect(container.textContent).toContain("is not a symlink");
83 + expect(screen.container.textContent).toContain("Unavailable");
84 + expect(screen.container.textContent).toContain("is not a symlink");
85 },
86 );
87 });
apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx
+58 -56
@@ -8,12 +8,12 @@ import {
8 type UnifiedSettings,
9 } from "@t3tools/contracts";
10 import { AsyncResult, type Atom } from "effect/reactivity";
11 -import { act, type ReactNode } from "react";
12 -import { createRoot, type Root } from "react-dom/client";
13 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
11 +import type { ReactNode } from "react";
12 +import { describe, expect, it, vi } from "vite-plus/test";
13 import { page, userEvent } from "vite-plus/test/browser";
14
15 import "~/index.css";
16 +import { act, render } from "../../../test/render";
17
18 const state = vi.hoisted(() => ({
19 providers: null as unknown as Atom.Writable<ReadonlyArray<ServerProvider>>,
@@ -187,31 +187,26 @@ function provider(): ServerProvider {
187 };
188 }
189
190 -let root: Root;
191 -let container: HTMLDivElement;
192 -
190 const setProviders = (providers: ReadonlyArray<ServerProvider>) =>
191 act(async () => appAtomRegistry.set(state.providers, providers));
192
196 -async function render(options?: {
193 +function panel(options?: {
194 readonly readOnly?: boolean;
195 readonly targetInstanceId?: ProviderInstanceId;
196 }) {
200 - await act(async () =>
201 - root.render(
202 - <RegistryContext.Provider value={appAtomRegistry}>
203 - <div className="@container/providers">
204 - <EnvironmentProviderSettings
205 - environmentId={environmentId}
206 - environmentLabel="Remote device"
207 - {...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly })}
208 - {...(options?.targetInstanceId === undefined
209 - ? {}
210 - : { targetInstanceId: options.targetInstanceId })}
211 - />
212 - </div>
213 - </RegistryContext.Provider>,
214 - ),
197 + return (
198 + <RegistryContext.Provider value={appAtomRegistry}>
199 + <div className="@container/providers">
200 + <EnvironmentProviderSettings
201 + environmentId={environmentId}
202 + environmentLabel="Remote device"
203 + {...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly })}
204 + {...(options?.targetInstanceId === undefined
205 + ? {}
206 + : { targetInstanceId: options.targetInstanceId })}
207 + />
208 + </div>
209 + </RegistryContext.Provider>
210 );
211 }
212
@@ -222,8 +217,7 @@ const addProvider = () => page.getByRole("button", { name: "Add provider" }).fir
217 const select = (name: string) => button(`Select ${name}`);
218 const deleteButton = (id: string) => button(`Delete instance ${id}`);
219
225 -beforeEach(async () => {
226 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
220 +async function setup() {
221 await page.viewport(1280, 900);
222 state.settings = DEFAULT_UNIFIED_SETTINGS;
223 state.canManageProviders = true;
@@ -241,20 +235,12 @@ beforeEach(async () => {
235 state.uninstall.mockReset().mockResolvedValue(AsyncResult.success({}));
236 state.acceptUrlAuth.mockReset().mockResolvedValue(AsyncResult.success({ accepted: true }));
237 await setProviders([]);
244 - container = document.createElement("div");
245 - document.body.append(container);
246 - root = createRoot(container);
247 -});
248 -
249 -afterEach(async () => {
250 - await act(async () => root.unmount());
251 - container.remove();
252 - vi.unstubAllGlobals();
253 -});
238 +}
239
240 describe("EnvironmentProviderSettings routing", () => {
241 it("shows Codex and Claude while hiding untouched disabled provider slots", async () => {
257 - await render();
242 + await setup();
243 + await using _screen = await render(panel());
244 await expect.element(select("Codex")).toBeVisible();
245 await expect.element(select("Claude")).toBeVisible();
246 for (const label of ["Cursor", "Grok", "Pi", "OpenCode", "Antigravity"]) {
@@ -263,6 +249,7 @@ describe("EnvironmentProviderSettings routing", () => {
249 });
250
251 it("keeps explicitly configured providers visible when disabled", async () => {
252 + await setup();
253 state.settings = {
254 ...DEFAULT_UNIFIED_SETTINGS,
255 providerInstances: {
@@ -272,11 +259,12 @@ describe("EnvironmentProviderSettings routing", () => {
259 },
260 },
261 };
275 - await render();
262 + await using _screen = await render(panel());
263 await expect.element(select("Grok")).toBeVisible();
264 });
265
266 it("keeps legacy provider configuration visible when disabled", async () => {
267 + await setup();
268 state.settings = {
269 ...DEFAULT_UNIFIED_SETTINGS,
270 providerInstances: {
@@ -287,12 +275,13 @@ describe("EnvironmentProviderSettings routing", () => {
275 },
276 },
277 };
290 - await render();
278 + await using _screen = await render(panel());
279 await expect.element(select("Grok")).toBeVisible();
280 });
281
282 it("reads and writes settings on the selected environment", async () => {
295 - await render();
283 + await setup();
284 + await using _screen = await render(panel());
285 await expect.element(select("Codex")).toBeVisible();
286 expect(new Set(state.readEnvironmentIds)).toEqual(new Set([environmentId]));
287 expect(new Set(state.updateEnvironmentIds)).toEqual(new Set([environmentId]));
@@ -300,8 +289,9 @@ describe("EnvironmentProviderSettings routing", () => {
289 });
290
291 it("routes refresh and provider update commands to the selected environment", async () => {
292 + await setup();
293 await setProviders([provider()]);
304 - await render();
294 + await using _screen = await render(panel());
295
296 await userEvent.click(refreshButton());
297 expect(state.refresh).toHaveBeenCalledWith({
@@ -318,6 +308,7 @@ describe("EnvironmentProviderSettings routing", () => {
308 });
309
310 it("opens the requested provider instance instead of the first provider", async () => {
311 + await setup();
312 state.settings = {
313 ...DEFAULT_UNIFIED_SETTINGS,
314 providerInstances: {
@@ -329,13 +320,14 @@ describe("EnvironmentProviderSettings routing", () => {
320 },
321 };
322 await setProviders([provider()]);
332 - await render({ targetInstanceId: customId });
323 + await using _screen = await render(panel({ targetInstanceId: customId }));
324 await expect.element(deleteButton(customId)).toBeVisible();
325 });
326
327 it("saves model favorites and visibility on the selected environment", async () => {
328 + await setup();
329 await setProviders([provider()]);
338 - await render();
330 + await using _screen = await render(panel());
331
332 await userEvent.click(button("Add Chosen to favorites"));
333 expect(state.toggleFavorite).toHaveBeenCalledExactlyOnceWith(codexId, "chosen");
@@ -348,8 +340,9 @@ describe("EnvironmentProviderSettings routing", () => {
340 });
341
342 it("does not substitute another account when the requested instance was removed", async () => {
343 + await setup();
344 await setProviders([provider()]);
352 - await render({ targetInstanceId: customId });
345 + await using _screen = await render(panel({ targetInstanceId: customId }));
346 await expect
347 .element(page.getByText("This provider instance is no longer available on this device."))
348 .toBeVisible();
@@ -357,6 +350,7 @@ describe("EnvironmentProviderSettings routing", () => {
350 });
351
352 it("keeps provider selection available while write controls are read only", async () => {
353 + await setup();
354 state.canWriteSettings = false;
355 state.settings = {
356 ...DEFAULT_UNIFIED_SETTINGS,
@@ -369,19 +363,20 @@ describe("EnvironmentProviderSettings routing", () => {
363 },
364 };
365 await setProviders([provider()]);
372 - await render({ readOnly: true });
366 + await using screen = await render(panel({ readOnly: true }));
367
368 await expect.element(page.getByRole("heading", { name: "Limited permissions" })).toBeVisible();
369 await userEvent.click(select("Work"));
370 await expect.element(deleteButton(customId)).toBeInTheDocument();
377 - expect(container.querySelector("[inert]")).not.toBeNull();
371 + expect(screen.container.querySelector("[inert]")).not.toBeNull();
372 await expect.element(refreshButton()).toBeVisible();
373 await expect.element(addProvider()).not.toBeInTheDocument();
374 });
375
376 it("keeps the editable layout interactive when not read only", async () => {
377 + await setup();
378 await setProviders([provider()]);
384 - await render();
379 + await using _screen = await render(panel());
380 await expect.element(page.getByText("Limited permissions")).not.toBeInTheDocument();
381 await expect.element(refreshButton()).toBeVisible();
382 await expect.element(addProvider()).toBeVisible();
@@ -389,28 +384,31 @@ describe("EnvironmentProviderSettings routing", () => {
384 });
385
386 it("removes an open add-instance dialog when the provider grant is revoked", async () => {
392 - await render();
387 + await setup();
388 + await using screen = await render(panel());
389 await userEvent.click(addProvider());
390 await expect.element(page.getByRole("dialog")).toBeVisible();
391
392 state.canManageProviders = false;
397 - await render({ readOnly: true });
393 + await screen.rerender(panel({ readOnly: true }));
394 await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')).toBeNull());
395 expect(state.updateSettings).not.toHaveBeenCalled();
396 });
397
398 it("keeps Advanced visible when search targets the provider health interval", async () => {
403 - await render();
399 + await setup();
400 + await using screen = await render(panel());
401 await expect.element(page.getByText("Advanced", { exact: true })).toBeVisible();
405 - expect(container.querySelector("#provider-health-check-interval")).not.toBeNull();
402 + expect(screen.container.querySelector("#provider-health-check-interval")).not.toBeNull();
403
404 state.searchTargetId = "provider-health-check-interval";
408 - await render();
405 + await screen.rerender(panel());
406 await expect.element(page.getByText("Advanced", { exact: true })).toBeVisible();
410 - expect(container.querySelector("#provider-health-check-interval")).not.toBeNull();
407 + expect(screen.container.querySelector("#provider-health-check-interval")).not.toBeNull();
408 });
409
410 it("deletes and resets provider configuration without erasing shared preferences", async () => {
411 + await setup();
412 state.settings = {
413 ...DEFAULT_UNIFIED_SETTINGS,
414 providerInstances: {
@@ -426,7 +424,7 @@ describe("EnvironmentProviderSettings routing", () => {
424 },
425 favorites: [{ provider: customId, model: "favorite" }],
426 };
429 - await render();
427 + await using _screen = await render(panel());
428 await userEvent.click(select("Work"));
429 await userEvent.click(deleteButton(customId));
430 expect(state.mutateProviderInstance).toHaveBeenLastCalledWith({
@@ -443,6 +441,7 @@ describe("EnvironmentProviderSettings routing", () => {
441 });
442
443 it("updates one provider instance without sending a stale whole map", async () => {
444 + await setup();
445 state.settings = {
446 ...DEFAULT_UNIFIED_SETTINGS,
447 providerInstances: {
@@ -453,7 +452,7 @@ describe("EnvironmentProviderSettings routing", () => {
452 },
453 },
454 };
456 - await render();
455 + await using _screen = await render(panel());
456 await userEvent.click(page.getByRole("switch", { name: "Enable Work" }).first());
457
458 expect(state.mutateProviderInstance).toHaveBeenCalledWith(
@@ -467,6 +466,7 @@ describe("EnvironmentProviderSettings routing", () => {
466 });
467
468 it("lets the server decide managed ACP cleanup after an atomic delete", async () => {
469 + await setup();
470 const firstId = ProviderInstanceId.make("acpRegistry_kilo_one");
471 const secondId = ProviderInstanceId.make("acpRegistry_kilo_two");
472 const registryInstance = (displayName: string) => ({
@@ -482,7 +482,7 @@ describe("EnvironmentProviderSettings routing", () => {
482 [secondId]: registryInstance("Kilo two"),
483 },
484 };
485 - await render();
485 + await using _screen = await render(panel());
486 await userEvent.click(select("Kilo one"));
487 await userEvent.click(deleteButton(firstId));
488
@@ -496,6 +496,7 @@ describe("EnvironmentProviderSettings routing", () => {
496 });
497
498 it("keeps the signed-in ACP account visible when login methods are no longer advertised", async () => {
499 + await setup();
500 const instanceId = ProviderInstanceId.make("acpRegistry_devin");
501 state.settings = {
502 ...DEFAULT_UNIFIED_SETTINGS,
@@ -516,11 +517,12 @@ describe("EnvironmentProviderSettings routing", () => {
517 setup: { canAuthenticate: false, canInstall: false },
518 },
519 ]);
519 - await render({ targetInstanceId: instanceId });
520 + await using _screen = await render(panel({ targetInstanceId: instanceId }));
521 await expect.element(page.getByRole("heading", { name: "Account" })).toBeVisible();
522 });
523
524 it("routes explicit ACP browser authentication consent to the selected environment", async () => {
525 + await setup();
526 const instanceId = ProviderInstanceId.make("acpRegistry_antigravity");
527 const action = {
528 elicitationId: "google-login-1",
@@ -545,7 +547,7 @@ describe("EnvironmentProviderSettings routing", () => {
547 auth: { status: "unauthenticated", action },
548 },
549 ]);
548 - await render({ targetInstanceId: instanceId });
550 + await using _screen = await render(panel({ targetInstanceId: instanceId }));
551 const link = page.getByRole("link", { name: "Continue authentication" });
552 link.element().addEventListener("click", (event) => event.preventDefault());
553 await userEvent.click(link);
apps/web/src/components/settings/ProviderSetupSection.browser.test.tsx
+126 -118
@@ -6,10 +6,10 @@ import {
6 type ProviderInstallState,
7 type ServerProvider,
8 } from "@t3tools/contracts";
9 -import { act } from "react";
10 -import { createRoot, type Root } from "react-dom/client";
9 import { page, userEvent } from "vite-plus/test/browser";
12 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
10 +import { describe, expect, it, vi } from "vite-plus/test";
11 +
12 +import { act, render } from "../../../test/render";
13
14 const setup = vi.hoisted(() => ({
15 auth: null as ProviderAuthState | null,
@@ -119,130 +119,122 @@ function deferred<T>() {
119 return { promise, resolve };
120 }
121
122 -let root: Root;
123 -let container: HTMLDivElement;
122 +interface SectionOptions {
123 + readOnly?: boolean;
124 + provider?: ServerProvider;
125 + enabled?: boolean;
126 + binaryPath?: string;
127 +}
128
125 -function renderSetup(
126 - options: {
127 - readOnly?: boolean;
128 - provider?: ServerProvider;
129 - enabled?: boolean;
130 - binaryPath?: string;
131 - } = {},
132 -) {
133 - return act(async () =>
134 - root.render(
135 - <ProviderSetupSection
136 - environmentId={environmentId}
137 - environmentLabel="Remote Google device"
138 - instanceId={instanceId}
139 - provider={options.provider ?? provider}
140 - binaryPath={options.binaryPath}
141 - enabled={options.enabled ?? true}
142 - readOnly={options.readOnly ?? false}
143 - onEnable={vi.fn()}
144 - />,
145 - ),
129 +function section(options: SectionOptions = {}) {
130 + return (
131 + <ProviderSetupSection
132 + environmentId={environmentId}
133 + environmentLabel="Remote Google device"
134 + instanceId={instanceId}
135 + provider={options.provider ?? provider}
136 + binaryPath={options.binaryPath}
137 + enabled={options.enabled ?? true}
138 + readOnly={options.readOnly ?? false}
139 + onEnable={vi.fn()}
140 + />
141 );
142 }
143
149 -function button(label: string) {
150 - return (
144 +async function renderSetup(options: SectionOptions = {}) {
145 + const screen = await render(section(options));
146 + const { container } = screen;
147 + const button = (label: string) =>
148 [...container.querySelectorAll("button")].find(
149 (element) => element.textContent === label || element.getAttribute("aria-label") === label,
153 - ) ?? null
154 - );
155 -}
156 -async function click(label: string) {
157 - const target = button(label);
158 - expect(target, `button ${label}`).not.toBeNull();
159 - expect(target!.disabled, `${label} disabled`).toBe(false);
160 - await act(async () => target!.click());
150 + ) ?? null;
151 + return Object.assign(screen, {
152 + button,
153 + async click(label: string) {
154 + const target = button(label);
155 + expect(target, `button ${label}`).not.toBeNull();
156 + expect(target!.disabled, `${label} disabled`).toBe(false);
157 + await act(async () => target!.click());
158 + },
159 + occurrences: (text: string) => (container.textContent ?? "").split(text).length - 1,
160 + callbackInput: () =>
161 + container.querySelector<HTMLInputElement>(`[id="provider-callback-${instanceId}"]`)!,
162 + });
163 }
162 -function occurrences(text: string) {
163 - return (container.textContent ?? "").split(text).length - 1;
164 +
165 +function resetSetup() {
166 + vi.clearAllMocks();
167 + setup.auth = authState();
168 + setup.installation = {
169 + driver: ProviderDriverKind.make("antigravity"),
170 + operationId: null,
171 + phase: "idle",
172 + downloadedBytes: 0,
173 + totalBytes: null,
174 + version: null,
175 + installedVersion: null,
176 + canRemove: false,
177 + message: null,
178 + };
179 + for (const command of [
180 + setup.startAuth,
181 + setup.completeAuth,
182 + setup.cancelAuth,
183 + setup.logoutAuth,
184 + setup.startInstall,
185 + setup.cancelInstall,
186 + setup.removeInstall,
187 + ]) {
188 + command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
189 + }
190 + setup.confirm.mockReset().mockResolvedValue(false);
191 }
165 -const callbackInput = () =>
166 - container.querySelector<HTMLInputElement>(`[id="provider-callback-${instanceId}"]`)!;
192
193 describe("Antigravity setup", () => {
169 - beforeEach(() => {
170 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
171 - vi.clearAllMocks();
172 - setup.auth = authState();
173 - setup.installation = {
174 - driver: ProviderDriverKind.make("antigravity"),
175 - operationId: null,
176 - phase: "idle",
177 - downloadedBytes: 0,
178 - totalBytes: null,
179 - version: null,
180 - installedVersion: null,
181 - canRemove: false,
182 - message: null,
183 - };
184 - for (const command of [
185 - setup.startAuth,
186 - setup.completeAuth,
187 - setup.cancelAuth,
188 - setup.logoutAuth,
189 - setup.startInstall,
190 - setup.cancelInstall,
191 - setup.removeInstall,
192 - ]) {
193 - command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
194 - }
195 - setup.confirm.mockReset().mockResolvedValue(false);
196 - container = document.createElement("div");
197 - document.body.append(container);
198 - root = createRoot(container);
199 - });
200 -
201 - afterEach(async () => {
202 - await act(async () => root.unmount());
203 - container.remove();
204 - vi.unstubAllGlobals();
205 - });
206 -
194 it("waits for verified auth after submitting a callback to the selected environment", async () => {
195 + resetSetup();
196 const callbackUrl = "http://127.0.0.1:5555/?state=test-only&code=test-only";
209 - await renderSetup();
210 - await act(async () => userEvent.fill(callbackInput(), callbackUrl));
211 - await click("Continue");
197 + await using screen = await renderSetup();
198 + await act(async () => userEvent.fill(screen.callbackInput(), callbackUrl));
199 + await screen.click("Continue");
200
201 expect(setup.completeAuth).toHaveBeenCalledWith({
202 environmentId,
203 input: { instanceId, flowId: "flow-1", callbackUrl },
204 });
217 - expect(occurrences("Signed in.")).toBe(0);
218 - expect(callbackInput().value).toBe("");
205 + expect(screen.occurrences("Signed in.")).toBe(0);
206 + expect(screen.callbackInput().value).toBe("");
207
208 setup.auth = authState({ phase: "verifying", authorizationUrl: null });
209 await publish();
222 - expect(occurrences("Signed in.")).toBe(0);
210 + expect(screen.occurrences("Signed in.")).toBe(0);
211 setup.auth = authState({ phase: "succeeded", authorizationUrl: null });
224 - await renderSetup({
225 - provider: { ...provider, status: "ready", auth: { status: "authenticated" } },
226 - });
227 - expect(occurrences("Signed in.")).toBe(1);
212 + await screen.rerender(
213 + section({
214 + provider: { ...provider, status: "ready", auth: { status: "authenticated" } },
215 + }),
216 + );
217 + expect(screen.occurrences("Signed in.")).toBe(1);
218 });
219
220 it("offers sign-in again when credentials expire after a completed auth flow", async () => {
221 + resetSetup();
222 setup.auth = authState({
223 phase: "succeeded",
224 authorizationUrl: null,
225 message: "Google sign-in complete.",
226 });
236 - await renderSetup({
227 + await using screen = await renderSetup({
228 provider: { ...provider, status: "ready", auth: { status: "authenticated" } },
229 });
239 - await renderSetup();
240 - expect(button("Sign in")).not.toBeNull();
241 - expect(occurrences("Signed in.")).toBe(0);
242 - expect(occurrences("Google sign-in complete.")).toBe(0);
230 + await screen.rerender(section());
231 + expect(screen.button("Sign in")).not.toBeNull();
232 + expect(screen.occurrences("Signed in.")).toBe(0);
233 + expect(screen.occurrences("Google sign-in complete.")).toBe(0);
234 });
235
236 it("does not send a callback left over from a replaced sign-in flow", async () => {
237 + resetSetup();
238 const interaction = {
239 type: "browser" as const,
240 id: "same-interaction",
@@ -251,25 +243,29 @@ describe("Antigravity setup", () => {
243 acceptsCallback: true,
244 };
245 setup.auth = authState({ interaction });
254 - await renderSetup();
246 + await using screen = await renderSetup();
247 await act(async () =>
256 - userEvent.fill(callbackInput(), "http://127.0.0.1:5555/?state=old-flow&code=test-only"),
248 + userEvent.fill(
249 + screen.callbackInput(),
250 + "http://127.0.0.1:5555/?state=old-flow&code=test-only",
251 + ),
252 );
253 setup.auth = authState({ flowId: "flow-2", interaction });
254 await publish();
260 - expect(callbackInput().value).toBe("");
261 - await act(async () => callbackInput().form!.requestSubmit());
255 + expect(screen.callbackInput().value).toBe("");
256 + await act(async () => screen.callbackInput().form!.requestSubmit());
257
258 expect(setup.completeAuth).not.toHaveBeenCalled();
259 expect(setup.authState).toHaveBeenLastCalledWith({ environmentId, input: { instanceId } });
260 });
261
262 it("coalesces repeated sign-in clicks while start is pending", async () => {
263 + resetSetup();
264 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
265 const pending = deferred<{ _tag: "Success"; value: undefined }>();
266 setup.startAuth.mockReturnValueOnce(pending.promise);
271 - await renderSetup();
272 - const signIn = button("Sign in")!;
267 + await using screen = await renderSetup();
268 + const signIn = screen.button("Sign in")!;
269 // Both clicks land before React re-renders the button as disabled.
270 await act(async () => {
271 signIn.click();
@@ -282,6 +278,7 @@ describe("Antigravity setup", () => {
278 });
279
280 it("shows a repeated runtime status message only once", async () => {
281 + resetSetup();
282 setup.installation = {
283 ...setup.installation!,
284 operationId: "install-1",
@@ -289,11 +286,12 @@ describe("Antigravity setup", () => {
286 message: "Checking the downloaded runtime.",
287 };
288
292 - await renderSetup();
293 - expect(occurrences("Checking the downloaded runtime.")).toBe(1);
289 + await using screen = await renderSetup();
290 + expect(screen.occurrences("Checking the downloaded runtime.")).toBe(1);
291 });
292
293 it("exposes download progress as a bounded progressbar only while the total is known", async () => {
294 + resetSetup();
295 const downloading = (downloadedBytes: number, totalBytes: number | null) => {
296 setup.installation = {
297 ...setup.installation!,
@@ -305,7 +303,7 @@ describe("Antigravity setup", () => {
303 return publish();
304 };
305 const progressbar = page.getByRole("progressbar", { name: "Antigravity download" });
308 - await renderSetup();
306 + await using _screen = await renderSetup();
307
308 await downloading(40_000_000, 100_000_000);
309 await expect.element(progressbar).toHaveValue(40_000_000);
@@ -317,6 +315,7 @@ describe("Antigravity setup", () => {
315 });
316
317 it("removes an owned damaged runtime only after confirmation", async () => {
318 + resetSetup();
319 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
320 setup.installation = {
321 ...setup.installation!,
@@ -324,22 +323,23 @@ describe("Antigravity setup", () => {
323 canRemove: true,
324 installedVersion: null,
325 };
327 - await renderSetup();
328 - await click("Remove downloaded runtime");
326 + await using screen = await renderSetup();
327 + await screen.click("Remove downloaded runtime");
328 expect(setup.confirm).toHaveBeenCalledOnce();
329 expect(setup.removeInstall).not.toHaveBeenCalled();
330
331 setup.confirm.mockResolvedValue(true);
333 - await click("Remove downloaded runtime");
332 + await screen.click("Remove downloaded runtime");
333 expect(setup.removeInstall).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
334 });
335
336 it.each([true, false])(
337 "can sign out a verified account when its instance is enabled=%s",
338 async (enabled) => {
339 + resetSetup();
340 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
341 setup.confirm.mockResolvedValue(true);
342 - await renderSetup({
342 + await using screen = await renderSetup({
343 enabled,
344 provider: {
345 ...provider,
@@ -349,7 +349,7 @@ describe("Antigravity setup", () => {
349 auth: { status: "authenticated" },
350 },
351 });
352 - await click("Sign out");
352 + await screen.click("Sign out");
353 expect(setup.logoutAuth).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
354 },
355 );
@@ -357,44 +357,52 @@ describe("Antigravity setup", () => {
357 it.each(["unauthenticated", "unknown"] as const)(
358 "does not offer sign-out for an unverified %s account",
359 async (status) => {
360 + resetSetup();
361 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
361 - await renderSetup({
362 + await using screen = await renderSetup({
363 provider: { ...provider, auth: { status, canLogout: true } },
364 });
364 - expect(button("Sign in")).not.toBeNull();
365 - expect(button("Sign out")).toBeNull();
366 - expect(button("Change account")).toBeNull();
365 + expect(screen.button("Sign in")).not.toBeNull();
366 + expect(screen.button("Sign out")).toBeNull();
367 + expect(screen.button("Change account")).toBeNull();
368 },
369 );
370
371 it("offers account actions after verified login when discovery cannot identify auth", async () => {
372 + resetSetup();
373 setup.auth = authState({ phase: "succeeded", flowId: null, authorizationUrl: null });
372 - await renderSetup({ provider: { ...provider, auth: { status: "unknown" } } });
373 - expect(button("Change account")).not.toBeNull();
374 - expect(button("Sign out")).not.toBeNull();
375 - expect(button("Sign in")).toBeNull();
374 + await using screen = await renderSetup({
375 + provider: { ...provider, auth: { status: "unknown" } },
376 + });
377 + expect(screen.button("Change account")).not.toBeNull();
378 + expect(screen.button("Sign out")).not.toBeNull();
379 + expect(screen.button("Sign in")).toBeNull();
380 });
381
382 it("does not let a shared managed install hide an invalid custom binary path", async () => {
383 + resetSetup();
384 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
385 setup.installation = {
386 ...setup.installation!,
387 installedVersion: "test-version",
388 canRemove: true,
389 };
385 - await renderSetup({
390 + await using screen = await renderSetup({
391 provider: { ...provider, installed: false },
392 binaryPath: "/missing/antigravity",
393 });
389 - expect(button("Sign in")?.disabled).toBe(true);
394 + expect(screen.button("Sign in")?.disabled).toBe(true);
395 expect(setup.startAuth).not.toHaveBeenCalled();
396 });
397
398 it.each(["read-only", "older-server"] as const)(
399 "does not open private setup subscriptions for a %s view",
400 async (mode) => {
401 + resetSetup();
402 const { setup: _setup, ...olderProvider } = provider;
397 - await renderSetup(mode === "read-only" ? { readOnly: true } : { provider: olderProvider });
403 + await using _screen = await renderSetup(
404 + mode === "read-only" ? { readOnly: true } : { provider: olderProvider },
405 + );
406 expect(setup.authState).not.toHaveBeenCalled();
407 expect(setup.installState).not.toHaveBeenCalled();
408 expect(setup.startAuth).not.toHaveBeenCalled();
apps/web/src/components/settings/SecretInput.browser.test.tsx
+18 -35
@@ -1,64 +1,47 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { describe, expect, it, vi } from "vite-plus/test";
2 import { userEvent } from "vite-plus/test/browser";
3
4 +import { render, type Screen } from "../../../test/render";
5 import { SecretInput } from "./SecretInput";
6
8 -let root: Root;
9 -let container: HTMLDivElement;
7 +const input = (screen: Screen) => screen.container.querySelector("input")!;
8
11 -beforeEach(() => {
12 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
13 - container = document.createElement("div");
14 - document.body.append(container);
15 - root = createRoot(container);
16 -});
17 -
18 -afterEach(async () => {
19 - await act(async () => root.unmount());
20 - container.remove();
21 - vi.unstubAllGlobals();
22 -});
23 -
24 -const input = () => container.querySelector("input")!;
25 -
26 -async function edit(value: string) {
27 - await userEvent.clear(input());
28 - if (value) await userEvent.type(input(), value);
9 +async function edit(screen: Screen, value: string) {
10 + await userEvent.clear(input(screen));
11 + if (value) await userEvent.type(input(screen), value);
12 await userEvent.click(document.body);
13 }
14
15 describe("SecretInput", () => {
16 it("preserves a configured secret on empty edits and commits a replacement", async () => {
17 const onCommit = vi.fn();
35 - await act(async () => root.render(<SecretInput configured value="" onCommit={onCommit} />));
36 - expect(input().type).toBe("password");
18 + await using screen = await render(<SecretInput configured value="" onCommit={onCommit} />);
19 + expect(input(screen).type).toBe("password");
20
38 - await userEvent.click(input());
21 + await userEvent.click(input(screen));
22 await userEvent.click(document.body);
23 expect(onCommit).not.toHaveBeenCalled();
24
42 - await edit("replacement");
25 + await edit(screen, "replacement");
26 expect(onCommit).toHaveBeenCalledExactlyOnceWith("replacement");
44 - expect(input().value).toBe("");
27 + expect(input(screen).value).toBe("");
28 });
29
30 it("allows clearing an unsaved draft", async () => {
31 const onCommit = vi.fn();
49 - await act(async () => root.render(<SecretInput value="draft" onCommit={onCommit} />));
50 - await edit("");
32 + await using screen = await render(<SecretInput value="draft" onCommit={onCommit} />);
33 + await edit(screen, "");
34 expect(onCommit).toHaveBeenCalledExactlyOnceWith("");
35 });
36
37 it("keeps an in-progress replacement when settings refresh", async () => {
38 const onCommit = vi.fn();
56 - const render = () => root.render(<SecretInput configured value="" onCommit={onCommit} />);
57 - await act(async () => render());
39 + const ui = () => <SecretInput configured value="" onCommit={onCommit} />;
40 + await using screen = await render(ui());
41
59 - await userEvent.type(input(), "replacement");
60 - await act(async () => render());
61 - expect(input().value).toBe("replacement");
42 + await userEvent.type(input(screen), "replacement");
43 + await screen.rerender(ui());
44 + expect(input(screen).value).toBe("replacement");
45
46 await userEvent.keyboard("{Enter}");
47 expect(onCommit).toHaveBeenCalledExactlyOnceWith("replacement");
apps/web/src/components/settings/SettingsPanels.restore.browser.test.tsx
+27 -25
@@ -1,7 +1,7 @@
1 +import { useEffect } from "react";
2 +import { act, render } from "../../../test/render";
3 import { DEFAULT_UNIFIED_SETTINGS, type UnifiedSettings } from "@t3tools/contracts";
2 -import { act, useEffect } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4 +import { describe, expect, it, vi } from "vite-plus/test";
5
6 const state = vi.hoisted(() => ({
7 settings: null as UnifiedSettings | null,
@@ -37,30 +37,28 @@ vi.mock(import("../../localApi"), async (original) => ({
37
38 import { useSettingsRestore } from "./SettingsPanels";
39
40 -let root: Root;
41 -let restore: ReturnType<typeof useSettingsRestore>;
42 -
43 -function Probe() {
44 - const result = useSettingsRestore();
45 - useEffect(() => {
46 - restore = result;
47 - });
48 - return null;
40 +async function renderRestore() {
41 + let restore!: ReturnType<typeof useSettingsRestore>;
42 + function Probe() {
43 + const result = useSettingsRestore();
44 + useEffect(() => {
45 + restore = result;
46 + });
47 + return null;
48 + }
49 + const screen = await render(<Probe />);
50 + return {
51 + ...screen,
52 + get restore() {
53 + return restore;
54 + },
55 + };
56 }
50 -
51 -beforeEach(async () => {
52 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
57 +function setup() {
58 vi.clearAllMocks();
59 state.settings = { ...DEFAULT_UNIFIED_SETTINGS };
60 state.confirm.mockResolvedValue(true);
56 - root = createRoot(document.createElement("div"));
57 -});
58 -afterEach(async () => {
59 - await act(async () => root.unmount());
60 - vi.unstubAllGlobals();
61 -});
62 -
63 -const render = () => act(async () => root.render(<Probe />));
61 +}
62
63 describe("restoring V2 settings", () => {
64 it.each([
@@ -68,8 +66,10 @@ describe("restoring V2 settings", () => {
66 ["autoResumeLimitedThreads", "Auto-resume limited threads"],
67 ["snoozeLimitedThreads", "Snooze limited threads"],
68 ] as const)("restores %s when it is the only changed setting", async (key, label) => {
69 + setup();
70 state.settings = { ...DEFAULT_UNIFIED_SETTINGS, [key]: true };
72 - await render();
71 + await using screen = await renderRestore();
72 + const { restore } = screen;
73
74 expect(restore.changedSettingLabels).toEqual([label]);
75 await act(() => restore.restoreDefaults());
@@ -80,9 +80,11 @@ describe("restoring V2 settings", () => {
80 });
81
82 it("does not reset settings after cancellation", async () => {
83 + setup();
84 state.settings = { ...DEFAULT_UNIFIED_SETTINGS, autoResumeLimitedThreads: true };
85 state.confirm.mockResolvedValue(false);
85 - await render();
86 + await using screen = await renderRestore();
87 + const { restore } = screen;
88
89 await act(() => restore.restoreDefaults());
90
apps/web/src/components/settings/SnapShotSettings.browser.test.tsx
+92 -52
@@ -1,12 +1,11 @@
1 +import { act, render } from "../../../test/render";
2 import {
3 DEFAULT_CLIENT_SETTINGS,
4 type ClientSettingsPatch,
5 type DesktopSnapShotState,
6 } from "@t3tools/contracts";
6 -import { act } from "react";
7 -import { createRoot, type Root } from "react-dom/client";
7 import { userEvent } from "vite-plus/test/browser";
9 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
8 +import { expect, it, vi } from "vite-plus/test";
9
10 const bridge = vi.hoisted(() => ({
11 getSnapShotState: vi.fn<() => Promise<DesktopSnapShotState>>(),
@@ -62,39 +61,49 @@ import { readSnapShotSetupResume } from "../../lib/snapShotSetupResume";
61 import { SnapShotSettings } from "./SnapShotSettings";
62
63 let state: DesktopSnapShotState;
65 -let root: Root;
66 -let container: HTMLDivElement;
67 -
64 async function mount() {
69 - root = createRoot(container);
70 - await act(async () => root.render(<SnapShotSettings />));
65 + await using stack = new AsyncDisposableStack();
66 + const screen = stack.use(await render(<SnapShotSettings />));
67 + const { container } = screen;
68 await vi.waitFor(() => expect(bridge.getSnapShotState).toHaveBeenCalled());
69 await act(async () => {});
70 + const dialog = () => document.querySelector<HTMLElement>('[role="dialog"]');
71 + const scope = () => dialog() ?? container;
72 + function button(label: string, within: ParentNode = scope()) {
73 + return (
74 + [...within.querySelectorAll("button")].find(
75 + (element) => element.textContent?.trim() === label,
76 + ) ?? null
77 + );
78 + }
79 + async function click(label: string) {
80 + const target = button(label);
81 + expect(target, `button ${label}`).not.toBeNull();
82 + await act(async () => target!.click());
83 + }
84 + const recorder = () => scope().querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;
85 + const toggle = (label: string) =>
86 + container.querySelector<HTMLButtonElement>(`[role="switch"][aria-label="${label}"]`)!;
87 + const stepTitle = () => dialog()?.querySelector("h3")?.textContent;
88 +
89 + const environment = stack.move();
90 + return {
91 + ...screen,
92 + dialog,
93 + button,
94 + click,
95 + recorder,
96 + toggle,
97 + stepTitle,
98 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
99 + };
100 }
74 -const dialog = () => document.querySelector<HTMLElement>('[role="dialog"]');
75 -const scope = () => dialog() ?? container;
76 -function button(label: string, within: ParentNode = scope()) {
77 - return (
78 - [...within.querySelectorAll("button")].find(
79 - (element) => element.textContent?.trim() === label,
80 - ) ?? null
81 - );
82 -}
83 -async function click(label: string) {
84 - const target = button(label);
85 - expect(target, `button ${label}`).not.toBeNull();
86 - await act(async () => target!.click());
87 -}
88 -const recorder = () => scope().querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;
89 -const toggle = (label: string) =>
90 - container.querySelector<HTMLButtonElement>(`[role="switch"][aria-label="${label}"]`)!;
91 -const stepTitle = () => dialog()?.querySelector("h3")?.textContent;
101
93 -beforeEach(() => {
94 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
102 +function setup() {
103 vi.clearAllMocks();
104 + const storage = new Map(Object.entries(localStorage));
105 localStorage.clear();
97 - Object.defineProperty(navigator, "platform", { configurable: true, get: () => "Linux" });
106 +
107 settingsStore.current = { ...DEFAULT_CLIENT_SETTINGS, snapShotEnabled: true };
108 state = {
109 mode: "portal",
@@ -115,22 +124,22 @@ beforeEach(() => {
124 state = { ...state, shortcut: patch.snapShotShortcut ?? state.shortcut };
125 settingsStore.set({ ...settingsStore.current, ...patch });
126 });
118 - container = document.createElement("div");
119 - document.body.append(container);
120 -});
121 -afterEach(async () => {
122 - await act(async () => root.unmount());
123 - container.remove();
124 - localStorage.clear();
125 - Reflect.deleteProperty(navigator, "platform");
126 - vi.unstubAllGlobals();
127 -});
127 + return {
128 + [Symbol.dispose]() {
129 + localStorage.clear();
130 + for (const [key, value] of storage) localStorage.setItem(key, value);
131 + },
132 + };
133 +}
134
135 it.each(["niri", "hyprland"] as const)(
136 "reopens %s setup at Shortcut without reading config or expanding Settings",
137 async (desktop) => {
138 + using _state = setup();
139 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
140 state = { ...state, linuxBackend: desktop };
133 - await mount();
141 + await using screen = await mount();
142 + const { container, dialog, button, click, stepTitle } = screen;
143 expect(dialog()).toBeNull();
144 expect(button("Review changes", container)).toBeNull();
145 await click("Change shortcut");
@@ -146,7 +155,10 @@ it.each(["niri", "hyprland"] as const)(
155 );
156
157 it("returns to Access if the Hyprland helper needs attention before changing keys", async () => {
149 - await mount();
158 + using _state = setup();
159 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
160 + await using screen = await mount();
161 + const { button, click, stepTitle } = screen;
162 state = { ...state, hyprlandHelper: { status: "not-installed", message: "Install helper" } };
163 await click("Change shortcut");
164 expect(stepTitle()).toBe("Allow snapshots");
@@ -157,6 +169,8 @@ it("returns to Access if the Hyprland helper needs attention before changing key
169 it.each(["direct", "gnome-extension", "kde"] as const)(
170 "keeps %s shortcut recording and saving inline",
171 async (backend) => {
172 + using _state = setup();
173 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
174 state = {
175 ...state,
176 mode: backend === "direct" ? "direct" : "portal",
@@ -165,7 +179,8 @@ it.each(["direct", "gnome-extension", "kde"] as const)(
179 shortcutLabel: backend === "direct" ? undefined : "Press <Shift><Control>2",
180 shortcutMessage: backend === "direct" ? null : "Desktop shortcut: Press <Shift><Control>2",
181 };
168 - await mount();
182 + await using screen = await mount();
183 + const { container, dialog, click, recorder } = screen;
184 if (backend !== "direct") {
185 expect(recorder().getAttribute("aria-label")).toBe(
186 "Record snapshot shortcut, currently Ctrl+Shift+2",
@@ -188,9 +203,12 @@ it.each(["direct", "gnome-extension", "kde"] as const)(
203 );
204
205 it("turns capture on directly on Windows without opening setup", async () => {
206 + using _state = setup();
207 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
208 settingsStore.current = { ...settingsStore.current, snapShotEnabled: false };
209 state = { ...state, mode: "direct", linuxBackend: undefined, windows: true };
193 - await mount();
210 + await using screen = await mount();
211 + const { dialog, button, toggle } = screen;
212 await act(async () => toggle("Enable snapshots").click());
213 expect(settingsStore.update).toHaveBeenCalledWith({ snapShotEnabled: true });
214 expect(toggle("Enable snapshots").getAttribute("aria-checked")).toBe("true");
@@ -199,6 +217,8 @@ it("turns capture on directly on Windows without opening setup", async () => {
217 });
218
219 it("keeps the approved desktop shortcut when recording is cancelled in setup", async () => {
220 + using _state = setup();
221 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
222 state = {
223 ...state,
224 linuxBackend: "gnome-extension",
@@ -206,7 +226,8 @@ it("keeps the approved desktop shortcut when recording is cancelled in setup", a
226 shortcutRegistered: true,
227 shortcutLabel: "Press <Control><Alt>8",
228 };
209 - await mount();
229 + await using screen = await mount();
230 + const { dialog, click, recorder } = screen;
231 await click("Manage capture");
232 expect(dialog()).not.toBeNull();
233 expect(recorder().getAttribute("aria-label")).toBe(
@@ -245,8 +266,11 @@ function usePortalShortcut(shortcutCanRetry: boolean) {
266 }
267
268 it("keeps older portal shortcuts editable without offering unsupported permissions", async () => {
269 + using _state = setup();
270 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
271 usePortalShortcut(false);
249 - await mount();
272 + await using screen = await mount();
273 + const { button, recorder } = screen;
274 expect(button("Shortcut permissions")).toBeNull();
275 expect(bridge.setupSnapShot).not.toHaveBeenCalled();
276 await act(async () => userEvent.click(recorder()));
@@ -254,9 +278,12 @@ it("keeps older portal shortcuts editable without offering unsupported permissio
278 });
279
280 it("shows permission errors once in a toast and allows retrying", async () => {
281 + using _state = setup();
282 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
283 usePortalShortcut(true);
284 bridge.setupSnapShot.mockRejectedValueOnce(new Error("The desktop service disconnected."));
259 - await mount();
285 + await using screen = await mount();
286 + const { container, click } = screen;
287 await click("Shortcut permissions");
288 expect(toast).toHaveBeenCalledExactlyOnceWith({
289 type: "error",
@@ -270,9 +297,12 @@ it("shows permission errors once in a toast and allows retrying", async () => {
297 });
298
299 it("keeps a failed preference unchanged and reports the save error in a toast", async () => {
300 + using _state = setup();
301 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
302 usePortalShortcut(true);
303 settingsStore.update.mockRejectedValueOnce(new Error("The settings file is read-only."));
275 - await mount();
304 + await using screen = await mount();
305 + const { toggle } = screen;
306 const flash = () => toggle("Flash captured window");
307 expect(flash().getAttribute("aria-checked")).toBe("true");
308 await act(async () => flash().click());
@@ -288,9 +318,12 @@ it("keeps a failed preference unchanged and reports the save error in a toast",
318 });
319
320 it("keeps setup errors in the wizard and does not toast them after closing it", async () => {
321 + using _state = setup();
322 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
323 usePortalShortcut(true);
324 state = { ...state, shortcutRegistered: false };
293 - await mount();
325 + await using screen = await mount();
326 + const { dialog, click, stepTitle } = screen;
327 await click("Manage capture");
328 expect(stepTitle()).toBe("Choose your shortcut");
329 bridge.setupSnapShot.mockRejectedValueOnce(new Error("The desktop service disconnected."));
@@ -322,8 +355,11 @@ function useMacPermissions(granted: boolean) {
355 it.each([false, true])(
356 "resumes macOS permission setup after restart and clears it on close, completed=%s",
357 async (completed) => {
358 + using _state = setup();
359 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
360 useMacPermissions(false);
326 - await mount();
361 + await using screen = await mount();
362 + let { dialog, button, click, toggle, stepTitle } = screen;
363 await act(async () => toggle("Enable snapshots").click());
364 expect(stepTitle()).toBe("Allow snapshots");
365 bridge.setupSnapShot.mockImplementationOnce(async () => {
@@ -333,10 +369,11 @@ it.each([false, true])(
369 expect(bridge.setupSnapShot).toHaveBeenCalledWith("allow-screen-recording");
370
371 // macOS quits the app from its permission prompt; the next launch resumes setup.
336 - await act(async () => root.unmount());
372 + await screen.unmount();
373 state = { ...state, shortcutRegistered: true };
374 state = { ...state, macPermissions: { screenRecording: true, accessibility: true } };
339 - await mount();
375 + await using resumed = await mount();
376 + ({ dialog, button, click, toggle, stepTitle } = resumed);
377 expect(stepTitle()).toBe("Allow snapshots");
378 expect(button("Finish later")).not.toBeNull();
379 if (completed) {
@@ -352,8 +389,11 @@ it.each([false, true])(
389 );
390
391 it("requires a successful macOS test capture before enabling and allows retry", async () => {
392 + using _state = setup();
393 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
394 useMacPermissions(true);
356 - await mount();
395 + await using screen = await mount();
396 + const { dialog, click, toggle, stepTitle } = screen;
397 await act(async () => toggle("Enable snapshots").click());
398 bridge.setupSnapShot.mockRejectedValueOnce(new Error("Capture was denied"));
399 await click("Test capture and continue");
apps/web/src/components/settings/SourceControlWritingSettings.browser.test.tsx
+20 -28
@@ -1,7 +1,7 @@
1 +import { render } from "../../../test/render";
2 import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
2 -import { act, StrictMode, type ReactNode } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 +import { StrictMode, type ReactNode } from "react";
4 +import { describe, expect, it, vi } from "vite-plus/test";
5 import { page, userEvent } from "vite-plus/test/browser";
6
7 import "../../index.css";
@@ -61,9 +61,6 @@ vi.mock(import("./settingsLayout"), async (original) => ({
61
62 import { SourceControlWritingSettingsSection } from "./SourceControlWritingSettings";
63
64 -let root: Root;
65 -let container: HTMLDivElement;
66 -
64 const resetButton = (label: string) =>
65 page.getByRole("button", { name: `Reset ${label} to default` });
66 const writeForAll = () => page.getByRole("button", { name: "Write custom instructions for all" });
@@ -73,17 +70,13 @@ const bulkEditor = () =>
70 name: "Custom source control instructions for all selected environments",
71 });
72
76 -async function render() {
77 - await act(async () =>
78 - root.render(
79 - <StrictMode>
80 - <SourceControlWritingSettingsSection />
81 - </StrictMode>,
82 - ),
83 - );
84 -}
73 +const content = () => (
74 + <StrictMode>
75 + <SourceControlWritingSettingsSection />
76 + </StrictMode>
77 +);
78
86 -beforeEach(async () => {
79 +async function setup() {
80 state.styles = [
81 {
82 ...DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle,
@@ -98,23 +91,17 @@ beforeEach(async () => {
91 followChangeRequestTemplates: false,
92 },
93 ];
94 + const screen = await render(content());
95 state.updateSettings.mockReset().mockImplementation((patch) => {
96 state.styles = state.styles.map((style) => ({ ...style, ...patch.sourceControlWritingStyle }));
103 - void render();
97 + void screen.rerender(content());
98 });
105 - container = document.createElement("div");
106 - document.body.append(container);
107 - root = createRoot(container);
108 - await render();
109 -});
110 -
111 -afterEach(async () => {
112 - await act(async () => root.unmount());
113 - container.remove();
114 -});
99 + return screen;
100 +}
101
102 describe("mixed source control instructions", () => {
103 it("resets mixed template preferences without replacing each environment's instructions", async () => {
104 + await using _screen = await setup();
105 const initialInstructions = state.styles.map(({ mode, customInstructions }) => ({
106 mode,
107 customInstructions,
@@ -133,8 +120,9 @@ describe("mixed source control instructions", () => {
120 });
121
122 it("resets every environment even when the representative already has default instructions", async () => {
123 + await using screen = await setup();
124 state.styles[0] = { ...DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle };
137 - await render();
125 + await screen.rerender(content());
126
127 await userEvent.click(resetButton("source control writing style"));
128
@@ -151,6 +139,7 @@ describe("mixed source control instructions", () => {
139 });
140
141 it("does not write an untouched bulk draft", async () => {
142 + await using _screen = await setup();
143 const initialStyles = state.styles;
144 await userEvent.click(writeForAll());
145 await expect.element(bulkEditor()).toHaveValue("");
@@ -161,6 +150,7 @@ describe("mixed source control instructions", () => {
150 });
151
152 it("applies edited instructions to every selected environment", async () => {
153 + await using _screen = await setup();
154 await userEvent.click(writeForAll());
155 await userEvent.fill(bulkEditor(), " Keep titles concise. ");
156 await expect.element(applyToAll()).toBeEnabled();
@@ -175,6 +165,7 @@ describe("mixed source control instructions", () => {
165 });
166
167 it("allows an intentional clear after editing", async () => {
168 + await using _screen = await setup();
169 await userEvent.click(writeForAll());
170 await userEvent.fill(bulkEditor(), "Temporary instructions");
171 await userEvent.clear(bulkEditor());
@@ -186,6 +177,7 @@ describe("mixed source control instructions", () => {
177 });
178
179 it("shows the plain editor once instructions agree, even while templates differ", async () => {
180 + await using _screen = await setup();
181 await userEvent.click(writeForAll());
182 await userEvent.fill(bulkEditor(), "Shared instructions");
183 await userEvent.click(applyToAll());
apps/web/src/components/settings/StorageSettings.browser.test.tsx
+21 -29
@@ -1,3 +1,4 @@
1 +import { act, render } from "../../../test/render";
2 import { RegistryProvider } from "@effect/atom-react";
3 import {
4 DEFAULT_SERVER_SETTINGS,
@@ -5,9 +6,8 @@ import {
6 ThreadId,
7 type StorageCleanupReport,
8 } from "@t3tools/contracts";
8 -import { act, type ReactNode } from "react";
9 -import { createRoot, type Root } from "react-dom/client";
10 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
9 +import { type ReactNode } from "react";
10 +import { expect, it, vi } from "vite-plus/test";
11 import { page } from "vite-plus/test/browser";
12
13 const state = vi.hoisted(() => ({
@@ -92,10 +92,7 @@ vi.mock(import("../ui/toast"), async (original) => {
92
93 import { StorageSettingsPanel } from "./StorageSettings";
94
95 -let root: Root;
96 -let container: HTMLDivElement;
97 -
98 -beforeEach(() => {
95 +function setup() {
96 state.settings = {
97 ...DEFAULT_SERVER_SETTINGS,
98 storageCleanup: {
@@ -112,32 +109,22 @@ beforeEach(() => {
109 };
110 state.report = null;
111 state.run.mockReset();
115 - container = document.createElement("div");
116 - document.body.append(container);
117 - root = createRoot(container);
118 -});
119 -
120 -afterEach(async () => {
121 - await act(async () => root.unmount());
122 - container.remove();
123 -});
112 +}
113
125 -async function render() {
126 - await act(async () =>
127 - root.render(
128 - <RegistryProvider>
129 - <StorageSettingsPanel />
130 - </RegistryProvider>,
131 - ),
132 - );
133 - return Array.from(container.querySelectorAll("button")).find(
114 +const panel = () => (
115 + <RegistryProvider>
116 + <StorageSettingsPanel />
117 + </RegistryProvider>
118 +);
119 +const deleteButton = (container: HTMLElement) =>
120 + Array.from(container.querySelectorAll("button")).find(
121 (button) => button.textContent === "Delete now",
122 )!;
136 -}
123
124 it.each(["machine-wide immediate", "project custom"])(
125 "runs cleanup when only %s settled retention is enabled",
126 async (scope) => {
127 + setup();
128 if (scope === "machine-wide immediate") {
129 state.settings = {
130 ...state.settings,
@@ -167,7 +154,8 @@ it.each(["machine-wide immediate", "project custom"])(
154 };
155 let complete!: (result: { _tag: "Success"; value: StorageCleanupReport }) => void;
156 state.run.mockImplementation(() => new Promise((resolve) => (complete = resolve)));
170 - const button = await render();
157 + await using screen = await render(panel());
158 + const button = deleteButton(screen.container);
159
160 expect(button.disabled).toBe(false);
161 await act(async () => button.click());
@@ -182,7 +170,9 @@ it.each(["machine-wide immediate", "project custom"])(
170 );
171
172 it("keeps cleanup disabled when settled retention and all other rules are off", async () => {
185 - const button = await render();
173 + setup();
174 + await using screen = await render(panel());
175 + const button = deleteButton(screen.container);
176
177 expect(button.disabled).toBe(true);
178 await act(async () => button.click());
@@ -190,6 +180,7 @@ it("keeps cleanup disabled when settled retention and all other rules are off",
180 });
181
182 it("shows orphan sizes and identifies failed worktrees with one connected machine", async () => {
183 + setup();
184 state.settings = {
185 ...state.settings,
186 storageCleanup: { ...state.settings.storageCleanup, worktreeSettledAfterDays: 0 },
@@ -226,7 +217,8 @@ it("shows orphan sizes and identifies failed worktrees with one connected machin
217 omittedCount: 0,
218 bytesFreed: 0,
219 };
229 - await render();
220 + await using screen = await render(panel());
221 + const { container } = screen;
222 const lastRun = Array.from(container.querySelectorAll("button")).find((button) =>
223 button.textContent?.includes("Last run"),
224 )!;
apps/web/src/components/settings/TelemetryExportSettings.browser.test.tsx
+12 -24
@@ -1,7 +1,6 @@
1 +import { render } from "../../../test/render";
2 import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
2 -import { act } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 +import { describe, expect, it, vi } from "vite-plus/test";
4 import { userEvent } from "vite-plus/test/browser";
5
6 const { state, updateSettings } = vi.hoisted(() => ({
@@ -46,40 +45,29 @@ vi.mock(import("./useScopedSettings"), async (original) => ({
45
46 import { TelemetryExportSettings } from "./TelemetryExportSettings";
47
49 -let root: Root;
50 -let container: HTMLDivElement;
51 -beforeEach(() => {
52 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
53 - container = document.createElement("div");
54 - document.body.append(container);
55 - root = createRoot(container);
56 -});
57 -
58 -afterEach(async () => {
59 - await act(async () => root.unmount());
60 - container.remove();
48 +function setup() {
49 updateSettings.mockClear();
62 - vi.unstubAllGlobals();
63 -});
64 -
65 -const field = (id: string) => container.querySelector<HTMLInputElement>(`#${id}`)!;
66 -async function replace(id: string, value: string) {
67 - await userEvent.clear(field(id));
68 - await userEvent.type(field(id), value);
50 }
51
52 describe("TelemetryExportSettings", () => {
53 it("does not resend a field the user restored after another client changed it", async () => {
54 + setup();
55 state.observability = {
56 ...DEFAULT_SERVER_SETTINGS.observability,
57 otlpTracesUrl: "http://old/v1/traces",
58 };
77 - await act(async () => root.render(<TelemetryExportSettings />));
59 + await using screen = await render(<TelemetryExportSettings />);
60
61 + const { container } = screen;
62 + const field = (id: string) => container.querySelector<HTMLInputElement>(`#${id}`)!;
63 + async function replace(id: string, value: string) {
64 + await userEvent.clear(field(id));
65 + await userEvent.type(field(id), value);
66 + }
67 await replace("otlpTracesUrl", "http://draft/v1/traces");
68 await replace("otlpTracesUrl", "http://old/v1/traces");
69 state.observability = { ...state.observability, otlpTracesUrl: "http://other/v1/traces" };
82 - await act(async () => root.render(<TelemetryExportSettings />));
70 + await screen.rerender(<TelemetryExportSettings />);
71 await replace("otlpMetricsUrl", "http://new/v1/metrics");
72 const save = [...container.querySelectorAll("button")].find(
73 (button) => button.textContent === "Save",
apps/web/src/components/settings/ThemeEditorHost.browser.test.tsx
+31 -29
@@ -1,6 +1,5 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { act, render } from "../../../test/render";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3
4 import {
5 installCustomTheme,
@@ -41,8 +40,6 @@ import { ThemeEditorHost } from "./ThemeEditorHost";
40 import { useThemeEditorStore } from "./themeEditorStore";
41
42 type Field = "editingTheme" | "seedTheme";
44 -let root: Root;
45 -let container: HTMLDivElement;
43
44 function install(id: string) {
45 return installCustomTheme(
@@ -65,7 +62,7 @@ function open(field: Field, themeId: string) {
62 }),
63 );
64 }
68 -async function shown(field: Field) {
65 +async function shown(container: HTMLElement, field: Field) {
66 await vi.waitFor(() => expect(container.querySelector("dl")).not.toBeNull(), {
67 timeout: 5_000,
68 });
@@ -73,66 +70,71 @@ async function shown(field: Field) {
70 return terms.find((term) => term.textContent === field)?.nextElementSibling?.textContent;
71 }
72
76 -// The host lazy-loads the panel; load it once so the first test does not race the import.
77 -beforeAll(() => import("./ThemeEditorPanel"));
78 -
79 -beforeEach(async () => {
80 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
73 +async function setup() {
74 + await import("./ThemeEditorPanel");
75 + const storage = new Map(Object.entries(localStorage));
76 + const session = useThemeEditorStore.getState().session;
77 localStorage.clear();
78 invalidateCustomThemes();
79 useThemeEditorStore.setState({ session: null });
84 - container = document.createElement("div");
85 - document.body.append(container);
86 - root = createRoot(container);
87 - await act(async () => root.render(<ThemeEditorHost />));
88 -});
89 -afterEach(async () => {
90 - await act(async () => root.unmount());
91 - container.remove();
92 - localStorage.clear();
93 - invalidateCustomThemes();
94 - vi.unstubAllGlobals();
95 -});
80 + return {
81 + [Symbol.dispose]() {
82 + localStorage.clear();
83 + for (const [key, value] of storage) localStorage.setItem(key, value);
84 + invalidateCustomThemes();
85 + useThemeEditorStore.setState({ session });
86 + },
87 + };
88 +}
89
90 describe("ThemeEditorHost", () => {
91 it.each(["editingTheme", "seedTheme"] as const)(
92 "reopens the same %s with its saved colors",
93 async (field) => {
94 + using _state = await setup();
95 + await using screen = await render(<ThemeEditorHost />);
96 + const { container } = screen;
97 const theme = install("saved-colors");
98 await open(field, theme.id);
103 - expect(await shown(field)).toBe("#1f6e4a");
99 + expect(await shown(container, field)).toBe("#1f6e4a");
100
101 await act(async () => useThemeEditorStore.getState().closeThemeEditor());
102 expect(container.querySelector("dl")).toBeNull();
103 updateCustomTheme({ ...theme, colors: { ...theme.colors, accent: "#7241b8" } });
104 await open(field, theme.id);
105
110 - expect(await shown(field)).toBe("#7241b8");
106 + expect(await shown(container, field)).toBe("#7241b8");
107 },
108 );
109
110 it.each(["editingTheme", "seedTheme"] as const)(
111 "refreshes an open %s when the library changes",
112 async (field) => {
113 + using _state = await setup();
114 + await using screen = await render(<ThemeEditorHost />);
115 + const { container } = screen;
116 const theme = install("updated-theme");
117 await open(field, theme.id);
119 - expect(await shown(field)).toBe("#1f6e4a");
118 + expect(await shown(container, field)).toBe("#1f6e4a");
119
120 await act(async () =>
121 updateCustomTheme({ ...theme, colors: { ...theme.colors, accent: "#7241b8" } }),
122 );
123
125 - expect(await shown(field)).toBe("#7241b8");
124 + expect(await shown(container, field)).toBe("#7241b8");
125 },
126 );
127
128 it("does not keep editing a theme removed from the library", async () => {
129 + using _state = await setup();
130 + await using screen = await render(<ThemeEditorHost />);
131 + const { container } = screen;
132 const theme = install("removed-theme");
133 await open("editingTheme", theme.id);
132 - expect(await shown("editingTheme")).toBe("#1f6e4a");
134 + expect(await shown(container, "editingTheme")).toBe("#1f6e4a");
135
136 await act(async () => removeCustomTheme(theme.id));
137
136 - expect(await shown("editingTheme")).toBe("none");
138 + expect(await shown(container, "editingTheme")).toBe("none");
139 });
140 });
apps/web/src/components/settings/colorPickers.browser.test.tsx
+48 -48
@@ -1,8 +1,9 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { describe, expect, it, vi } from "vite-plus/test";
2 import { userEvent } from "vite-plus/test/browser";
3
4 +import type { ReactNode } from "react";
5 +
6 +import { act, fakeTimers, render } from "../../../test/render";
7 import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
8 import { ThemeColorField } from "./ThemeColorPicker";
9
@@ -11,25 +12,16 @@ const SATURATION = "Accent color saturation";
12 const BRIGHTNESS = "Accent color brightness";
13 const PLANE = "Accent color saturation and brightness";
14
14 -let root: Root;
15 -let container: HTMLDivElement;
16 -
17 -beforeEach(() => {
18 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
15 +async function renderPicker(ui: ReactNode) {
16 + await using stack = new AsyncDisposableStack();
17 // Synthetic pointer ids are not active pointers, so the browser would reject capture.
20 - vi.spyOn(HTMLElement.prototype, "setPointerCapture").mockImplementation(() => {});
21 - container = document.createElement("div");
22 - document.body.append(container);
23 - root = createRoot(container);
24 -});
25 -
26 -afterEach(async () => {
27 - await act(async () => root.unmount());
28 - container.remove();
29 - vi.useRealTimers();
30 - vi.restoreAllMocks();
31 - vi.unstubAllGlobals();
32 -});
18 + stack.use(vi.spyOn(HTMLElement.prototype, "setPointerCapture").mockImplementation(() => {}));
19 + const screen = stack.use(await render(ui));
20 + const environment = stack.move();
21 + return Object.assign(screen, {
22 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
23 + });
24 +}
25
26 function byLabel<T extends HTMLElement = HTMLElement>(label: string) {
27 const element = document.querySelector<T>(`[aria-label="${label}"]`);
@@ -77,32 +69,35 @@ const nextFrame = () =>
69
70 async function renderAccent(value: string | undefined, commitDelayMs?: number) {
71 const onCommit = vi.fn();
80 - await act(async () =>
81 - root.render(
82 - <ProviderAccentColorPicker
83 - displayName="Codex"
84 - value={value}
85 - onCommit={onCommit}
86 - {...(commitDelayMs === undefined ? {} : { commitDelayMs })}
87 - />,
88 - ),
72 + const screen = await renderPicker(
73 + <ProviderAccentColorPicker
74 + displayName="Codex"
75 + value={value}
76 + onCommit={onCommit}
77 + {...(commitDelayMs === undefined ? {} : { commitDelayMs })}
78 + />,
79 );
80 await open(`${value ? "Change" : "Add"} accent color for Codex`);
91 - return onCommit;
81 + return Object.assign(screen, { onCommit });
82 }
83
84 async function renderThemeField(value: string) {
85 const onChange = vi.fn();
96 - const render = (current: string) =>
97 - root.render(<ThemeColorField role="accent" value={current} onChange={onChange} />);
98 - await act(async () => render(value));
86 + const field = (current: string) => (
87 + <ThemeColorField role="accent" value={current} onChange={onChange} />
88 + );
89 + const screen = await renderPicker(field(value));
90 await open("Choose Accent color color");
100 - return { onChange, echo: (next: string) => act(async () => render(next)) };
91 + return Object.assign(screen, {
92 + onChange,
93 + echo: (current: string) => screen.rerender(field(current)),
94 + });
95 }
96
97 describe("provider accent color picker", () => {
98 it("adjusts each color axis independently from the keyboard", async () => {
105 - const onCommit = await renderAccent("#ff0000");
99 + await using screen = await renderAccent("#ff0000");
100 + const { onCommit } = screen;
101
102 await press(HUE, "ArrowLeft");
103 expect(slider(HUE).getAttribute("aria-valuenow")).toBe("359");
@@ -134,7 +129,8 @@ describe("provider accent color picker", () => {
129 });
130
131 it("supports Home/End and clamps each axis without changing the other", async () => {
137 - const onCommit = await renderAccent("#ff0000");
132 + await using screen = await renderAccent("#ff0000");
133 + const { onCommit } = screen;
134
135 await press(SATURATION, "Home");
136 await press(SATURATION, "ArrowLeft");
@@ -156,7 +152,8 @@ describe("provider accent color picker", () => {
152 });
153
154 it("adds an accent only after choosing one and clears it back to no accent", async () => {
159 - const onCommit = await renderAccent(undefined);
155 + await using screen = await renderAccent(undefined);
156 + const { onCommit } = screen;
157 const clearButton = () =>
158 [...document.querySelectorAll("button")].find((button) =>
159 button.textContent?.includes("Clear color"),
@@ -174,8 +171,9 @@ describe("provider accent color picker", () => {
171 });
172
173 it("debounces commits and commits the pending color on unmount", async () => {
177 - const onCommit = await renderAccent("#ff0000", 250);
178 - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
174 + await using screen = await renderAccent("#ff0000", 250);
175 + const { onCommit } = screen;
176 + using _timers = fakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
177
178 await press(HUE, "ArrowRight", true);
179 await press(HUE, "ArrowRight", true);
@@ -184,17 +182,17 @@ describe("provider accent color picker", () => {
182 expect(onCommit).toHaveBeenCalledExactlyOnceWith("#ff5500");
183
184 await press(HUE, "ArrowRight", true);
187 - await act(async () => root.unmount());
185 + await screen.unmount();
186 expect(onCommit).toHaveBeenLastCalledWith("#ff8000");
187 await act(async () => vi.advanceTimersByTime(250));
188 expect(onCommit).toHaveBeenCalledTimes(2);
191 - root = createRoot(container);
189 });
190 });
191
192 describe("theme color field", () => {
193 it("batches native range changes into one commit per frame and keeps alpha", async () => {
197 - const { onChange } = await renderThemeField("#ff000080");
194 + await using screen = await renderThemeField("#ff000080");
195 + const { onChange } = screen;
196
197 // Both changes land in one task, so no animation frame can run between them.
198 await act(async () => {
@@ -212,7 +210,8 @@ describe("theme color field", () => {
210 });
211
212 it("flushes the final drag color on release of the dragging pointer only", async () => {
215 - const { onChange } = await renderThemeField("#ff000080");
213 + await using screen = await renderThemeField("#ff000080");
214 + const { onChange } = screen;
215
216 // The drag runs in one task, so no animation frame can commit mid-drag.
217 await act(async () => {
@@ -230,7 +229,8 @@ describe("theme color field", () => {
229 });
230
231 it("clamps out-of-bounds drags and flushes on cancellation and unmount", async () => {
233 - const { onChange } = await renderThemeField("#ff000080");
232 + await using screen = await renderThemeField("#ff000080");
233 + const { onChange } = screen;
234
235 await act(async () => {
236 pointer(PLANE, "pointerdown", -0.5, -0.5);
@@ -240,14 +240,14 @@ describe("theme color field", () => {
240
241 await act(async () => {
242 pointer(PLANE, "pointerdown", 1.5, 1.5);
243 - root.unmount();
243 + await screen.unmount();
244 });
245 expect(onChange).toHaveBeenLastCalledWith("accent", "#00000080");
246 - root = createRoot(container);
246 });
247
248 it("keeps the selected hue when a grey color is echoed back from theme settings", async () => {
250 - const { onChange, echo } = await renderThemeField("#ff0000");
249 + await using screen = await renderThemeField("#ff0000");
250 + const { onChange, echo } = screen;
251
252 await press(HUE, "ArrowRight", true);
253 await act(async () => {
apps/web/src/components/settings/settingsLayout.browser.test.tsx
+25 -21
@@ -1,29 +1,29 @@
1 -import { afterEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { describe, expect, it, vi } from "vite-plus/test";
2
3 import { scrollToSettingsTarget } from "./settingsLayout";
4
5 const PULSE = "settings-search-target-pulse";
6
7 -afterEach(() => {
8 - document.body.replaceChildren();
9 - vi.restoreAllMocks();
10 -});
11 -
7 function mount(html: string) {
13 - document.body.innerHTML = html;
14 - return vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
8 + const container = document.createElement("div");
9 + container.innerHTML = html;
10 + document.body.append(container);
11 + return { [Symbol.dispose]: () => container.remove() };
12 }
13
14 function reduceMotion(matches: boolean) {
18 - vi.spyOn(window, "matchMedia").mockReturnValue({ matches } as MediaQueryList);
15 + return vi.spyOn(window, "matchMedia").mockReturnValue({ matches } as MediaQueryList);
16 }
17
18 describe("settings search targets", () => {
19 it("scrolls a section's header into view, focuses the section, and pulses until blur", () => {
23 - reduceMotion(false);
24 - const scrollIntoView = mount(
20 + using _motion = reduceMotion(false);
21 + using _fixture = mount(
22 `<section id="providers" tabindex="-1"><h2>Providers</h2><p>Body</p></section>`,
23 );
24 + using scrollIntoView = vi
25 + .spyOn(HTMLElement.prototype, "scrollIntoView")
26 + .mockImplementation(() => {});
27 const section = document.getElementById("providers")!;
28
29 expect(scrollToSettingsTarget("providers")).toBe(true);
@@ -38,10 +38,11 @@ describe("settings search targets", () => {
38 });
39
40 it("restarts the pulse when the same destination is chosen again", () => {
41 - reduceMotion(false);
42 - mount(`<div id="word-wrap" tabindex="-1" class="${PULSE}"></div>`);
41 + using _motion = reduceMotion(false);
42 + using _fixture = mount(`<div id="word-wrap" tabindex="-1" class="${PULSE}"></div>`);
43 const target = document.getElementById("word-wrap")!;
44 const observer = new MutationObserver(() => {});
45 + using _observer = { [Symbol.dispose]: () => observer.disconnect() };
46 observer.observe(target, { attributeFilter: ["class"], attributeOldValue: true });
47
48 scrollToSettingsTarget("word-wrap");
@@ -51,8 +52,11 @@ describe("settings search targets", () => {
52 });
53
54 it("does not animate the destination when reduced motion is requested", () => {
54 - reduceMotion(true);
55 - const scrollIntoView = mount(`<div id="word-wrap" tabindex="-1"></div>`);
55 + using _motion = reduceMotion(true);
56 + using _fixture = mount(`<div id="word-wrap" tabindex="-1"></div>`);
57 + using scrollIntoView = vi
58 + .spyOn(HTMLElement.prototype, "scrollIntoView")
59 + .mockImplementation(() => {});
60 const target = document.getElementById("word-wrap")!;
61
62 expect(scrollToSettingsTarget("word-wrap")).toBe(true);
@@ -66,8 +70,8 @@ describe("settings search targets", () => {
70 "fully reveals the row when the opening style clears: %s",
71 async (phase) => {
72 // Keep scrolling synchronous while the panel height transitions independently.
69 - reduceMotion(true);
70 - document.body.innerHTML = `
73 + using _motion = reduceMotion(true);
74 + using _fixture = mount(`
75 <div id="viewport" style="height: 200px; overflow: auto; overflow-anchor: none">
76 <div id="panel" data-slot="collapsible-panel" data-open data-starting-style
77 style="height: 0; overflow: hidden; transition: height 200ms linear">
@@ -75,7 +79,7 @@ describe("settings search targets", () => {
79 <div id="legacy-sidebar" tabindex="-1" style="height: 40px">Legacy sidebar</div>
80 <div style="height: 60px"></div>
81 </div>
78 - </div>`;
82 + </div>`);
83 const viewport = document.getElementById("viewport")!;
84 const panel = document.getElementById("panel")!;
85 const target = document.getElementById("legacy-sidebar")!;
@@ -116,8 +120,8 @@ describe("settings search targets", () => {
120 );
121
122 it("keeps the newer search destination visible when an earlier panel finishes opening", async () => {
119 - reduceMotion(true);
120 - document.body.innerHTML = `
123 + using _motion = reduceMotion(true);
124 + using _fixture = mount(`
125 <div id="viewport" style="height: 200px; overflow: auto; overflow-anchor: none">
126 <div id="new-target" tabindex="-1" style="height: 40px">New target</div>
127 <div style="height: 1000px"></div>
@@ -127,7 +131,7 @@ describe("settings search targets", () => {
131 <div id="legacy-sidebar" tabindex="-1" style="height: 40px">Legacy sidebar</div>
132 <div style="height: 60px"></div>
133 </div>
130 - </div>`;
134 + </div>`);
135 const panel = document.getElementById("panel")!;
136 void panel.offsetHeight;
137 panel.style.height = "600px";
apps/web/src/components/settings/settingsScopeRetention.browser.test.tsx
+12 -23
@@ -1,6 +1,6 @@
1 -import { act, useState, type ReactNode } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
1 +import { act, render } from "../../../test/render";
2 +import { useState, type ReactNode } from "react";
3 +import { expect, it, vi } from "vite-plus/test";
4 import type { SettingsScopeSearch } from "./settingsScope";
5
6 interface ScopeState {
@@ -85,29 +85,14 @@ function StatefulContent() {
85 );
86 }
87
88 -let root: Root;
89 -let container: HTMLDivElement;
88 const Layout = Route.options.component!;
89 await Layout.preload?.();
90
93 -async function render(scope: ScopeState) {
91 +function setup(pathname: string, scope: ScopeState) {
92 + state.pathname = pathname;
93 state.scope = scope;
95 - await act(async () => root.render(<Layout />));
96 -}
97 -function retainedValue() {
98 - return container.querySelector('button[aria-label="Retained value"]')?.textContent ?? null;
94 }
95
101 -beforeEach(() => {
102 - container = document.createElement("div");
103 - document.body.append(container);
104 - root = createRoot(container);
105 -});
106 -afterEach(async () => {
107 - await act(async () => root.unmount());
108 - container.remove();
109 -});
110 -
96 const first = { search: { machine: "first", project: "one" }, environmentId: "first" };
97 const otherProject = { search: { machine: "first", project: "two" }, environmentId: "first" };
98 const otherMachine = { search: { machine: "second", project: "one" }, environmentId: "second" };
@@ -126,14 +111,18 @@ it.each([
111 ["/settings/diagnostics", "a disconnect", "0", first, disconnected],
112 ["/settings/keybindings", "another project", "0", first, otherProject],
113 ])("%s after %s shows %s", async (pathname, _change, expected, before, after) => {
129 - state.pathname = pathname;
130 - await render(before);
114 + setup(pathname, before);
115 + await using screen = await render(<Layout />);
116 + const { container } = screen;
117 + const retainedValue = () =>
118 + container.querySelector('button[aria-label="Retained value"]')?.textContent ?? null;
119 await act(async () =>
120 container.querySelector<HTMLButtonElement>('button[aria-label="Retained value"]')?.click(),
121 );
122 expect(retainedValue()).toBe("1");
123
136 - await render(after);
124 + state.scope = after;
125 + await screen.rerender(<Layout />);
126
127 expect(retainedValue()).toBe(expected);
128 });
apps/web/src/components/settings/useProjectScriptSettings.browser.test.tsx
+42 -45
@@ -1,3 +1,4 @@
1 +import { act, render } from "../../../test/render";
2 import {
3 DEFAULT_SERVER_SETTINGS,
4 EnvironmentId,
@@ -6,9 +7,7 @@ import {
7 type ResolvedKeybindingsConfig,
8 } from "@t3tools/contracts";
9 import { AsyncResult } from "effect/reactivity";
9 -import { act } from "react";
10 -import { createRoot, type Root } from "react-dom/client";
11 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
10 +import { describe, expect, it, vi } from "vite-plus/test";
11
12 import type { NewProjectScriptInput } from "../projectScriptEditor";
13
@@ -87,35 +86,35 @@ function Probe(props: {
86 return null;
87 }
88
90 -let root: Root;
91 -let container: HTMLDivElement;
92 -
89 async function renderSettings(
90 keybindings: ResolvedKeybindingsConfig,
91 scope: "project" | "environment" = "project",
92 ) {
93 let settings: ProjectScriptSettings | undefined;
98 - await act(async () =>
99 - root.render(
100 - <Probe
101 - targets={[
102 - {
103 - environmentId,
104 - settings: {
105 - ...DEFAULT_SERVER_SETTINGS,
106 - defaultProjectScripts: scope === "environment" ? [lint] : [],
107 - },
108 - keybindings,
109 - ...(scope === "project"
110 - ? { project: { id: ProjectId.make("project"), scripts: [lint] } }
111 - : {}),
94 + const screen = await render(
95 + <Probe
96 + targets={[
97 + {
98 + environmentId,
99 + settings: {
100 + ...DEFAULT_SERVER_SETTINGS,
101 + defaultProjectScripts: scope === "environment" ? [lint] : [],
102 },
113 - ]}
114 - onResult={(next) => (settings = next)}
115 - />,
116 - ),
103 + keybindings,
104 + ...(scope === "project"
105 + ? { project: { id: ProjectId.make("project"), scripts: [lint] } }
106 + : {}),
107 + },
108 + ]}
109 + onResult={(next) => (settings = next)}
110 + />,
111 );
118 - return settings!;
112 + return {
113 + ...screen,
114 + get settings() {
115 + return settings!;
116 + },
117 + };
118 }
119
120 async function submitInAct(
@@ -128,29 +127,19 @@ async function submitInAct(
127 });
128 return result!;
129 }
131 -
132 -beforeEach(() => {
133 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
130 +function setup() {
131 vi.clearAllMocks();
135 - for (const command of Object.values(commands)) {
132 + for (const command of Object.values(commands))
133 command.mockResolvedValue(AsyncResult.success(undefined));
137 - }
138 - container = document.createElement("div");
139 - document.body.append(container);
140 - root = createRoot(container);
141 -});
142 -
143 -afterEach(async () => {
144 - await act(async () => root.unmount());
145 - container.remove();
146 - vi.unstubAllGlobals();
147 -});
134 +}
135
136 describe("useProjectScriptSettings", () => {
137 it.each(["project", "environment"] as const)(
138 "preserves the shortcut for %s action name and command edits",
139 async (scope) => {
153 - const { submit } = await renderSettings(lintBinding, scope);
140 + setup();
141 + await using screen = await renderSettings(lintBinding, scope);
142 + const { submit } = screen.settings;
143 const changes = { name: "Lint and fix", command: "vp lint --fix" };
144
145 const result = await submitInAct(submit, changes);
@@ -172,7 +161,9 @@ describe("useProjectScriptSettings", () => {
161 );
162
163 it("saves a recorded action shortcut", async () => {
175 - const { submit } = await renderSettings([]);
164 + setup();
165 + await using screen = await renderSettings([]);
166 + const { submit } = screen.settings;
167
168 const result = await submitInAct(submit, { keybinding: "mod+shift+k" });
169
@@ -184,7 +175,9 @@ describe("useProjectScriptSettings", () => {
175 });
176
177 it("removes a cleared action shortcut", async () => {
187 - const { submit } = await renderSettings(lintBinding);
178 + setup();
179 + await using screen = await renderSettings(lintBinding);
180 + const { submit } = screen.settings;
181
182 const result = await submitInAct(submit, { keybinding: null });
183
@@ -197,7 +190,9 @@ describe("useProjectScriptSettings", () => {
190 });
191
192 it("replaces an explicitly changed action shortcut", async () => {
200 - const { submit } = await renderSettings(lintBinding);
193 + setup();
194 + await using screen = await renderSettings(lintBinding);
195 + const { submit } = screen.settings;
196
197 const result = await submitInAct(submit, { keybinding: "mod+shift+l" });
198
@@ -214,7 +209,9 @@ describe("useProjectScriptSettings", () => {
209 });
210
211 it("removes the shortcut when its action is deleted", async () => {
217 - const { persist } = await renderSettings(lintBinding);
212 + setup();
213 + await using screen = await renderSettings(lintBinding);
214 + const { persist } = screen.settings;
215
216 await act(async () => {
217 expect((await persist(() => []))._tag).toBe("Success");
apps/web/src/components/settings/useSnapShotShortcutRecorder.browser.test.tsx
+65 -44
@@ -1,8 +1,8 @@
1 +import { act, render } from "../../../test/render";
2 import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts";
2 -import { act, useEffect } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
3 +import { useEffect } from "react";
4 import { userEvent } from "vite-plus/test/browser";
5 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
5 +import { expect, it, vi } from "vite-plus/test";
6
7 const suppress = vi.hoisted(() => vi.fn<(enabled: boolean) => Promise<void>>());
8 vi.mock(import("../../lib/desktopSnapShot"), async (original) => ({
@@ -22,8 +22,6 @@ function deferred<T>() {
22
23 const recorded = vi.fn();
24 const error = vi.fn();
25 -let root: Root;
26 -let container: HTMLDivElement;
25 let recording = false;
26
27 function Recorder(props: { allowModifierPairs?: boolean; shortcutLabel?: string }) {
@@ -40,39 +38,33 @@ function Recorder(props: { allowModifierPairs?: boolean; shortcutLabel?: string
38 return recorder.input;
39 }
40
43 -async function render(props: Parameters<typeof Recorder>[0] = {}) {
44 - await act(async () => root.render(<Recorder {...props} />));
45 -}
46 -const button = () => container.querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;
47 -async function start(props: Parameters<typeof Recorder>[0] = {}) {
48 - await render(props);
49 - await act(async () => userEvent.click(button()));
50 - expect(recording).toBe(true);
51 -}
52 -const press = (keys: string) => act(async () => userEvent.keyboard(keys));
53 -function setPlatform(platform: string) {
54 - Object.defineProperty(navigator, "platform", { configurable: true, get: () => platform });
55 -}
56 -
57 -beforeEach(() => {
58 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
41 +function setup() {
42 suppress.mockReset().mockResolvedValue(undefined);
43 recorded.mockReset();
44 error.mockReset();
62 - setPlatform("Linux x86_64");
63 - container = document.createElement("div");
64 - document.body.append(container);
65 - root = createRoot(container);
66 -});
67 -afterEach(async () => {
68 - await act(async () => root.unmount());
69 - container.remove();
70 - Reflect.deleteProperty(navigator, "platform");
71 - vi.unstubAllGlobals();
72 -});
45 + recording = false;
46 +}
47 +async function renderRecorder(props: Parameters<typeof Recorder>[0] = {}) {
48 + const screen = await render(<Recorder {...props} />);
49 + const button = () =>
50 + screen.container.querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;
51 + return {
52 + ...screen,
53 + button,
54 + async start() {
55 + await act(() => userEvent.click(button()));
56 + expect(recording).toBe(true);
57 + },
58 + };
59 +}
60 +const press = (keys: string) => act(async () => userEvent.keyboard(keys));
61
62 it("suppresses capture while recording and uses the physical key for shifted digits", async () => {
75 - await start();
63 + setup();
64 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
65 + await using screen = await renderRecorder();
66 + const { button } = screen;
67 + await screen.start();
68 expect(suppress).toHaveBeenCalledExactlyOnceWith(true);
69 expect(button().textContent).toBe("Press shortcut…");
70 await press("{Control>}{Shift>}2{/Shift}{/Control}");
@@ -89,8 +81,11 @@ it("suppresses capture while recording and uses the physical key for shifted dig
81 });
82
83 it("lets users replace an unrecognized desktop label without displaying guessed keys", async () => {
84 + setup();
85 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
86 const shortcutLabel = "Use the shortcut assigned in desktop settings";
93 - await render({ shortcutLabel });
87 + await using screen = await renderRecorder({ shortcutLabel });
88 + const { button } = screen;
89 expect(button().textContent).toBe("Change shortcut");
90 expect(button().getAttribute("aria-label")).toBe("Change snapshot shortcut");
91 await act(async () => userEvent.click(button()));
@@ -103,31 +98,42 @@ it("lets users replace an unrecognized desktop label without displaying guessed
98 });
99
100 it("records macOS Command without treating it as Control", async () => {
106 - setPlatform("MacIntel");
107 - await start({ allowModifierPairs: true });
101 + setup();
102 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
103 + _platform.mockReturnValue("MacIntel");
104 + await using screen = await renderRecorder({ allowModifierPairs: true });
105 +
106 + await screen.start();
107 await press("{Meta>}k{/Meta}");
108 expect(recorded).toHaveBeenCalledWith(expect.objectContaining({ key: "k", modKey: true }));
109 });
110
111 it.each(["Escape", "blur", "unmount"])("cancels on %s without selecting keys", async (cancel) => {
113 - await start();
112 + setup();
113 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
114 + await using screen = await renderRecorder();
115 + const { button } = screen;
116 + await screen.start();
117 if (cancel === "Escape") {
118 const outside = vi.fn();
119 document.addEventListener("keydown", outside);
120 + using _listener = { [Symbol.dispose]: () => document.removeEventListener("keydown", outside) };
121 await press("{Escape}");
118 - document.removeEventListener("keydown", outside);
122 expect(outside).not.toHaveBeenCalled();
123 } else if (cancel === "blur") await act(async () => button().blur());
121 - else await act(async () => root.render(null));
124 + else await screen.unmount();
125 expect(suppress).toHaveBeenLastCalledWith(false);
126 expect(recorded).not.toHaveBeenCalled();
127 if (cancel !== "unmount") expect(recording).toBe(false);
128 });
129
130 it("ignores late suppression acknowledgements after cancellation", async () => {
131 + setup();
132 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
133 const pending = deferred<void>();
134 suppress.mockImplementation((enabled) => (enabled ? pending.promise : Promise.resolve()));
130 - await render();
135 + await using screen = await renderRecorder();
136 + const { button } = screen;
137 await act(async () => userEvent.click(button()));
138 await act(async () => button().blur());
139 await act(async () => pending.resolve());
@@ -137,15 +143,22 @@ it("ignores late suppression acknowledgements after cancellation", async () => {
143 });
144
145 it("reports suppression failures instead of arming the recorder", async () => {
146 + setup();
147 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
148 suppress.mockRejectedValue(new Error("Couldn't pause capture"));
141 - await render();
149 + await using screen = await renderRecorder();
150 + const { button } = screen;
151 await act(async () => userEvent.click(button()));
152 expect(recording).toBe(false);
153 expect(error).toHaveBeenCalledWith("Couldn't pause capture");
154 });
155
156 it("does not record Tab, unmodified keys, or modifier keys on their own", async () => {
148 - await start();
157 + setup();
158 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
159 + await using screen = await renderRecorder();
160 + const { button } = screen;
161 + await screen.start();
162 await press("y");
163 await press("{Control>}{/Control}");
164 expect(recorded).not.toHaveBeenCalled();
@@ -155,7 +168,11 @@ it("does not record Tab, unmodified keys, or modifier keys on their own", async
168 });
169
170 it("rejects modifier pairs on Wayland but accepts the next key chord", async () => {
158 - await start();
171 + setup();
172 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
173 + await using screen = await renderRecorder();
174 +
175 + await screen.start();
176 await press("{ShiftLeft>}{ShiftRight>}{/ShiftRight}{/ShiftLeft}");
177 expect(recorded).not.toHaveBeenCalled();
178 expect(error).toHaveBeenCalledWith(expect.stringContaining("Add a letter, number"));
@@ -165,7 +182,11 @@ it("rejects modifier pairs on Wayland but accepts the next key chord", async ()
182 });
183
184 it("preserves native modifier-pair recording and tracks released keys", async () => {
168 - await start({ allowModifierPairs: true });
185 + setup();
186 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
187 + await using screen = await renderRecorder({ allowModifierPairs: true });
188 +
189 + await screen.start();
190 await press("{ShiftLeft}");
191 await press("{ShiftRight>}");
192 expect(recorded).not.toHaveBeenCalled();
apps/web/src/components/ui/sidebar.browser.test.tsx
+21 -43
@@ -1,49 +1,23 @@
1 +import { render } from "../../../test/render";
2 import "../../index.css";
3
3 -import { act } from "react";
4 -import { createRoot, type Root } from "react-dom/client";
5 -import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
4 +import { describe, expect, it } from "vite-plus/test";
5
6 import { page, userEvent } from "vite-plus/test/browser";
7
8 import { Sidebar, SidebarProvider, SidebarTrigger } from "./sidebar";
9 import { resolveSidebarState } from "./sidebarState";
10
12 -let root: Root;
13 -let container: HTMLDivElement;
14 -
15 -beforeEach(async () => {
16 - await page.viewport(1280, 900);
17 - container = document.createElement("div");
18 - document.body.append(container);
19 - root = createRoot(container);
20 -});
21 -
22 -afterEach(async () => {
23 - await act(async () => root.unmount());
24 - container.remove();
25 -});
26 -
27 -async function renderSidebar(open: boolean) {
28 - await act(async () => {
29 - root.render(
30 - <SidebarProvider open={open}>
31 - <Sidebar>
32 - <SidebarTrigger data-testid="internal-trigger" />
33 - <button data-testid="sidebar-control">Thread</button>
34 - </Sidebar>
35 - <SidebarTrigger data-testid="external-trigger" />
36 - <button data-testid="content-control">Content</button>
37 - </SidebarProvider>,
38 - );
39 - });
40 -}
41 -
42 -function element(selector: string) {
43 - const node = container.querySelector<HTMLElement>(selector);
44 - if (!node) throw new Error(`Missing element: ${selector}`);
45 - return node;
46 -}
11 +const sidebarUi = (open: boolean) => (
12 + <SidebarProvider open={open}>
13 + <Sidebar>
14 + <SidebarTrigger data-testid="internal-trigger" />
15 + <button data-testid="sidebar-control">Thread</button>
16 + </Sidebar>
17 + <SidebarTrigger data-testid="external-trigger" />
18 + <button data-testid="content-control">Content</button>
19 + </SidebarProvider>
20 +);
21
22 describe("responsive sidebar state", () => {
23 it("uses mobile sheet visibility for the shared responsive state", () => {
@@ -59,13 +33,15 @@ describe("responsive sidebar state", () => {
33
34 describe("desktop sidebar focus", () => {
35 it("moves focus to the external toggle on collapse and restores sidebar access on expansion", async () => {
62 - await renderSidebar(true);
36 + await page.viewport(1280, 900);
37 + await using screen = await render(sidebarUi(true));
38 + const element = (selector: string) => screen.container.querySelector<HTMLElement>(selector)!;
39 const control = element('[data-testid="sidebar-control"]');
40 const sidebar = element('[data-slot="sidebar"]');
41 control.focus();
42 expect(document.activeElement).toBe(control);
43
68 - await renderSidebar(false);
44 + await screen.rerender(sidebarUi(false));
45
46 expect(document.activeElement).toBe(element('[data-testid="external-trigger"]'));
47 expect(sidebar.inert).toBe(true);
@@ -79,7 +55,7 @@ describe("desktop sidebar focus", () => {
55 await userEvent.keyboard("{Tab}");
56 expect(document.activeElement).toBe(element('[data-testid="content-control"]'));
57
82 - await renderSidebar(true);
58 + await screen.rerender(sidebarUi(true));
59
60 expect(sidebar.inert).toBe(false);
61 control.focus();
@@ -87,12 +63,14 @@ describe("desktop sidebar focus", () => {
63 });
64
65 it("keeps focus in the content when the sidebar collapses", async () => {
90 - await renderSidebar(true);
66 + await page.viewport(1280, 900);
67 + await using screen = await render(sidebarUi(true));
68 + const element = (selector: string) => screen.container.querySelector<HTMLElement>(selector)!;
69 const control = element('[data-testid="content-control"]');
70 control.focus();
71 expect(document.activeElement).toBe(control);
72
95 - await renderSidebar(false);
73 + await screen.rerender(sidebarUi(false));
74
75 expect(document.activeElement).toBe(control);
76 });
apps/web/src/components/ui/switch.browser.test.tsx
+9 -37
@@ -1,25 +1,9 @@
1 -import { act, useState } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { act, render } from "../../../test/render";
2 +import { useState } from "react";
3 +import { describe, expect, it } from "vite-plus/test";
4
5 import { Switch } from "./switch";
6
7 -let root: Root;
8 -let container: HTMLDivElement;
9 -
10 -beforeEach(() => {
11 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
12 - container = document.createElement("div");
13 - document.body.append(container);
14 - root = createRoot(container);
15 -});
16 -
17 -afterEach(async () => {
18 - await act(async () => root.unmount());
19 - container.remove();
20 - vi.unstubAllGlobals();
21 -});
22 -
7 function ControlledSwitch({
8 initialChecked,
9 initialMixed = false,
@@ -43,32 +27,20 @@ function ControlledSwitch({
27 );
28 }
29
46 -function switchRoot() {
47 - const element = container.querySelector<HTMLElement>('[role="switch"]');
48 - if (!element) throw new Error("Switch was not rendered");
49 - return element;
50 -}
51 -
52 -async function clickSwitch() {
53 - await act(async () => switchRoot().click());
54 -}
55 -
56 -async function renderSwitch(initialChecked: boolean, initialMixed = false) {
57 - await act(async () => {
58 - root.render(<ControlledSwitch {...{ initialChecked, initialMixed }} />);
59 - });
60 -}
61 -
30 describe("Switch accessibility", () => {
31 it.each([
32 { initialChecked: false, initialMixed: false, before: false, after: true },
33 { initialChecked: true, initialMixed: false, before: true, after: false },
34 { initialChecked: false, initialMixed: true, before: "mixed", after: true },
35 ])("exposes $before before activation and $after after activation", async (state) => {
68 - await renderSwitch(state.initialChecked, state.initialMixed);
36 + await using screen = await render(
37 + <ControlledSwitch initialChecked={state.initialChecked} initialMixed={state.initialMixed} />,
38 + );
39 + const { container } = screen;
40 + const switchRoot = () => container.querySelector<HTMLElement>('[role="switch"]')!;
41 expect(switchRoot().getAttribute("aria-checked")).toBe(String(state.before));
42
71 - await clickSwitch();
43 + await act(() => switchRoot().click());
44
45 expect(switchRoot().getAttribute("aria-checked")).toBe(String(state.after));
46 expect(container.querySelector<HTMLInputElement>('input[type="checkbox"]')?.checked).toBe(
apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx
+29 -32
@@ -1,3 +1,4 @@
1 +import { act, render } from "../../../test/render";
2 import {
3 EnvironmentId,
4 ProviderDriverKind,
@@ -6,9 +7,7 @@ import {
7 type ServerProvider,
8 } from "@t3tools/contracts";
9 import type { LimitPresentations } from "@t3tools/shared/usageLimits";
9 -import { act } from "react";
10 -import { createRoot, type Root } from "react-dom/client";
11 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
10 +import { expect, it, vi } from "vite-plus/test";
11 import { page, userEvent } from "vite-plus/test/browser";
12
13 // Real pointer clicks need the dialog's stacking styles to land above Base UI's modal overlay.
@@ -70,27 +69,12 @@ const presentations = (resetsAt: string | undefined, availableCount: number): Li
69 ],
70 ]);
71
73 -let root: Root;
74 -let container: HTMLDivElement;
75 -
76 -beforeEach(async () => {
77 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
72 +function setup() {
73 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 -
89 -afterEach(async () => {
90 - await act(() => root.unmount());
91 - container.remove();
92 - vi.unstubAllGlobals();
93 -});
74 +}
75 +const initial = () => (
76 + <UsageLimitsPooled presentations={presentations("2026-09-03T14:00:00Z", 1)} now={0} />
77 +);
78
79 async function click(label: string) {
80 const button = Array.from(document.querySelectorAll("button")).find(
@@ -134,6 +118,8 @@ it.each([
118 text: "Codex rejected the credit.",
119 },
120 ])("keeps pending feedback outside the closed popup until $label", async ({ result, text }) => {
121 + setup();
122 + await using _screen = await render(initial());
123 let answer!: (result: unknown) => void;
124 consume.mockReturnValue(new Promise((resolve) => (answer = resolve)));
125 await click("Alpha:");
@@ -160,6 +146,9 @@ it.each([
146 });
147
148 it("omits an empty reset plate but keeps countdowns and banked credits visible", async () => {
149 + setup();
150 + await using screen = await render(initial());
151 +
152 await page.viewport(1440, 900);
153 const now = Date.parse("2026-09-03T11:00:00Z");
154 const segment = page.getByRole("button", { name: /^Alpha:/ });
@@ -168,13 +157,13 @@ it("omits an empty reset plate but keeps countdowns and banked credits visible",
157 segment.element().querySelector<HTMLSpanElement>('[class~="bg-background/85"]');
158
159 await act(() =>
171 - root.render(<UsageLimitsPooled presentations={presentations(undefined, 0)} now={now} />),
160 + screen.rerender(<UsageLimitsPooled presentations={presentations(undefined, 0)} now={now} />),
161 );
162 await expect.element(segment.getByText("100%", { exact: true })).toBeVisible();
163 expect(plate()).toBeNull();
164
165 await act(() =>
177 - root.render(
166 + screen.rerender(
167 <UsageLimitsPooled presentations={presentations("2026-09-03T14:00:00Z", 0)} now={now} />,
168 ),
169 );
@@ -182,13 +171,16 @@ it("omits an empty reset plate but keeps countdowns and banked credits visible",
171 expect(plate()?.textContent).toBe("↻ 3h 0m");
172
173 await act(() =>
185 - root.render(<UsageLimitsPooled presentations={presentations(undefined, 1)} now={now} />),
174 + screen.rerender(<UsageLimitsPooled presentations={presentations(undefined, 1)} now={now} />),
175 );
176 await expect.element(plate()).toBeVisible();
177 expect(plate()?.textContent).toBe("1");
178 });
179
180 it("moves the one limit popover between windows on hover", async () => {
181 + setup();
182 + await using screen = await render(initial());
183 + const { container } = screen;
184 const [environmentId, presentation] = [...presentations("2026-09-03T14:00:00Z", 1)][0]!;
185 const serverConfig = presentation.serverConfig!;
186 const provider = serverConfig.providers[0]!;
@@ -217,7 +209,7 @@ it("moves the one limit popover between windows on hover", async () => {
209 ]);
210 // Room above the bars so the popover opens there instead of flipping over the next card.
211 container.style.paddingTop = "20rem";
220 - await act(() => root.render(<UsageLimitsPooled presentations={twoWindows} now={0} />));
212 + await act(() => screen.rerender(<UsageLimitsPooled presentations={twoWindows} now={0} />));
213 const segment = (label: string) =>
214 Array.from(document.querySelectorAll("button")).find((node) =>
215 node.getAttribute("aria-label")?.startsWith(label),
@@ -244,17 +236,20 @@ it("moves the one limit popover between windows on hover", async () => {
236 await expect.poll(popups).toEqual([expect.stringContaining("Left60%")]);
237
238 await expectDismissedInPlace(() =>
247 - act(() => root.render(<UsageLimitsPooled presentations={new Map()} now={0} />)),
239 + act(() => screen.rerender(<UsageLimitsPooled presentations={new Map()} now={0} />)),
240 );
241 await act(() => userEvent.hover(container, { position: { x: 4, y: 4 } }));
242
251 - await act(() => root.render(<UsageLimitsPooled presentations={twoWindows} now={0} />));
243 + await act(() => screen.rerender(<UsageLimitsPooled presentations={twoWindows} now={0} />));
244 await expect.poll(popups).toEqual([]);
245 await act(() => userEvent.click(segment("Alpha: 60%")));
246 await expect.poll(popups).toEqual([expect.stringContaining("Left60%")]);
247 });
248
249 it("closes an open source-account popover when reset availability replaces its trigger", async () => {
250 + setup();
251 + await using screen = await render(initial());
252 +
253 const [environmentId, presentation] = [...presentations("2026-09-03T14:00:00Z", 1)][0]!;
254 const provider = presentation.serverConfig!.providers[0]!;
255 const source = (nextCreditId?: string): LimitPresentations =>
@@ -291,18 +286,20 @@ it("closes an open source-account popover when reset availability replaces its t
286 ],
287 ]);
288 const popup = () => document.querySelector('[data-slot="popover-popup"]');
294 - await act(() => root.render(<UsageLimitsPooled presentations={source("credit-1")} now={0} />));
289 + await act(() =>
290 + screen.rerender(<UsageLimitsPooled presentations={source("credit-1")} now={0} />),
291 + );
292 await click("Alpha: 60%");
293 await expect.poll(() => popup()?.textContent).toContain("Use reset");
294
295 await expectDismissedInPlace(() =>
299 - act(() => root.render(<UsageLimitsPooled presentations={source()} now={0} />)),
296 + act(() => screen.rerender(<UsageLimitsPooled presentations={source()} now={0} />)),
297 );
298 await click("Alpha: 60%");
299 await expect.poll(() => popup()?.textContent).toContain("Left60%");
300
301 await expectDismissedInPlace(() =>
305 - act(() => root.render(<UsageLimitsPooled presentations={source("credit-2")} now={0} />)),
302 + act(() => screen.rerender(<UsageLimitsPooled presentations={source("credit-2")} now={0} />)),
303 );
304 await click("Alpha: 60%");
305 await expect.poll(() => popup()?.textContent).toContain("Use reset");
apps/web/src/components/usage/UsagePage.browser.test.tsx
+30 -33
@@ -1,8 +1,7 @@
1 +import { render } from "../../../test/render";
2 import { EnvironmentId, UsageDay, USAGE_CONTRACT_VERSION } from "@t3tools/contracts";
3 import { mergeUsage } from "@t3tools/shared/usageMerge";
3 -import { act } from "react";
4 -import { createRoot, type Root } from "react-dom/client";
5 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4 +import { describe, expect, it, vi } from "vite-plus/test";
5 import { page, userEvent } from "vite-plus/test/browser";
6
7 import "~/index.css";
@@ -45,7 +44,7 @@ const environments = [
44 },
45 ];
46
48 -beforeEach(() => {
47 +function setup() {
48 testState.useUsage.mockReturnValue({
49 merged: mergeUsage([], USAGE_CONTRACT_VERSION),
50 environments,
@@ -55,31 +54,11 @@ beforeEach(() => {
54 isPartial: false,
55 refresh: vi.fn(),
56 });
58 -});
57 + testState.navigate.mockClear();
58 + testState.canGoBack = true;
59 +}
60
61 describe("UsagePage Escape navigation", () => {
61 - let renderer: Root;
62 - let container: HTMLDivElement;
63 - let back: ReturnType<typeof vi.spyOn>;
64 -
65 - beforeEach(async () => {
66 - back = vi.spyOn(window.history, "back").mockImplementation(() => {});
67 - testState.navigate.mockClear();
68 - testState.canGoBack = true;
69 - container = document.createElement("div");
70 - document.body.append(container);
71 - renderer = createRoot(container);
72 - await act(() => {
73 - renderer.render(<UsagePage />);
74 - });
75 - });
76 -
77 - afterEach(async () => {
78 - await act(() => renderer.unmount());
79 - container.remove();
80 - back.mockRestore();
81 - });
82 -
62 // Playwright cannot press a repeating or composing key, so those cases dispatch the event.
63 function escape(properties: { repeat?: boolean; isComposing?: boolean } = {}) {
64 return new KeyboardEvent("keydown", {
@@ -91,14 +70,22 @@ describe("UsagePage Escape navigation", () => {
70 }
71
72 it("returns to the previous page on Escape", async () => {
73 + setup();
74 + using back = vi.spyOn(window.history, "back").mockImplementation(() => {});
75 + await using _screen = await render(<UsagePage />);
76 +
77 await userEvent.keyboard("{Escape}");
78 expect(back).toHaveBeenCalledOnce();
79 expect(testState.navigate).not.toHaveBeenCalled();
80 });
81
82 it("returns home when there is no previous app page", async () => {
83 + setup();
84 + using back = vi.spyOn(window.history, "back").mockImplementation(() => {});
85 + await using screen = await render(<UsagePage />);
86 +
87 testState.canGoBack = false;
101 - await act(() => renderer.render(<UsagePage />));
88 + await screen.rerender(<UsagePage />);
89
90 await userEvent.keyboard("{Escape}");
91 expect(testState.navigate).toHaveBeenCalledWith({ to: "/" });
@@ -106,6 +93,10 @@ describe("UsagePage Escape navigation", () => {
93 });
94
95 it("closes the environment menu before Escape navigates back", async () => {
96 + setup();
97 + using back = vi.spyOn(window.history, "back").mockImplementation(() => {});
98 + await using screen = await render(<UsagePage />);
99 + const { container } = screen;
100 const trigger = container.querySelector<HTMLButtonElement>('[data-slot="menu-trigger"]')!;
101 await userEvent.click(trigger);
102 await expect.element(page.getByRole("menu")).toBeVisible();
@@ -119,9 +110,15 @@ describe("UsagePage Escape navigation", () => {
110 expect(back).toHaveBeenCalledOnce();
111 });
112
122 - it.each([{ repeat: true }, { isComposing: true }])("ignores Escape with %j", (properties) => {
123 - document.body.dispatchEvent(escape(properties));
124 - expect(back).not.toHaveBeenCalled();
125 - expect(testState.navigate).not.toHaveBeenCalled();
126 - });
113 + it.each([{ repeat: true }, { isComposing: true }])(
114 + "ignores Escape with %j",
115 + async (properties) => {
116 + setup();
117 + using back = vi.spyOn(window.history, "back").mockImplementation(() => {});
118 + await using _screen = await render(<UsagePage />);
119 + document.body.dispatchEvent(escape(properties));
120 + expect(back).not.toHaveBeenCalled();
121 + expect(testState.navigate).not.toHaveBeenCalled();
122 + },
123 + );
124 });
apps/web/src/components/usage/UsagePage.refresh.browser.test.tsx
+29 -30
@@ -1,10 +1,10 @@
1 +import { act, render } from "../../../test/render";
2 import { RegistryContext } from "@effect/atom-react";
3 import { EnvironmentId, ProviderInstanceId, USAGE_CONTRACT_VERSION } from "@t3tools/contracts";
4 import { mergeUsage } from "@t3tools/shared/usageMerge";
5 import type { Atom } from "effect/reactivity";
5 -import { act, StrictMode } from "react";
6 -import { createRoot, type Root } from "react-dom/client";
7 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
6 +import { StrictMode } from "react";
7 +import { expect, it, vi } from "vite-plus/test";
8 import { page, userEvent } from "vite-plus/test/browser";
9
10 import "~/index.css";
@@ -76,8 +76,6 @@ import { appAtomRegistry } from "~/rpc/atomRegistry";
76 import { UsagePage } from "./UsagePage";
77
78 const PREFERENCES_KEY = "t3code:usage-page-preferences:v1";
79 -let root: Root;
80 -let container: HTMLDivElement;
79 // Limits refreshes are throttled per environment for the whole session, so each test
80 // gets fresh environment ids.
81 let environmentNumber = 0;
@@ -128,37 +126,34 @@ const resetsIn = (countdown: string) =>
126 const refreshButton = () => page.getByRole("button", { name: "Refresh limits" });
127 const selectMetric = (label: string) => userEvent.click(page.getByRole("button", { name: label }));
128
131 -async function render({ strict = false } = {}) {
129 +async function renderPage({ strict = false } = {}) {
130 const content = (
131 <RegistryContext.Provider value={appAtomRegistry}>
132 <UsagePage />
133 </RegistryContext.Provider>
134 );
137 - await act(async () => root.render(strict ? <StrictMode>{content}</StrictMode> : content));
135 + return render(strict ? <StrictMode>{content}</StrictMode> : content);
136 }
137
140 -beforeEach(async () => {
141 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
138 +async function setup() {
139 // The metric toggle and its refresh button only show on wide screens.
140 await page.viewport(1440, 900);
144 - vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-09-11T12:00:00Z"));
141 + const now = vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-09-11T12:00:00Z"));
142 environmentNumber += 1;
143 environmentId = EnvironmentId.make(`test-${environmentNumber}`);
144 + const previous = localStorage.getItem(PREFERENCES_KEY);
145 localStorage.setItem(PREFERENCES_KEY, JSON.stringify({ metric: "limits", windowDays: 30 }));
146 state.refreshProviders.mockReset().mockResolvedValue(undefined);
147 await setPresentations([[environmentId, presentation()]]);
150 - container = document.createElement("div");
151 - document.body.append(container);
152 - root = createRoot(container);
153 -});
154 -
155 -afterEach(async () => {
156 - await act(async () => root.unmount());
157 - container.remove();
158 - localStorage.clear();
159 - vi.restoreAllMocks();
160 - vi.unstubAllGlobals();
161 -});
148 + return {
149 + [Symbol.dispose]() {
150 + now.mockRestore();
151 + if (previous === null) localStorage.removeItem(PREFERENCES_KEY);
152 + else localStorage.setItem(PREFERENCES_KEY, previous);
153 + appAtomRegistry.set(state.presentations, new Map());
154 + },
155 + };
156 +}
157
158 it.each([
159 ["wide", 1440],
@@ -166,8 +161,9 @@ it.each([
161 ])(
162 "refreshes the visible limits countdown from the %s toolbar without switching tabs, even when quota is unchanged",
163 async (_layout, width) => {
164 + using _state = await setup();
165 await page.viewport(width, 900);
170 - await render();
166 + await using _screen = await renderPage();
167 await expect.element(resetsIn("2h 0m")).toBeVisible();
168 setNow("2026-09-11T12:30:00Z");
169
@@ -180,7 +176,8 @@ it.each([
176 );
177
178 it("uses the current time when returning to limits from tokens", async () => {
183 - await render();
179 + using _state = await setup();
180 + await using _screen = await renderPage();
181 await selectMetric("Tokens");
182 setNow("2026-09-11T13:00:00Z");
183 await selectMetric("Limits");
@@ -190,17 +187,17 @@ it("uses the current time when returning to limits from tokens", async () => {
187 });
188
189 it("refreshes once on opening Limits and suppresses rapid returns and remounts", async () => {
190 + using _state = await setup();
191 localStorage.setItem(PREFERENCES_KEY, JSON.stringify({ metric: "tokens", windowDays: 30 }));
194 - await render({ strict: true });
192 + await using screen = await renderPage({ strict: true });
193 expect(state.refreshProviders).not.toHaveBeenCalled();
194
195 await selectMetric("Limits");
196 await vi.waitFor(() => expect(state.refreshProviders).toHaveBeenCalledTimes(1));
197 await selectMetric("Tokens");
198 await selectMetric("Limits");
201 - await act(async () => root.unmount());
202 - root = createRoot(container);
203 - await render({ strict: true });
199 + await screen.unmount();
200 + await using _remounted = await renderPage({ strict: true });
201 expect(state.refreshProviders).toHaveBeenCalledTimes(1);
202
203 await selectMetric("Tokens");
@@ -210,8 +207,9 @@ it("refreshes once on opening Limits and suppresses rapid returns and remounts",
207 });
208
209 it("waits for connection and refreshes new environments during a slow refresh", async () => {
210 + using _state = await setup();
211 await setPresentations([[environmentId, presentation("disconnected")]]);
214 - await render();
212 + await using _screen = await renderPage();
213 expect(state.refreshProviders).not.toHaveBeenCalled();
214
215 let finishRefresh!: () => void;
@@ -232,11 +230,12 @@ it("waits for connection and refreshes new environments during a slow refresh",
230 });
231
232 it("keeps manual refresh busy until the already-running automatic check settles", async () => {
233 + using _state = await setup();
234 let finishRefresh!: () => void;
235 state.refreshProviders.mockImplementationOnce(
236 () => new Promise((resolve) => (finishRefresh = () => resolve(undefined))),
237 );
239 - await render();
238 + await using _screen = await renderPage();
239 await vi.waitFor(() => expect(state.refreshProviders).toHaveBeenCalledTimes(1));
240
241 await userEvent.click(refreshButton());
apps/web/src/hooks/useActiveThreadRef.browser.test.tsx
+30 -30
@@ -1,18 +1,32 @@
1 +import { useEffect } from "react";
2 +import { render } from "../../test/render";
3 import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
2 -import { act } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4 +import { describe, expect, it } from "vite-plus/test";
5
6 import { useActiveThreadRef } from "./useActiveThreadRef";
7
8 type ThreadLike = { environmentId: EnvironmentId; id: ThreadId; status: string } | null;
9
10 -let root: Root;
11 -let observed: Array<ScopedThreadRef | null> = [];
12 -
13 -function Probe({ thread }: { thread: ThreadLike }) {
14 - observed.push(useActiveThreadRef(thread));
15 - return null;
10 +async function renderThread(value: ThreadLike) {
11 + let observed: ScopedThreadRef | null = null;
12 + function Probe({ thread }: { thread: ThreadLike }) {
13 + const result = useActiveThreadRef(thread);
14 + useEffect(() => {
15 + observed = result;
16 + });
17 + return null;
18 + }
19 + const screen = await render(<Probe thread={value} />);
20 + return {
21 + ...screen,
22 + get current() {
23 + return observed;
24 + },
25 + async update(value: ThreadLike) {
26 + await screen.rerender(<Probe thread={value} />);
27 + return observed;
28 + },
29 + };
30 }
31
32 const thread = (id: string, status = "idle"): ThreadLike => ({
@@ -21,35 +35,21 @@ const thread = (id: string, status = "idle"): ThreadLike => ({
35 status,
36 });
37
24 -async function render(value: ThreadLike) {
25 - await act(() => root.render(<Probe thread={value} />));
26 - return observed.at(-1);
27 -}
28 -
29 -beforeEach(() => {
30 - observed = [];
31 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
32 - root = createRoot(document.createElement("div"));
33 -});
34 -
35 -afterEach(async () => {
36 - await act(() => root.unmount());
37 - vi.unstubAllGlobals();
38 -});
39 -
38 describe("useActiveThreadRef", () => {
39 it("keeps the same ref while the thread object is replaced during a run", async () => {
42 - const first = await render(thread("t1", "running"));
43 - const afterUpdate = await render(thread("t1", "waiting"));
40 + await using screen = await renderThread(thread("t1", "running"));
41 + const first = screen.current;
42 + const afterUpdate = await screen.update(thread("t1", "waiting"));
43
44 expect(first).toEqual({ environmentId: "env-1", threadId: "t1" });
45 expect(afterUpdate).toBe(first);
46 });
47
48 it("returns a new ref when the thread changes or goes away", async () => {
50 - const first = await render(thread("t1"));
51 - const switched = await render(thread("t2"));
52 - const gone = await render(null);
49 + await using screen = await renderThread(thread("t1"));
50 + const first = screen.current;
51 + const switched = await screen.update(thread("t2"));
52 + const gone = await screen.update(null);
53
54 expect(switched).not.toBe(first);
55 expect(switched).toEqual({ environmentId: "env-1", threadId: "t2" });
apps/web/src/hooks/useEnvironmentDisconnectDelay.browser.test.tsx
+28 -41
@@ -1,65 +1,52 @@
1 +import { act, fakeTimers, render } from "../../test/render";
2 import { EnvironmentId } from "@t3tools/contracts";
2 -import { act } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
3 +import { expect, it, vi } from "vite-plus/test";
4
5 import { useEnvironmentDisconnectDelay } from "./useEnvironmentDisconnectDelay";
6
7 const environmentId = EnvironmentId.make("remote");
9 -let root: Root;
10 -let container: HTMLDivElement;
11 -
8 function Probe({ unavailableId }: { unavailableId: EnvironmentId | null }) {
9 return <>{useEnvironmentDisconnectDelay(unavailableId) ? "Disconnected" : "Waiting"}</>;
10 }
11
16 -const shown = () => container.textContent;
17 -const render = (unavailableId: EnvironmentId | null) =>
18 - act(() => root.render(<Probe unavailableId={unavailableId} />));
19 -
20 -beforeEach(() => {
21 - vi.useFakeTimers();
22 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
23 - container = document.createElement("div");
24 - root = createRoot(container);
25 - render(environmentId);
26 -});
27 -
28 -afterEach(() => {
29 - act(() => root.unmount());
30 - vi.useRealTimers();
31 - vi.unstubAllGlobals();
32 -});
33 -
34 -it("waits 20 seconds without restarting on renders for the same environment", () => {
35 - act(() => vi.advanceTimersByTime(10_000));
12 +it("waits 20 seconds without restarting on renders for the same environment", async () => {
13 + using _timers = fakeTimers();
14 + await using screen = await render(<Probe unavailableId={environmentId} />, { router: false });
15 + const shown = () => screen.container.textContent;
16 + await act(() => vi.advanceTimersByTime(10_000));
17 expect(shown()).toBe("Waiting");
37 - render(environmentId);
38 - act(() => vi.advanceTimersByTime(9_999));
18 + await screen.rerender(<Probe unavailableId={environmentId} />);
19 + await act(() => vi.advanceTimersByTime(9_999));
20 expect(shown()).toBe("Waiting");
40 - act(() => vi.advanceTimersByTime(1));
21 + await act(() => vi.advanceTimersByTime(1));
22 expect(shown()).toBe("Disconnected");
23 });
24
44 -it("cancels a brief outage and starts a fresh delay on the next outage", () => {
45 - act(() => vi.advanceTimersByTime(10_000));
46 - render(null);
47 - act(() => vi.advanceTimersByTime(20_000));
25 +it("cancels a brief outage and starts a fresh delay on the next outage", async () => {
26 + using _timers = fakeTimers();
27 + await using screen = await render(<Probe unavailableId={environmentId} />, { router: false });
28 + const shown = () => screen.container.textContent;
29 + await act(() => vi.advanceTimersByTime(10_000));
30 + await screen.rerender(<Probe unavailableId={null} />);
31 + await act(() => vi.advanceTimersByTime(20_000));
32 expect(shown()).toBe("Waiting");
49 - render(environmentId);
50 - act(() => vi.advanceTimersByTime(19_999));
33 + await screen.rerender(<Probe unavailableId={environmentId} />);
34 + await act(() => vi.advanceTimersByTime(19_999));
35 expect(shown()).toBe("Waiting");
52 - act(() => vi.advanceTimersByTime(1));
36 + await act(() => vi.advanceTimersByTime(1));
37 expect(shown()).toBe("Disconnected");
54 - render(null);
38 + await screen.rerender(<Probe unavailableId={null} />);
39 expect(shown()).toBe("Waiting");
40 });
41
58 -it("does not carry elapsed time to another environment", () => {
59 - act(() => vi.advanceTimersByTime(20_000));
42 +it("does not carry elapsed time to another environment", async () => {
43 + using _timers = fakeTimers();
44 + await using screen = await render(<Probe unavailableId={environmentId} />, { router: false });
45 + const shown = () => screen.container.textContent;
46 + await act(() => vi.advanceTimersByTime(20_000));
47 expect(shown()).toBe("Disconnected");
61 - render(EnvironmentId.make("another-remote"));
48 + await screen.rerender(<Probe unavailableId={EnvironmentId.make("another-remote")} />);
49 expect(shown()).toBe("Waiting");
63 - act(() => vi.advanceTimersByTime(20_000));
50 + await act(() => vi.advanceTimersByTime(20_000));
51 expect(shown()).toBe("Disconnected");
52 });
apps/web/src/hooks/useHtmlRenderTheme.browser.test.tsx
+15 -28
@@ -1,9 +1,9 @@
1 import { HTML_RENDER_DEFAULT_FONTS, type HtmlRenderTheme } from "@t3tools/shared/htmlRender";
2 import { BUILT_IN_THEME_IDS } from "@t3tools/shared/themePalettes";
3 -import { act, useEffect } from "react";
4 -import { createRoot, type Root } from "react-dom/client";
5 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 +import { useEffect } from "react";
4 +import { describe, expect, it, vi } from "vite-plus/test";
5
6 +import { render } from "../../test/render";
7 import {
8 getStandardThemeColors,
9 setEnvironmentThemes,
@@ -24,21 +24,12 @@ vi.mock(import("./useTheme"), async (original) => ({
24 useTheme: (() => selection) as never,
25 }));
26
27 -let root: Root | undefined;
28 -
29 -beforeEach(() => {
30 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
31 - selection.themeHalves = null;
32 -});
33 -
34 -afterEach(() => {
35 - act(() => root?.unmount());
36 - root = undefined;
37 - setEnvironmentThemes([]);
38 - vi.unstubAllGlobals();
39 -});
27 +function setup(theme: ThemePreference, resolvedTheme: ThemeAppearance): Disposable {
28 + Object.assign(selection, { theme, resolvedTheme, themeHalves: null });
29 + return { [Symbol.dispose]: () => setEnvironmentThemes([]) };
30 +}
31
41 -function readRenderTheme(): HtmlRenderTheme {
32 +async function readRenderTheme(): Promise<HtmlRenderTheme> {
33 let theme: HtmlRenderTheme | undefined;
34 function Probe() {
35 const resolved = useHtmlRenderTheme();
@@ -47,9 +38,7 @@ function readRenderTheme(): HtmlRenderTheme {
38 }, [resolved]);
39 return null;
40 }
50 - act(() => root?.unmount());
51 - root = createRoot(document.createElement("div"));
52 - act(() => root!.render(<Probe />));
41 + await using _screen = await render(<Probe />);
42 if (!theme) throw new Error("The HTML render theme was not resolved.");
43 return theme;
44 }
@@ -58,11 +47,10 @@ describe("useHtmlRenderTheme", () => {
47 for (const appearance of ["light", "dark"] as const) {
48 it.each([appearance, ...BUILT_IN_THEME_IDS])(
49 `injects hex colors for %s in ${appearance} mode`,
61 - (preference) => {
62 - selection.theme = preference;
63 - selection.resolvedTheme = appearance;
50 + async (preference) => {
51 + using _selection = setup(preference, appearance);
52
65 - const theme = readRenderTheme();
53 + const theme = await readRenderTheme();
54
55 expect(theme.appearance).toBe(appearance);
56 for (const [variable, value] of Object.entries(theme.variables)) {
@@ -76,7 +64,8 @@ describe("useHtmlRenderTheme", () => {
64 );
65 }
66
79 - it("preserves alpha when converting a published palette", () => {
67 + it("preserves alpha when converting a published palette", async () => {
68 + using _selection = setup("transparent", "dark");
69 setEnvironmentThemes([
70 {
71 id: "transparent",
@@ -85,10 +74,8 @@ describe("useHtmlRenderTheme", () => {
74 colors: { ...getStandardThemeColors("dark"), accent: "oklch(0.5 0 0 / 0.5)" },
75 },
76 ]);
88 - selection.theme = "transparent";
89 - selection.resolvedTheme = "dark";
77
91 - const theme = readRenderTheme();
78 + const theme = await readRenderTheme();
79
80 expect(theme.variables["--accent"]).toBe("#63636380");
81 expect(theme.variables["--chart-1"]).toBe("#63636380");
apps/web/src/hooks/useLiveRefresh.browser.test.tsx
+43 -49
@@ -1,87 +1,81 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { describe, expect, it, vi } from "vite-plus/test";
2
3 +import { act, fakeTimers, render } from "../../test/render";
4 import { LIVE_REFRESH_IDLE_AFTER_MS, useLiveRefresh } from "./useLiveRefresh";
5
7 -let root: Root;
8 -let visibility: DocumentVisibilityState;
9 -const refresh = vi.fn();
10 -
11 -function setVisibility(next: DocumentVisibilityState) {
12 - visibility = next;
13 - document.dispatchEvent(new Event("visibilitychange"));
6 +function setup() {
7 + using stack = new DisposableStack();
8 + stack.use(fakeTimers());
9 + let visibility: DocumentVisibilityState = "visible";
10 + stack.use(vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility));
11 + const environment = stack.move();
12 + return {
13 + refresh: vi.fn(),
14 + setVisibility(next: DocumentVisibilityState) {
15 + visibility = next;
16 + document.dispatchEvent(new Event("visibilitychange"));
17 + },
18 + [Symbol.dispose]: () => environment.dispose(),
19 + };
20 }
21
16 -beforeEach(() => {
17 - vi.useFakeTimers();
18 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
19 - visibility = "visible";
20 - vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility);
21 - refresh.mockReset();
22 - root = createRoot(document.createElement("div"));
23 -});
24 -
25 -afterEach(() => {
26 - act(() => root.unmount());
27 - vi.restoreAllMocks();
28 - vi.useRealTimers();
29 - vi.unstubAllGlobals();
30 -});
31 -
22 describe("live refresh cadence", () => {
33 - it("polls every 45 seconds, pauses while hidden or busy, respects disabling, and cleans up", () => {
23 + it("polls every 45 seconds, pauses while hidden or busy, respects disabling, and cleans up", async () => {
24 + using env = setup();
25 + const { refresh } = env;
26 vi.setSystemTime(0);
27 function Probe({ pending = false, enabled = true }) {
28 useLiveRefresh(pending ? null : refresh, { intervalMs: 45_000, enabled });
29 return null;
30 }
39 - act(() => root.render(<Probe />));
40 - act(() => vi.advanceTimersByTime(44_999));
31 + await using screen = await render(<Probe />);
32 + await act(() => vi.advanceTimersByTime(44_999));
33 expect(refresh).not.toHaveBeenCalled();
42 - act(() => vi.advanceTimersByTime(1));
34 + await act(() => vi.advanceTimersByTime(1));
35 expect(refresh).toHaveBeenCalledTimes(1);
44 - act(() => vi.advanceTimersByTime(45_000));
36 + await act(() => vi.advanceTimersByTime(45_000));
37 expect(refresh).toHaveBeenCalledTimes(2);
46 - setVisibility("hidden");
47 - act(() => vi.advanceTimersByTime(90_000));
38 + env.setVisibility("hidden");
39 + await act(() => vi.advanceTimersByTime(90_000));
40 expect(refresh).toHaveBeenCalledTimes(2);
49 - setVisibility("visible");
41 + env.setVisibility("visible");
42 window.dispatchEvent(new Event("focus"));
43 expect(refresh).toHaveBeenCalledTimes(3);
52 - act(() => root.render(<Probe pending />));
53 - act(() => vi.advanceTimersByTime(45_000));
44 + await screen.rerender(<Probe pending />);
45 + await act(() => vi.advanceTimersByTime(45_000));
46 expect(refresh).toHaveBeenCalledTimes(3);
55 - act(() => root.render(<Probe />));
56 - act(() => vi.advanceTimersByTime(45_000));
47 + await screen.rerender(<Probe />);
48 + await act(() => vi.advanceTimersByTime(45_000));
49 expect(refresh).toHaveBeenCalledTimes(4);
58 - act(() => root.render(<Probe enabled={false} />));
59 - act(() => vi.advanceTimersByTime(90_000));
50 + await screen.rerender(<Probe enabled={false} />);
51 + await act(() => vi.advanceTimersByTime(90_000));
52 window.dispatchEvent(new Event("focus"));
53 expect(refresh).toHaveBeenCalledTimes(4);
62 - act(() => root.render(null));
63 - act(() => vi.advanceTimersByTime(45_000));
54 + await screen.rerender(null);
55 + await act(() => vi.advanceTimersByTime(45_000));
56 expect(refresh).toHaveBeenCalledTimes(4);
57 });
58
59 it.each(["focus", "visibilitychange"])(
60 "keeps an idle view paused after %s until input",
69 - (event) => {
61 + async (event) => {
62 + using env = setup();
63 + const { refresh } = env;
64 vi.setSystemTime(1_000_000);
65 function Probe() {
66 useLiveRefresh(refresh, { intervalMs: 45_000 });
67 return null;
68 }
75 - act(() => root.render(<Probe />));
76 - act(() => vi.advanceTimersByTime(LIVE_REFRESH_IDLE_AFTER_MS));
69 + await using _screen = await render(<Probe />);
70 + await act(() => vi.advanceTimersByTime(LIVE_REFRESH_IDLE_AFTER_MS));
71 refresh.mockClear();
78 - act(() => (event === "focus" ? window : document).dispatchEvent(new Event(event)));
72 + await act(() => (event === "focus" ? window : document).dispatchEvent(new Event(event)));
73 expect(refresh).not.toHaveBeenCalled();
80 - act(() => vi.advanceTimersByTime(90_000));
74 + await act(() => vi.advanceTimersByTime(90_000));
75 expect(refresh).not.toHaveBeenCalled();
82 - act(() => document.dispatchEvent(new Event("pointerdown")));
76 + await act(() => document.dispatchEvent(new Event("pointerdown")));
77 expect(refresh).toHaveBeenCalledTimes(1);
84 - act(() => vi.advanceTimersByTime(45_000));
78 + await act(() => vi.advanceTimersByTime(45_000));
79 expect(refresh).toHaveBeenCalledTimes(2);
80 },
81 );
apps/web/src/hooks/useLocalStorage.hook.browser.test.tsx
+32 -31
@@ -1,51 +1,52 @@
1 import * as Schema from "effect/Schema";
2 -import { act, createElement, useEffect } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2 +import { useEffect } from "react";
3 +import { describe, expect, it, vi } from "vite-plus/test";
4
5 +import { act, render } from "../../test/render";
6 import { useLocalStorage } from "./useLocalStorage";
7
8 const KEY = "corrupt-key";
9 -let root: Root;
10 -let current: ReturnType<typeof useLocalStorage<number, number>>;
9 +type StoredNumber = ReturnType<typeof useLocalStorage<number, number>>;
10
12 -function Probe() {
13 - const result = useLocalStorage(KEY, 0, Schema.Number);
14 - useEffect(() => {
15 - current = result;
16 - });
17 - return null;
18 -}
19 -
20 -beforeEach(async () => {
21 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
22 - vi.spyOn(console, "error").mockImplementation(() => {});
11 +async function renderWithCorruptValue() {
12 + await using stack = new AsyncDisposableStack();
13 + stack.use(vi.spyOn(console, "error").mockImplementation(() => {}));
14 localStorage.setItem(KEY, JSON.stringify("not a number"));
24 - root = createRoot(document.createElement("div"));
25 - await act(() => root.render(createElement(Probe)));
26 -});
27 -
28 -afterEach(async () => {
29 - await act(() => root.unmount());
30 - localStorage.clear();
31 - vi.restoreAllMocks();
32 - vi.unstubAllGlobals();
33 -});
15 + stack.defer(() => localStorage.clear());
16 + let current: StoredNumber | undefined;
17 + function Probe() {
18 + const result = useLocalStorage(KEY, 0, Schema.Number);
19 + useEffect(() => {
20 + current = result;
21 + });
22 + return null;
23 + }
24 + stack.use(await render(<Probe />));
25 + const environment = stack.move();
26 + return {
27 + get current() {
28 + return current!;
29 + },
30 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
31 + };
32 +}
33
34 describe("useLocalStorage with a stored value that fails decode", () => {
35 it("replaces it with a plain write", async () => {
37 - expect(current[0]).toBe(0);
36 + await using stored = await renderWithCorruptValue();
37 + expect(stored.current[0]).toBe(0);
38
39 - await act(() => current[1](42));
39 + await act(() => stored.current[1](42));
40
41 expect(localStorage.getItem(KEY)).toBe("42");
42 - expect(current[0]).toBe(42);
42 + expect(stored.current[0]).toBe(42);
43 });
44
45 it("runs an updater from the initial value", async () => {
46 - await act(() => current[1]((value) => value + 1));
46 + await using stored = await renderWithCorruptValue();
47 + await act(() => stored.current[1]((value) => value + 1));
48
49 expect(localStorage.getItem(KEY)).toBe("1");
49 - expect(current[0]).toBe(1);
50 + expect(stored.current[0]).toBe(1);
51 });
52 });
apps/web/src/hooks/usePullRequestChecksRefresh.browser.test.tsx
+30 -45
@@ -1,32 +1,18 @@
1 import type { PullRequestCheck } from "@t3tools/contracts";
2 -import { act } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
2 +import { expect, it, vi } from "vite-plus/test";
3
4 +import { act, fakeTimers, render } from "../../test/render";
5 import { usePullRequestChecksRefresh } from "./usePullRequestChecksRefresh";
6
8 -let root: Root;
9 -let visibility: DocumentVisibilityState;
10 -
11 -beforeEach(() => {
12 - vi.useFakeTimers();
13 - vi.setSystemTime(1_000_000);
14 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
15 - visibility = "visible";
16 - vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility);
17 - root = createRoot(document.createElement("div"));
18 -});
19 -
20 -afterEach(() => {
21 - act(() => root.unmount());
22 - vi.restoreAllMocks();
23 - vi.useRealTimers();
24 - vi.unstubAllGlobals();
25 -});
26 -
7 it.each(["pending", "action-required"] as const)(
8 "polls quiet PRs each minute, speeds up for %s or missing checks, resumes from idle, and stops for closed PRs",
29 - (pendingStatus) => {
9 + async (pendingStatus) => {
10 + using _timers = fakeTimers();
11 + vi.setSystemTime(1_000_000);
12 + let visibility: DocumentVisibilityState = "visible";
13 + using _visibility = vi
14 + .spyOn(document, "visibilityState", "get")
15 + .mockImplementation(() => visibility);
16 const refresh = vi.fn();
17 function Probe({
18 status = "success",
@@ -43,46 +29,45 @@ it.each(["pending", "action-required"] as const)(
29 });
30 return null;
31 }
46 - const update = (props: Parameters<typeof Probe>[0]) =>
47 - act(() => root.render(<Probe {...props} />));
32 + await using screen = await render(<Probe />);
33 + const update = (props: Parameters<typeof Probe>[0]) => screen.rerender(<Probe {...props} />);
34 const advance = (ms: number) => act(() => vi.advanceTimersByTime(ms));
35
50 - update({});
51 - advance(59_999);
36 + await advance(59_999);
37 expect(refresh).toHaveBeenCalledTimes(0);
53 - advance(1);
38 + await advance(1);
39 expect(refresh).toHaveBeenCalledTimes(1);
55 - update({ status: pendingStatus });
56 - advance(44_999);
40 + await update({ status: pendingStatus });
41 + await advance(44_999);
42 expect(refresh).toHaveBeenCalledTimes(1);
58 - advance(1);
43 + await advance(1);
44 expect(refresh).toHaveBeenCalledTimes(2);
60 - update({ status: "failure" });
61 - advance(60_000);
45 + await update({ status: "failure" });
46 + await advance(60_000);
47 expect(refresh).toHaveBeenCalledTimes(3);
63 - update({ status: null });
48 + await update({ status: null });
49 for (let tick = 0; tick < 3; tick++) {
65 - advance(45_000);
66 - update({ status: null });
50 + await advance(45_000);
51 + await update({ status: null });
52 }
53 expect(refresh).toHaveBeenCalledTimes(6);
69 - advance(44_999);
54 + await advance(44_999);
55 expect(refresh).toHaveBeenCalledTimes(6);
71 - advance(1);
56 + await advance(1);
57 expect(refresh).toHaveBeenCalledTimes(7);
73 - advance(6 * 60_000);
58 + await advance(6 * 60_000);
59 const beforeResume = refresh.mock.calls.length;
75 - act(() => document.dispatchEvent(new Event("pointerdown")));
60 + await act(() => document.dispatchEvent(new Event("pointerdown")));
61 expect(refresh).toHaveBeenCalledTimes(beforeResume + 1);
62 visibility = "hidden";
78 - act(() => document.dispatchEvent(new Event("visibilitychange")));
79 - advance(60_000);
63 + await act(() => document.dispatchEvent(new Event("visibilitychange")));
64 + await advance(60_000);
65 expect(refresh).toHaveBeenCalledTimes(beforeResume + 1);
66 visibility = "visible";
82 - act(() => document.dispatchEvent(new Event("visibilitychange")));
67 + await act(() => document.dispatchEvent(new Event("visibilitychange")));
68 expect(refresh).toHaveBeenCalledTimes(beforeResume + 2);
84 - update({ enabled: false });
85 - advance(120_000);
69 + await update({ enabled: false });
70 + await advance(120_000);
71 expect(refresh).toHaveBeenCalledTimes(beforeResume + 2);
72 },
73 );
apps/web/src/hooks/useResizableWidth.browser.test.tsx
+100 -84
@@ -1,16 +1,9 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import type { ReactNode } from "react";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3
4 +import { act, render, type Screen } from "../../test/render";
5 import { RESIZABLE_WIDTH_PROPERTY, useResizableWidth } from "./useResizableWidth";
6
7 -let root: Root;
8 -let container: HTMLDivElement;
9 -let captured = false;
10 -let frame: FrameRequestCallback | undefined;
11 -const cancelAnimationFrame = vi.fn();
12 -let setItem: ReturnType<typeof vi.spyOn<Storage, "setItem">>;
13 -
7 function Panel({
8 edge = "left",
9 maxWidth = 800,
@@ -35,97 +28,106 @@ function Panel({
28 );
29 }
30
38 -const host = () => container.querySelector<HTMLElement>("[data-testid=host]")!;
39 -const shownWidth = () => Number(container.querySelector("output")!.textContent);
40 -const liveWidth = () => host().style.getPropertyValue(RESIZABLE_WIDTH_PROPERTY);
41 -const bodyStyle = () => document.body.style;
42 -
43 -function handle() {
44 - const element = container.querySelector<HTMLElement>("[data-testid=handle]")!;
45 - // Synthetic pointers have no active pointer for the browser to capture.
46 - element.setPointerCapture = () => {
47 - captured = true;
48 - };
49 - element.hasPointerCapture = () => captured;
50 - element.releasePointerCapture = () => {
51 - captured = false;
52 - };
53 - return element;
54 -}
55 -
56 -function pointer(
57 - type: "pointerdown" | "pointermove" | "pointerup" | "pointercancel" | "lostpointercapture",
58 - clientX = 100,
59 -) {
60 - handle().dispatchEvent(
61 - new PointerEvent(type, { bubbles: true, cancelable: true, button: 0, pointerId: 1, clientX }),
31 +async function renderPanel() {
32 + await using stack = new AsyncDisposableStack();
33 + let captured = false;
34 + let frame: FrameRequestCallback | undefined;
35 + const cancelAnimationFrame = vi.fn();
36 + stack.use(
37 + vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
38 + frame = callback;
39 + return 42;
40 + }),
41 );
63 -}
42 + stack.use(vi.spyOn(window, "cancelAnimationFrame").mockImplementation(cancelAnimationFrame));
43 + const setItem = stack.use(vi.spyOn(Storage.prototype, "setItem"));
44 + localStorage.clear();
45 + stack.defer(() => localStorage.clear());
46 + let screen: Screen = stack.use(await render(<Panel />));
47 + const container = () => screen.container;
48 + const host = () => container().querySelector<HTMLElement>("[data-testid=host]")!;
49
65 -async function render(element = <Panel />) {
66 - await act(() => root.render(element));
67 -}
50 + function handle() {
51 + const element = container().querySelector<HTMLElement>("[data-testid=handle]")!;
52 + // Synthetic pointers have no active pointer for the browser to capture.
53 + element.setPointerCapture = () => {
54 + captured = true;
55 + };
56 + element.hasPointerCapture = () => captured;
57 + element.releasePointerCapture = () => {
58 + captured = false;
59 + };
60 + return element;
61 + }
62
69 -async function mountFresh(element = <Panel />) {
70 - root = createRoot(container);
71 - await render(element);
63 + const environment = stack.move();
64 + return {
65 + setItem,
66 + cancelAnimationFrame,
67 + get captured() {
68 + return captured;
69 + },
70 + frame: () => frame?.(0),
71 + host,
72 + shownWidth: () => Number(container().querySelector("output")!.textContent),
73 + liveWidth: () => host().style.getPropertyValue(RESIZABLE_WIDTH_PROPERTY),
74 + pointer(
75 + type: "pointerdown" | "pointermove" | "pointerup" | "pointercancel" | "lostpointercapture",
76 + clientX = 100,
77 + ) {
78 + handle().dispatchEvent(
79 + new PointerEvent(type, {
80 + bubbles: true,
81 + cancelable: true,
82 + button: 0,
83 + pointerId: 1,
84 + clientX,
85 + }),
86 + );
87 + },
88 + rerender: (element: ReactNode = <Panel />) => screen.rerender(element),
89 + unmount: () => screen.unmount(),
90 + async mountFresh(element: ReactNode = <Panel />) {
91 + screen = environment.use(await render(element));
92 + },
93 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
94 + };
95 }
96
74 -beforeEach(async () => {
75 - localStorage.clear();
76 - captured = false;
77 - frame = undefined;
78 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
79 - vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
80 - frame = callback;
81 - return 42;
82 - });
83 - vi.spyOn(window, "cancelAnimationFrame").mockImplementation(cancelAnimationFrame);
84 - setItem = vi.spyOn(Storage.prototype, "setItem");
85 - container = document.createElement("div");
86 - document.body.append(container);
87 - await mountFresh();
88 -});
89 -
90 -afterEach(async () => {
91 - await act(() => root.unmount());
92 - container.remove();
93 - localStorage.clear();
94 - vi.restoreAllMocks();
95 - vi.unstubAllGlobals();
96 - cancelAnimationFrame.mockClear();
97 -});
97 +const bodyStyle = () => document.body.style;
98
99 describe("panel resize cleanup", () => {
100 it.each(["unmount", "lost capture", "blur", "cancel"])(
101 "clears the cursor and pending resize after %s",
102 async (reason) => {
103 + await using panel = await renderPanel();
104 + const { pointer, host, shownWidth, liveWidth, setItem, cancelAnimationFrame } = panel;
105 await act(() => {
106 pointer("pointerdown");
107 pointer("pointermove", 50);
108 });
109 const resizedHost = host();
108 - await act(() => frame?.(0));
110 + await act(() => panel.frame());
111 expect(liveWidth()).toBe("450px");
112 expect(resizedHost.style.getPropertyValue("transition-property")).toBe("none");
113 expect(shownWidth()).toBe(400);
114 await act(() => pointer("pointermove", 25));
115 expect(bodyStyle().cursor).toBe("col-resize");
116 expect(bodyStyle().userSelect).toBe("none");
117 + if (reason === "unmount") await panel.unmount();
118 await act(() => {
116 - if (reason === "unmount") root.unmount();
119 if (reason === "lost capture") pointer("lostpointercapture");
120 if (reason === "blur") window.dispatchEvent(new Event("blur"));
121 if (reason === "cancel") pointer("pointercancel");
122 });
123 expect(bodyStyle().cursor).toBe("");
124 expect(bodyStyle().userSelect).toBe("");
123 - expect(captured).toBe(false);
125 + expect(panel.captured).toBe(false);
126 expect(resizedHost.style.getPropertyValue("transition-property")).toBe("");
127 expect(cancelAnimationFrame).toHaveBeenCalledWith(42);
128 if (reason === "unmount") {
129 expect(setItem).not.toHaveBeenCalled();
128 - await mountFresh();
130 + await panel.mountFresh();
131 } else {
132 expect(shownWidth()).toBe(475);
133 expect(setItem).toHaveBeenCalledExactlyOnceWith("test-panel-width", "475");
@@ -136,7 +138,9 @@ describe("panel resize cleanup", () => {
138 it.each(["left", "right"] as const)(
139 "uses the release position for a fast %s-edge drag",
140 async (edge) => {
139 - await render(<Panel edge={edge} />);
141 + await using panel = await renderPanel();
142 + const { pointer, shownWidth, setItem, cancelAnimationFrame } = panel;
143 + await panel.rerender(<Panel edge={edge} />);
144 await act(() => {
145 pointer("pointerdown");
146 pointer("pointermove", edge === "left" ? 50 : 150);
@@ -152,16 +156,18 @@ describe("panel resize cleanup", () => {
156 [800, 450],
157 [450, 800],
158 ])("uses updated bounds during a drag from max %s to %s", async (initialMax, nextMax) => {
155 - await render(<Panel maxWidth={initialMax} />);
159 + await using panel = await renderPanel();
160 + const { pointer, shownWidth, liveWidth, setItem } = panel;
161 + await panel.rerender(<Panel maxWidth={initialMax} />);
162 await act(() => {
163 pointer("pointerdown");
164 pointer("pointermove", -200);
165 });
160 - await act(() => frame?.(0));
166 + await act(() => panel.frame());
167 expect(liveWidth()).toBe(`${Math.min(700, initialMax)}px`);
162 - await render(<Panel maxWidth={nextMax} />);
168 + await panel.rerender(<Panel maxWidth={nextMax} />);
169 await act(() => pointer("pointermove", -250));
164 - await act(() => frame?.(0));
170 + await act(() => panel.frame());
171 expect(liveWidth()).toBe(`${Math.min(750, nextMax)}px`);
172 await act(() => pointer("pointerup", -300));
173 expect(shownWidth()).toBe(nextMax);
@@ -169,6 +175,8 @@ describe("panel resize cleanup", () => {
175 });
176
177 it("handles release before any move event", async () => {
178 + await using panel = await renderPanel();
179 + const { pointer, shownWidth, setItem } = panel;
180 await act(() => {
181 pointer("pointerdown");
182 pointer("pointerup", 25);
@@ -178,6 +186,8 @@ describe("panel resize cleanup", () => {
186 });
187
188 it("clamps the release position to the panel bounds", async () => {
189 + await using panel = await renderPanel();
190 + const { pointer, shownWidth, setItem } = panel;
191 await act(() => {
192 pointer("pointerdown");
193 pointer("pointerup", -1000);
@@ -187,6 +197,8 @@ describe("panel resize cleanup", () => {
197 });
198
199 it("saves the final width when release is followed by lost capture", async () => {
200 + await using panel = await renderPanel();
201 + const { pointer, shownWidth, setItem } = panel;
202 await act(() => {
203 pointer("pointerdown");
204 pointer("pointermove", 50);
@@ -196,19 +208,21 @@ describe("panel resize cleanup", () => {
208 expect(shownWidth()).toBe(450);
209 expect(setItem).toHaveBeenCalledExactlyOnceWith("test-panel-width", "450");
210 expect(bodyStyle().cursor).toBe("");
199 - expect(captured).toBe(false);
211 + expect(panel.captured).toBe(false);
212 });
213 });
214
215 describe("panel width storage changes", () => {
216 it("restores separate thread widths without remounting and retains them after reload", async () => {
217 + await using panel = await renderPanel();
218 + const { pointer, shownWidth } = panel;
219 await act(() => {
220 pointer("pointerdown");
221 pointer("pointermove", 50);
222 pointer("pointerup", 50);
223 });
224 expect(shownWidth()).toBe(450);
211 - await render(<Panel storageKey="thread-b" />);
225 + await panel.rerender(<Panel storageKey="thread-b" />);
226 expect(shownWidth()).toBe(400);
227 await act(() => {
228 pointer("pointerdown");
@@ -216,35 +230,37 @@ describe("panel width storage changes", () => {
230 pointer("pointerup", -100);
231 });
232 expect(shownWidth()).toBe(600);
219 - await render(<Panel />);
233 + await panel.rerender(<Panel />);
234 expect(shownWidth()).toBe(450);
221 - await act(() => root.unmount());
222 - await mountFresh(<Panel storageKey="thread-b" />);
235 + await panel.unmount();
236 + await panel.mountFresh(<Panel storageKey="thread-b" />);
237 expect(shownWidth()).toBe(600);
238 });
239
240 it("cancels an unfinished drag on a thread switch without saving it to either thread", async () => {
241 + await using panel = await renderPanel();
242 + const { pointer, shownWidth, liveWidth, setItem } = panel;
243 localStorage.setItem("thread-b", "650");
244 setItem.mockClear();
245 await act(() => {
246 pointer("pointerdown");
247 pointer("pointermove", 50);
248 });
233 - await act(() => frame?.(0));
249 + await act(() => panel.frame());
250 expect(liveWidth()).toBe("450px");
251 await act(() => pointer("pointermove", 25));
236 - await render(<Panel storageKey="thread-b" />);
252 + await panel.rerender(<Panel storageKey="thread-b" />);
253 expect(shownWidth()).toBe(650);
254 expect(liveWidth()).toBe("650px");
239 - expect(captured).toBe(false);
255 + expect(panel.captured).toBe(false);
256 expect(bodyStyle().cursor).toBe("");
257 await act(() => {
242 - frame?.(0);
258 + panel.frame();
259 pointer("pointerup", 25);
260 });
261 expect(shownWidth()).toBe(650);
262 expect(setItem).not.toHaveBeenCalled();
247 - await render(<Panel />);
263 + await panel.rerender(<Panel />);
264 expect(shownWidth()).toBe(400);
265 });
266 });
apps/web/src/hooks/useSettings.favorites.browser.test.tsx
+73 -51
@@ -13,9 +13,10 @@ import {
13 import * as Cause from "effect/Cause";
14 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
15 import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
16 -import { act } from "react";
17 -import { createRoot, type Root } from "react-dom/client";
18 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
16 +import type { ReactNode } from "react";
17 +import { describe, expect, it, vi } from "vite-plus/test";
18 +
19 +import { act, render, type Screen } from "../../test/render";
20
21 const state = vi.hoisted(() => ({
22 settings: new Map<string, unknown>(),
@@ -70,51 +71,39 @@ const initialSettings = {
71 favorites: [],
72 providerModelPreferences: {},
73 } satisfies ServerSettings;
73 -let registry: AtomRegistry.AtomRegistry;
74 -let root: Root;
75 -let container: HTMLDivElement;
76 -let durable: Map<EnvironmentId, ServerSettings>;
77 -let toggles: Array<() => Promise<void>>;
78 -let pendingClick: Promise<void> | undefined;
79 -let writes: Array<{
74 +interface Write {
75 environmentId: EnvironmentId;
76 patch: ServerSettingsPatch;
77 finish: (success?: boolean) => void;
83 -}>;
78 +}
79
80 const settingsAtom = (id: EnvironmentId) =>
81 state.settings.get(id) as Atom.Writable<ServerSettings | null>;
82
88 -function FavoriteEditor({ environmentId }: { environmentId: EnvironmentId }) {
83 +function FavoriteEditor({
84 + environmentId,
85 + toggles,
86 + onClicked,
87 +}: {
88 + environmentId: EnvironmentId;
89 + toggles: Array<() => Promise<void>>;
90 + onClicked: (pending: Promise<void>) => void;
91 +}) {
92 const toggle = useToggleEnvironmentModelFavorite(environmentId);
93 const onClick = () => toggle(provider, model);
94 toggles.push(onClick);
92 - return <button onClick={() => void (pendingClick = onClick())}>Toggle favorite</button>;
93 -}
94 -
95 -function mount(environmentId = primaryId) {
96 - return act(() =>
97 - root.render(
98 - <RegistryContext.Provider value={registry}>
99 - <FavoriteEditor environmentId={environmentId} />
100 - </RegistryContext.Provider>,
101 - ),
102 - );
103 -}
104 -
105 -function click(): Promise<void> {
106 - container.querySelector("button")!.click();
107 - return pendingClick!;
95 + return <button onClick={() => onClicked(onClick())}>Toggle favorite</button>;
96 }
97
110 -beforeEach(() => {
111 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
112 - registry = AtomRegistry.make();
98 +async function setup() {
99 + await using stack = new AsyncDisposableStack();
100 + const registry = stack.adopt(AtomRegistry.make(), (registry) => registry.dispose());
101 state.settings.clear();
102 state.connections.clear();
115 - durable = new Map();
116 - toggles = [];
117 - writes = [];
103 + const durable = new Map<EnvironmentId, ServerSettings>();
104 + const toggles: Array<() => Promise<void>> = [];
105 + const writes: Write[] = [];
106 + let pendingClick: Promise<void> | undefined;
107 for (const id of [primaryId, remoteId]) {
108 state.settings.set(id, Atom.make<ServerSettings | null>(initialSettings));
109 durable.set(id, initialSettings);
@@ -143,22 +132,45 @@ beforeEach(() => {
132 });
133 }),
134 );
146 - container = document.createElement("div");
147 - document.body.append(container);
148 - root = createRoot(container);
149 -});
135
151 -afterEach(async () => {
152 - await act(() => root.unmount());
153 - container.remove();
154 - registry.dispose();
155 - vi.unstubAllGlobals();
156 -});
136 + const environment = stack.move();
137 + let screen: Screen | undefined;
138 + const show = async (ui: ReactNode) => {
139 + const tree = <RegistryContext.Provider value={registry}>{ui}</RegistryContext.Provider>;
140 + if (screen) await screen.rerender(tree);
141 + else screen = environment.use(await render(tree));
142 + };
143 +
144 + return {
145 + registry,
146 + durable,
147 + toggles,
148 + writes,
149 + show,
150 + mount: (environmentId = primaryId) =>
151 + show(
152 + <FavoriteEditor
153 + environmentId={environmentId}
154 + toggles={toggles}
155 + onClicked={(pending) => {
156 + pendingClick = pending;
157 + }}
158 + />,
159 + ),
160 + click(): Promise<void> {
161 + screen!.container.querySelector("button")!.click();
162 + return pendingClick!;
163 + },
164 + [Symbol.asyncDispose]: () => environment.disposeAsync(),
165 + };
166 +}
167
168 describe("environment favorite toggles", () => {
169 it.each([false, true])(
170 "toggles twice before any server echo when initially favorited=%s",
171 async (initiallyFavorited) => {
172 + await using fixture = await setup();
173 + const { registry, durable, writes, mount, click } = fixture;
174 const favorites = initiallyFavorited ? [{ provider, model }] : [];
175 const settings = { ...initialSettings, favorites };
176 registry.set(settingsAtom(primaryId), settings);
@@ -180,6 +192,8 @@ describe("environment favorite toggles", () => {
192 );
193
194 it("keeps the newest pending intent when an earlier write completes", async () => {
195 + await using fixture = await setup();
196 + const { durable, writes, mount, click } = fixture;
197 await mount();
198 const first = click();
199 const second = click();
@@ -201,6 +215,8 @@ describe("environment favorite toggles", () => {
215 });
216
217 it("clears failed intent so a retry still adds the favorite", async () => {
218 + await using fixture = await setup();
219 + const { durable, writes, mount, click } = fixture;
220 await mount();
221 const failed = click();
222 await act(async () => {});
@@ -214,6 +230,8 @@ describe("environment favorite toggles", () => {
230 });
231
232 it("toggles the acknowledged choice when the RPC reply precedes its server echo", async () => {
233 + await using fixture = await setup();
234 + const { registry, durable, writes, mount, click } = fixture;
235 await mount();
236 const first = click();
237 await act(async () => {});
@@ -228,6 +246,8 @@ describe("environment favorite toggles", () => {
246 });
247
248 it("uses a later remote change instead of a cached acknowledged choice", async () => {
249 + await using fixture = await setup();
250 + const { registry, durable, writes, mount, click } = fixture;
251 await mount();
252 const first = click();
253 await act(async () => {});
@@ -244,6 +264,8 @@ describe("environment favorite toggles", () => {
264 });
265
266 it("preserves an acknowledged add when a later remove fails before its echo", async () => {
267 + await using fixture = await setup();
268 + const { durable, writes, mount, click } = fixture;
269 await mount();
270 const first = click();
271 await act(async () => {});
@@ -261,6 +283,8 @@ describe("environment favorite toggles", () => {
283 });
284
285 it("does not reuse another environment's pending intent for the same model", async () => {
286 + await using fixture = await setup();
287 + const { durable, writes, mount, click } = fixture;
288 await mount();
289 const primary = click();
290 await mount(remoteId);
@@ -275,6 +299,8 @@ describe("environment favorite toggles", () => {
299 });
300
301 it("reads the latest server state even when the click callback predates its echo", async () => {
302 + await using fixture = await setup();
303 + const { registry, durable, toggles, writes, mount } = fixture;
304 await mount();
305 const previousClick = toggles.at(-1)!;
306 const updated = { ...initialSettings, favorites: [{ provider, model }] };
@@ -297,6 +323,8 @@ describe("legacy model preferences migration", () => {
323 it.each(["succeeds", "fails"] as const)(
324 "waits for connection and retries only after reconnect when the first save %s",
325 async (outcome) => {
326 + await using fixture = await setup();
327 + const { registry, show } = fixture;
328 const environmentId = EnvironmentId.make(`migration-${outcome}`);
329 const otherId = EnvironmentId.make(`other-${outcome}`);
330 for (const id of [environmentId, otherId]) {
@@ -326,13 +354,7 @@ describe("legacy model preferences migration", () => {
354 .mockReturnValueOnce(firstSave)
355 .mockResolvedValue(AsyncResult.success(DEFAULT_SERVER_SETTINGS));
356 const renderReader = (id = environmentId) =>
329 - act(() =>
330 - root.render(
331 - <RegistryContext.Provider value={registry}>
332 - <ModelPreferencesReader key={id} environmentId={id} />
333 - </RegistryContext.Provider>,
334 - ),
335 - );
357 + show(<ModelPreferencesReader key={id} environmentId={id} />);
358 const connect = (id: EnvironmentId, generation: number) =>
359 act(() =>
360 registry.set(
apps/web/src/hooks/useSettings.selector.browser.test.tsx
+26 -30
@@ -1,6 +1,7 @@
1 -import { act, createElement, Profiler, useEffect, type ReactNode } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { createElement, Profiler, useEffect, type ReactNode } from "react";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3 +
4 +import { act, render } from "../../test/render";
5
6 vi.mock("~/localApi", () => ({
7 ensureLocalApi: () => ({
@@ -15,11 +16,12 @@ import {
16 useClientSettings,
17 } from "./useSettings";
18
18 -const renders = { meter: 0, grouping: 0 };
19 -const seen = { grouping: [] as unknown[] };
20 -let root: Root;
19 +interface Counts {
20 + readonly renders: { meter: number; grouping: number };
21 + readonly grouping: unknown[];
22 +}
23
22 -function counted(key: keyof typeof renders, child: ReactNode) {
24 +function counted(renders: Counts["renders"], key: keyof typeof renders, child: ReactNode) {
25 return createElement(
26 Profiler,
27 {
@@ -37,43 +39,35 @@ function MeterReader() {
39 return createElement("span", null, String(enabled));
40 }
41
40 -function GroupingReader() {
42 +function GroupingReader({ seen }: { seen: unknown[] }) {
43 const grouping = useClientSettings((settings) => ({
44 mode: settings.sidebarProjectGroupingMode,
45 overrides: settings.sidebarProjectGroupingOverrides,
46 }));
47 useEffect(() => {
46 - seen.grouping.push(grouping);
48 + seen.push(grouping);
49 });
50 return null;
51 }
52
51 -beforeEach(async () => {
52 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
53 +async function renderReaders() {
54 await ensureClientSettingsHydrated();
54 - renders.meter = 0;
55 - renders.grouping = 0;
56 - seen.grouping = [];
57 - root = createRoot(document.createElement("div"));
58 - await act(() =>
59 - root.render(
60 - createElement(
61 - "div",
62 - null,
63 - counted("meter", createElement(MeterReader)),
64 - counted("grouping", createElement(GroupingReader)),
65 - ),
55 + const counts: Counts = { renders: { meter: 0, grouping: 0 }, grouping: [] };
56 + const screen = await render(
57 + createElement(
58 + "div",
59 + null,
60 + counted(counts.renders, "meter", createElement(MeterReader)),
61 + counted(counts.renders, "grouping", createElement(GroupingReader, { seen: counts.grouping })),
62 ),
63 );
68 -});
69 -
70 -afterEach(async () => {
71 - await act(() => root.unmount());
72 - vi.unstubAllGlobals();
73 -});
64 + return { ...counts, [Symbol.asyncDispose]: () => screen[Symbol.asyncDispose]() };
65 +}
66
67 describe("useClientSettings(selector)", () => {
68 it("re-renders only readers whose selected value changed", async () => {
69 + await using readers = await renderReaders();
70 + const { renders } = readers;
71 const before = { ...renders };
72
73 await act(() =>
@@ -87,11 +81,13 @@ describe("useClientSettings(selector)", () => {
81 });
82
83 it("keeps a structurally equal object selection", async () => {
84 + await using readers = await renderReaders();
85 + const { renders } = readers;
86 const before = renders.grouping;
87
88 await act(() => persistClientSettingsPatch({ sidebarProjectGroupingOverrides: {} }));
89
90 expect(renders.grouping).toBe(before);
95 - expect(new Set(seen.grouping).size).toBe(1);
91 + expect(new Set(readers.grouping).size).toBe(1);
92 });
93 });
apps/web/src/hooks/useSettings.sync.browser.test.tsx
+37 -45
@@ -9,9 +9,9 @@ import {
9 } from "@t3tools/contracts";
10 import * as Cause from "effect/Cause";
11 import { AsyncResult, Atom } from "effect/reactivity";
12 -import { act } from "react";
13 -import { createRoot, type Root } from "react-dom/client";
14 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
12 +import { describe, expect, it, vi } from "vite-plus/test";
13 +
14 +import { act, render } from "../../test/render";
15
16 type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
17 const state = vi.hoisted(() => ({
@@ -67,34 +67,28 @@ const session = (scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState
67 sessionCookieName: "t3_session",
68 },
69 });
70 -let root: Root;
71 -let container: HTMLDivElement;
72 -let handlers: Array<() => void> = [];
73 -
74 -function SettingsEditor() {
70 +function SettingsEditor({ handlers }: { handlers: Array<() => void> }) {
71 const updateSettings = useUpdatePrimarySettings();
72 const save = () => void updateSettings(patch);
73 handlers.push(save);
74 return <button onClick={save}>Save shared setting</button>;
75 }
76
81 -function saveSharedSettings() {
82 - container.querySelector("button")!.click();
83 -}
84 -
77 async function mountEditor() {
86 - await act(() =>
87 - root.render(
88 - <RegistryContext.Provider value={appAtomRegistry}>
89 - <SettingsEditor />
90 - </RegistryContext.Provider>,
91 - ),
78 + const handlers: Array<() => void> = [];
79 + const screen = await render(
80 + <RegistryContext.Provider value={appAtomRegistry}>
81 + <SettingsEditor handlers={handlers} />
82 + </RegistryContext.Provider>,
83 );
84 + return {
85 + handlers,
86 + saveSharedSettings: () => screen.container.querySelector("button")!.click(),
87 + [Symbol.asyncDispose]: () => screen[Symbol.asyncDispose](),
88 + };
89 }
90
95 -beforeEach(() => {
96 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
97 - handlers = [];
91 +function setup() {
92 state.sessions.clear();
93 state.sessions.set(
94 primaryId,
@@ -113,19 +107,11 @@ beforeEach(() => {
107 state.persist.mockReset();
108 state.persist.mockResolvedValue(AsyncResult.success(DEFAULT_SERVER_SETTINGS));
109 state.toast.mockReset();
116 - container = document.createElement("div");
117 - document.body.append(container);
118 - root = createRoot(container);
119 -});
120 -
121 -afterEach(async () => {
122 - await act(() => root.unmount());
123 - container.remove();
124 - vi.unstubAllGlobals();
125 -});
110 +}
111
112 describe("shared settings writes", () => {
113 it("waits for the remaining target before reporting a partial save", async () => {
114 + setup();
115 let finishRemote = () => {};
116 const remote = new Promise((resolve) => {
117 finishRemote = () => resolve(AsyncResult.success(DEFAULT_SERVER_SETTINGS));
@@ -134,8 +120,8 @@ describe("shared settings writes", () => {
120 AsyncResult.failure(Cause.fail(new Error("Permission denied"))),
121 );
122 state.persist.mockReturnValueOnce(remote);
137 - await mountEditor();
138 - await act(async () => saveSharedSettings());
123 + await using editor = await mountEditor();
124 + await act(async () => editor.saveSharedSettings());
125 expect(state.toast).not.toHaveBeenCalled();
126 await act(async () => finishRemote());
127 expect(state.toast).toHaveBeenCalledExactlyOnceWith({
@@ -146,12 +132,13 @@ describe("shared settings writes", () => {
132 });
133
134 it("keeps a single-target failure specific to that environment", async () => {
135 + setup();
136 appAtomRegistry.set(state.sessions.get(remoteId)!, AsyncResult.success(session([])));
137 state.persist.mockResolvedValueOnce(
138 AsyncResult.failure(Cause.fail(new Error("Permission denied"))),
139 );
153 - await mountEditor();
154 - await act(async () => saveSharedSettings());
140 + await using editor = await mountEditor();
141 + await act(async () => editor.saveSharedSettings());
142 expect(state.toast).toHaveBeenCalledExactlyOnceWith({
143 type: "error",
144 title: "Setting not saved",
@@ -160,12 +147,13 @@ describe("shared settings writes", () => {
147 });
148
149 it("names the failed environment when a server rejects a save after the grant check", async () => {
150 + setup();
151 state.persist.mockResolvedValueOnce(AsyncResult.success(DEFAULT_SERVER_SETTINGS));
152 state.persist.mockResolvedValueOnce(
153 AsyncResult.failure(Cause.fail(new Error("Permission denied"))),
154 );
167 - await mountEditor();
168 - await act(async () => saveSharedSettings());
155 + await using editor = await mountEditor();
156 + await act(async () => editor.saveSharedSettings());
157 expect(state.toast).toHaveBeenCalledExactlyOnceWith({
158 type: "error",
159 title: "Setting saved on some environments",
@@ -174,8 +162,9 @@ describe("shared settings writes", () => {
162 });
163
164 it("dispatches to the primary and connected remote before the remote grant finishes loading", async () => {
177 - await mountEditor();
178 - saveSharedSettings();
165 + setup();
166 + await using editor = await mountEditor();
167 + editor.saveSharedSettings();
168
169 expect(state.persist.mock.calls).toEqual([
170 [{ environmentId: primaryId, input: { patch } }],
@@ -192,9 +181,10 @@ describe("shared settings writes", () => {
181 () => AsyncResult.failure<AuthSessionState, Error>(Cause.fail(new Error("session rejected"))),
182 ],
183 ] as const)("skips a remote whose grant is %s", async (_label, result) => {
184 + setup();
185 appAtomRegistry.set(state.sessions.get(remoteId)!, result());
196 - await mountEditor();
197 - saveSharedSettings();
186 + await using editor = await mountEditor();
187 + editor.saveSharedSettings();
188
189 expect(state.persist).toHaveBeenCalledExactlyOnceWith({
190 environmentId: primaryId,
@@ -205,11 +195,12 @@ describe("shared settings writes", () => {
195 it.each(["disconnected", "unsupported"] as const)(
196 "skips a %s remote even with a cold grant",
197 async (condition) => {
198 + setup();
199 const remote = state.environments[1]!;
200 if (condition === "disconnected") remote.connection.phase = "disconnected";
201 else remote.serverConfig.environment.capabilities.threadAutoSettlement = false;
211 - await mountEditor();
212 - saveSharedSettings();
202 + await using editor = await mountEditor();
203 + editor.saveSharedSettings();
204
205 expect(state.persist).toHaveBeenCalledExactlyOnceWith({
206 environmentId: primaryId,
@@ -221,13 +212,14 @@ describe("shared settings writes", () => {
212 it.each(["primary", "hosted"] as const)(
213 "rechecks a cold remote grant that resolves to denied after the %s handler renders",
214 async (mode) => {
215 + setup();
216 if (mode === "hosted") {
217 state.environments = state.environments.filter(
218 (environment) => environment.environmentId !== primaryId,
219 );
220 }
229 - await mountEditor();
230 - const previousUpdate = handlers.at(-1)!;
221 + await using editor = await mountEditor();
222 + const previousUpdate = editor.handlers.at(-1)!;
223 await act(() => {
224 appAtomRegistry.set(state.sessions.get(remoteId)!, AsyncResult.success(session([])));
225 });
apps/web/src/hooks/useStableCallback.browser.test.tsx
+6 -20
@@ -1,32 +1,18 @@
1 -import { act } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { describe, expect, it } from "vite-plus/test";
2
3 +import { render } from "../../test/render";
4 import { useStableCallback } from "./useStableCallback";
5
7 -let root: Root;
8 -let handlers: Array<() => string> = [];
9 -
10 -function Probe({ label }: { label: string }) {
6 +function Probe({ label, handlers }: { label: string; handlers: Array<() => string> }) {
7 handlers.push(useStableCallback(() => label));
8 return null;
9 }
10
15 -beforeEach(() => {
16 - handlers = [];
17 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
18 - root = createRoot(document.createElement("div"));
19 -});
20 -
21 -afterEach(async () => {
22 - await act(() => root.unmount());
23 - vi.unstubAllGlobals();
24 -});
25 -
11 describe("useStableCallback", () => {
12 it("keeps one identity and calls the latest committed function", async () => {
28 - await act(() => root.render(<Probe label="first" />));
29 - await act(() => root.render(<Probe label="second" />));
13 + const handlers: Array<() => string> = [];
14 + await using screen = await render(<Probe label="first" handlers={handlers} />);
15 + await screen.rerender(<Probe label="second" handlers={handlers} />);
16
17 expect(new Set(handlers).size).toBe(1);
18 expect(handlers[0]!()).toBe("second");
apps/web/src/panelAnimations.browser.test.tsx
+29 -35
@@ -1,48 +1,42 @@
1 -import { act, useLayoutEffect } from "react";
2 -import { createRoot, type Root } from "react-dom/client";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { useLayoutEffect } from "react";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3
4 +import { act, render } from "../test/render";
5 import { usePanelNavigationSuppression } from "./panelAnimations";
6
7 -let root: Root;
8 -let pendingFrames: FrameRequestCallback[] = [];
9 -let observed: boolean[] = [];
10 -
11 -function SuppressionProbe({ navigationKey }: { navigationKey: string }) {
7 +function SuppressionProbe({
8 + navigationKey,
9 + observed,
10 +}: {
11 + navigationKey: string;
12 + observed: boolean[];
13 +}) {
14 const suppressed = usePanelNavigationSuppression(navigationKey);
15 useLayoutEffect(() => {
16 observed.push(suppressed);
15 - }, [suppressed]);
17 + }, [observed, suppressed]);
18 return null;
19 }
20
19 -beforeEach(() => {
20 - pendingFrames = [];
21 - observed = [];
22 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
23 - // Frames are stepped by hand so each assertion lands between two paints.
24 - vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
25 - pendingFrames.push(callback);
26 - return pendingFrames.length;
27 - });
28 - vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => undefined);
29 - root = createRoot(document.createElement("div"));
30 -});
31 -
32 -afterEach(async () => {
33 - await act(() => root.unmount());
34 - vi.restoreAllMocks();
35 - vi.unstubAllGlobals();
36 -});
37 -
38 -async function paintPendingFrame() {
39 - const callback = pendingFrames.shift();
40 - await act(() => callback?.(0));
41 -}
42 -
21 describe("usePanelNavigationSuppression", () => {
22 it("suppresses initial and navigated panel state until each route has painted", async () => {
45 - await act(() => root.render(<SuppressionProbe navigationKey="/thread/one" />));
23 + const pendingFrames: FrameRequestCallback[] = [];
24 + const observed: boolean[] = [];
25 + // Frames are stepped by hand so each assertion lands between two paints.
26 + using _requestFrame = vi
27 + .spyOn(window, "requestAnimationFrame")
28 + .mockImplementation((callback) => pendingFrames.push(callback));
29 + using _cancelFrame = vi
30 + .spyOn(window, "cancelAnimationFrame")
31 + .mockImplementation(() => undefined);
32 + const paintPendingFrame = async () => {
33 + const callback = pendingFrames.shift();
34 + await act(() => callback?.(0));
35 + };
36 +
37 + await using screen = await render(
38 + <SuppressionProbe navigationKey="/thread/one" observed={observed} />,
39 + );
40 expect(observed.at(-1)).toBe(true);
41
42 await paintPendingFrame();
@@ -50,7 +44,7 @@ describe("usePanelNavigationSuppression", () => {
44 await paintPendingFrame();
45 expect(observed.at(-1)).toBe(false);
46
53 - await act(() => root.render(<SuppressionProbe navigationKey="/thread/two" />));
47 + await screen.rerender(<SuppressionProbe navigationKey="/thread/two" observed={observed} />);
48 expect(observed.at(-1)).toBe(true);
49
50 await paintPendingFrame();
apps/web/src/state/queries.threadSearch.browser.test.tsx
+14 -25
@@ -1,8 +1,7 @@
1 import { EnvironmentId } from "@t3tools/contracts";
2 -import { act } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3
4 +import { act, fakeTimers, render } from "../../test/render";
5 import { useThreadSearch } from "./queries";
6
7 const searchResults = vi.hoisted(() => ({
@@ -24,33 +23,23 @@ function Probe(props: { query: string; onResult: (result: ThreadSearch) => void
23 }
24
25 describe("useThreadSearch", () => {
27 - let root: Root;
28 - beforeEach(() => {
29 - vi.useFakeTimers();
30 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
31 - root = createRoot(document.createElement("div"));
32 - });
33 - afterEach(() => {
34 - act(() => root.unmount());
35 - vi.unstubAllGlobals();
36 - vi.useRealTimers();
37 - });
38 -
39 - it("keeps the settled query and matches stable while typing, then reports the settled query", () => {
26 + it("keeps the settled query and matches stable while typing, then reports the settled query", async () => {
27 + using _timers = fakeTimers();
28 const results: ThreadSearch[] = [];
41 - const render = (query: string) => {
42 - const element = <Probe query={query} onResult={(result) => results.push(result)} />;
43 - act(() => root.render(element));
44 - return results.at(-1)!;
45 - };
46 -
47 - render("");
48 - const typing = ["li", "lin", "link "].map(render);
29 + const probe = (query: string) => (
30 + <Probe query={query} onResult={(result) => results.push(result)} />
31 + );
32 + await using screen = await render(probe(""));
33 + const typing: ThreadSearch[] = [];
34 + for (const query of ["li", "lin", "link "]) {
35 + await screen.rerender(probe(query));
36 + typing.push(results.at(-1)!);
37 + }
38 expect(typing.map((result) => result.query)).toEqual(["", "", ""]);
39 expect(new Set(typing.map((result) => result.matches)).size).toBe(1);
40 expect(typing.every((result) => result.isPending)).toBe(true);
41
53 - act(() => {
42 + await act(() => {
43 vi.advanceTimersByTime(200);
44 });
45 const settled = results.at(-1)!;
apps/web/src/state/terminalSessionAvailability.browser.test.tsx
+32 -34
@@ -1,8 +1,8 @@
1 import { EnvironmentId, ThreadId, type TerminalSummary } from "@t3tools/contracts";
2 -import { act, useEffect } from "react";
3 -import { createRoot, type Root } from "react-dom/client";
4 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
2 +import { useEffect } from "react";
3 +import { expect, it, vi } from "vite-plus/test";
4
5 +import { render } from "../../test/render";
6 import { useKnownTerminalSessions } from "./terminalSessions";
7
8 const state = vi.hoisted(() => ({
@@ -23,8 +23,7 @@ vi.mock(import("./query"), async (original) => ({
23 : { data: state.data, error: state.error }) as never,
24 }));
25
26 -let root: Root;
27 -let current: ReturnType<typeof useKnownTerminalSessions>;
26 +type KnownSessions = ReturnType<typeof useKnownTerminalSessions>;
27 const target = {
28 environmentId: EnvironmentId.make("secondary"),
29 threadId: ThreadId.make("thread"),
@@ -43,56 +42,55 @@ const terminal: TerminalSummary = {
42 updatedAt: "2026-09-05T00:00:00.000Z",
43 };
44
46 -function Probe() {
45 +function Probe({ onSessions }: { onSessions: (sessions: KnownSessions) => void }) {
46 const sessions = useKnownTerminalSessions(target);
47 useEffect(() => {
49 - current = sessions;
50 - }, [sessions]);
48 + onSessions(sessions);
49 + }, [onSessions, sessions]);
50 return null;
51 }
52
54 -function render() {
55 - return act(() => root.render(<Probe />));
53 +function setup() {
54 + Object.assign(state, { canRead: true, data: null, error: null });
55 + let current: KnownSessions | undefined;
56 + const onSessions = (sessions: KnownSessions) => {
57 + current = sessions;
58 + };
59 + return {
60 + get current() {
61 + return current;
62 + },
63 + element: () => <Probe onSessions={onSessions} />,
64 + };
65 }
66
58 -beforeEach(() => {
59 - state.canRead = true;
60 - state.data = null;
61 - state.error = null;
62 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
63 - root = createRoot(document.createElement("div"));
64 -});
65 -
66 -afterEach(async () => {
67 - await act(() => root.unmount());
68 - vi.unstubAllGlobals();
69 -});
70 -
67 it("distinguishes missing metadata from an authoritative empty list across scope changes", async () => {
72 - await render();
73 - expect(current).toBeNull();
68 + const probe = setup();
69 + await using screen = await render(probe.element());
70 + expect(probe.current).toBeNull();
71
72 state.data = [terminal];
76 - await render();
77 - expect(current?.[0]).toMatchObject({
73 + await screen.rerender(probe.element());
74 + expect(probe.current?.[0]).toMatchObject({
75 target: { environmentId: "secondary", terminalId: "term-1" },
76 state: { hasRunningSubprocess: true },
77 });
78
79 state.canRead = false;
83 - await render();
84 - expect(current).toBeNull();
80 + await screen.rerender(probe.element());
81 + expect(probe.current).toBeNull();
82
83 state.canRead = true;
84 state.data = [];
88 - await render();
89 - expect(current).toEqual([]);
85 + await screen.rerender(probe.element());
86 + expect(probe.current).toEqual([]);
87 });
88
89 it("does not reuse cached terminal metadata after a subscription failure", async () => {
90 + const probe = setup();
91 state.data = [terminal];
94 - await render();
92 + await using screen = await render(probe.element());
93 state.error = "Access denied";
96 - await render();
97 - expect(current).toBeNull();
94 + await screen.rerender(probe.element());
95 + expect(probe.current).toBeNull();
96 });
apps/web/src/state/usage.browser.test.tsx
+96 -90
@@ -4,10 +4,10 @@ import {
4 USAGE_CONTRACT_VERSION,
5 type UsageProviderKind,
6 } from "@t3tools/contracts";
7 -import { act, useLayoutEffect } from "react";
8 -import { createRoot, type Root } from "react-dom/client";
9 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
7 +import { useLayoutEffect } from "react";
8 +import { describe, expect, it, vi } from "vite-plus/test";
9
10 +import { render } from "../../test/render";
11 import { useUsage, type EnvironmentUsageStatus, type UsageView } from "./usage";
12
13 const testState = vi.hoisted(() => ({ environments: [] as EnvironmentUsageStatus[] }));
@@ -85,150 +85,156 @@ function environment(
85 };
86 }
87
88 -let root: Root;
89 -let latest: UsageView;
88 +interface ProbeProps {
89 + selected: ReadonlySet<EnvironmentId> | null;
90 + hidden?: ReadonlySet<UsageProviderKind>;
91 + window?: typeof input;
92 +}
93
94 function Probe({
95 selected,
96 hidden,
97 window = input,
95 -}: {
96 - selected: ReadonlySet<EnvironmentId> | null;
97 - hidden?: ReadonlySet<UsageProviderKind>;
98 - window?: typeof input;
99 -}) {
98 + onUsage,
99 +}: ProbeProps & { onUsage: (usage: UsageView) => void }) {
100 const usage = useUsage(window, selected, hidden);
101 useLayoutEffect(() => {
102 - latest = usage;
103 - }, [usage]);
102 + onUsage(usage);
103 + }, [onUsage, usage]);
104 return null;
105 }
106
107 -async function select(...ids: string[]) {
108 - await act(() =>
109 - root.render(<Probe selected={new Set(ids.map((id) => EnvironmentId.make(id)))} />),
110 - );
111 -}
112 -
113 -beforeEach(async () => {
114 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
107 +async function setup() {
108 testState.environments = [environment("a", 10), environment("b", 20), environment("slow", null)];
116 - root = createRoot(document.createElement("div"));
117 - await act(() => root.render(<Probe selected={null} />));
118 -});
119 -
120 -afterEach(async () => {
121 - await act(() => root.unmount());
122 - vi.unstubAllGlobals();
123 -});
109 + let latest: UsageView | undefined;
110 + const onUsage = (usage: UsageView) => {
111 + latest = usage;
112 + };
113 + const screen = await render(<Probe selected={null} onUsage={onUsage} />);
114 + const show = (props: ProbeProps) => screen.rerender(<Probe {...props} onUsage={onUsage} />);
115 + return {
116 + get latest() {
117 + return latest!;
118 + },
119 + show,
120 + select: (...ids: string[]) =>
121 + show({ selected: new Set(ids.map((id) => EnvironmentId.make(id))) }),
122 + [Symbol.asyncDispose]: () => screen[Symbol.asyncDispose](),
123 + };
124 +}
125
126 describe("usage environment selection", () => {
127 it("starts with all environments and adds results as they arrive", async () => {
127 - expect(latest.merged.costUsd).toBe(30);
128 - expect(latest.isPending).toBe(false);
129 - expect(latest.isPartial).toBe(true);
128 + await using screen = await setup();
129 + expect(screen.latest.merged.costUsd).toBe(30);
130 + expect(screen.latest.isPending).toBe(false);
131 + expect(screen.latest.isPartial).toBe(true);
132
133 testState.environments = [...testState.environments.slice(0, 2), environment("slow", 40)];
132 - await act(() => root.render(<Probe selected={null} />));
133 - expect(latest.merged.costUsd).toBe(70);
134 - expect(latest.isPartial).toBe(false);
134 + await screen.show({ selected: null });
135 + expect(screen.latest.merged.costUsd).toBe(70);
136 + expect(screen.latest.isPartial).toBe(false);
137 });
138
139 it("excludes unselected usage and pending environments, then restores all", async () => {
138 - await select("b");
139 - expect(latest.merged.costUsd).toBe(20);
140 - expect(latest.merged.models.map((model) => model.model)).toEqual(["b"]);
141 - expect(latest.isPending).toBe(false);
142 - expect(latest.isPartial).toBe(false);
143 - expect(latest.environments).toHaveLength(3);
144 -
145 - await act(() => root.render(<Probe selected={null} />));
146 - expect(latest.merged.costUsd).toBe(30);
147 - expect(latest.isPartial).toBe(true);
140 + await using screen = await setup();
141 + await screen.select("b");
142 + expect(screen.latest.merged.costUsd).toBe(20);
143 + expect(screen.latest.merged.models.map((model) => model.model)).toEqual(["b"]);
144 + expect(screen.latest.isPending).toBe(false);
145 + expect(screen.latest.isPartial).toBe(false);
146 + expect(screen.latest.environments).toHaveLength(3);
147 +
148 + await screen.show({ selected: null });
149 + expect(screen.latest.merged.costUsd).toBe(30);
150 + expect(screen.latest.isPartial).toBe(true);
151 });
152
153 it("distinguishes a pending selection from an empty or failed selection", async () => {
151 - await select("slow");
152 - expect(latest.isPending).toBe(true);
153 - expect(latest.merged.costUsd).toBe(0);
154 + await using screen = await setup();
155 + await screen.select("slow");
156 + expect(screen.latest.isPending).toBe(true);
157 + expect(screen.latest.merged.costUsd).toBe(0);
158
155 - await select();
156 - expect(latest.selectedEnvironments).toHaveLength(0);
157 - expect(latest.isPending).toBe(false);
158 - expect(latest.isPartial).toBe(false);
159 + await screen.select();
160 + expect(screen.latest.selectedEnvironments).toHaveLength(0);
161 + expect(screen.latest.isPending).toBe(false);
162 + expect(screen.latest.isPartial).toBe(false);
163
164 testState.environments = [{ ...environment("slow", null), isPending: false, error: "Offline" }];
161 - await select("slow");
162 - expect(latest.isPending).toBe(false);
163 - expect(latest.isPartial).toBe(false);
165 + await screen.select("slow");
166 + expect(screen.latest.isPending).toBe(false);
167 + expect(screen.latest.isPartial).toBe(false);
168 });
169
170 it("deduplicates within the selection so an excluded owner cannot hide usage", async () => {
171 + await using screen = await setup();
172 testState.environments = [environment("a", 10, "shared"), environment("b", 20, "shared")];
168 - await act(() => root.render(<Probe selected={null} />));
169 - expect(latest.merged.costUsd).toBe(10);
173 + await screen.show({ selected: null });
174 + expect(screen.latest.merged.costUsd).toBe(10);
175
171 - await select("b");
172 - expect(latest.merged.costUsd).toBe(20);
173 - expect(latest.merged.duplicateSources).toEqual([]);
176 + await screen.select("b");
177 + expect(screen.latest.merged.costUsd).toBe(20);
178 + expect(screen.latest.merged.duplicateSources).toEqual([]);
179 });
180
181 it("keeps selected cached results visible during a refresh", async () => {
182 + await using screen = await setup();
183 testState.environments = [
184 { ...environment("a", 10), isPending: true },
185 environment("slow", null),
186 ];
181 - await select("a");
182 - expect(latest.merged.costUsd).toBe(10);
183 - expect(latest.isPending).toBe(false);
184 - expect(latest.isPartial).toBe(false);
187 + await screen.select("a");
188 + expect(screen.latest.merged.costUsd).toBe(10);
189 + expect(screen.latest.isPending).toBe(false);
190 + expect(screen.latest.isPartial).toBe(false);
191 });
192
193 it("shows the last answered usage until the next window answers, for the same selection", async () => {
194 + await using screen = await setup();
195 const selected = new Set([EnvironmentId.make("a")]);
189 - await act(() => root.render(<Probe selected={selected} />));
190 - expect(latest.shown?.merged.costUsd).toBe(10);
196 + await screen.show({ selected });
197 + expect(screen.latest.shown?.merged.costUsd).toBe(10);
198
199 const nextWindow = { ...input, sinceDay: UsageDay.make("2026-08-28") };
200 testState.environments = [environment("a", null)];
194 - await act(() => root.render(<Probe selected={selected} window={nextWindow} />));
195 - expect(latest.isPending).toBe(true);
196 - expect(latest.shown?.window).toBe(input);
197 - expect(latest.shown?.merged.costUsd).toBe(10);
201 + await screen.show({ selected, window: nextWindow });
202 + expect(screen.latest.isPending).toBe(true);
203 + expect(screen.latest.shown?.window).toBe(input);
204 + expect(screen.latest.shown?.merged.costUsd).toBe(10);
205
206 testState.environments = [{ ...environment("a", null), isPending: false, error: "Offline" }];
200 - await act(() => root.render(<Probe selected={selected} window={nextWindow} />));
201 - expect(latest.isPending).toBe(false);
202 - expect(latest.shown?.window).toBe(input);
203 - expect(latest.shown?.merged.costUsd).toBe(10);
207 + await screen.show({ selected, window: nextWindow });
208 + expect(screen.latest.isPending).toBe(false);
209 + expect(screen.latest.shown?.window).toBe(input);
210 + expect(screen.latest.shown?.merged.costUsd).toBe(10);
211
212 testState.environments = [environment("a", 30)];
206 - await act(() => root.render(<Probe selected={selected} window={nextWindow} />));
207 - expect(latest.shown?.window).toBe(nextWindow);
208 - expect(latest.shown?.merged.costUsd).toBe(30);
213 + await screen.show({ selected, window: nextWindow });
214 + expect(screen.latest.shown?.window).toBe(nextWindow);
215 + expect(screen.latest.shown?.merged.costUsd).toBe(30);
216
217 testState.environments = [environment("a", null)];
211 - await act(() =>
212 - root.render(<Probe selected={selected} hidden={new Set(["claude"])} window={input} />),
213 - );
214 - expect(latest.shown).toBeNull();
218 + await screen.show({ selected, hidden: new Set(["claude"]), window: input });
219 + expect(screen.latest.shown).toBeNull();
220
221 testState.environments = [environment("a", null)];
217 - await select("a");
218 - expect(latest.shown).toBeNull();
222 + await screen.select("a");
223 + expect(screen.latest.shown).toBeNull();
224 });
225 });
226
227 describe("usage provider filter", () => {
228 it("drops hidden providers from totals and sessions, then restores them", async () => {
229 + await using screen = await setup();
230 testState.environments = [environment("a", 10), environment("c", 5, "c", "claude")];
225 - await act(() => root.render(<Probe selected={null} hidden={new Set(["codex"])} />));
226 - expect(latest.merged.costUsd).toBe(5);
227 - expect(latest.merged.sessions).toBe(1);
228 - expect(latest.merged.providers.map((entry) => entry.provider)).toEqual(["claude"]);
229 -
230 - await act(() => root.render(<Probe selected={null} />));
231 - expect(latest.merged.costUsd).toBe(15);
232 - expect(latest.merged.sessions).toBe(2);
231 + await screen.show({ selected: null, hidden: new Set(["codex"]) });
232 + expect(screen.latest.merged.costUsd).toBe(5);
233 + expect(screen.latest.merged.sessions).toBe(1);
234 + expect(screen.latest.merged.providers.map((entry) => entry.provider)).toEqual(["claude"]);
235 +
236 + await screen.show({ selected: null });
237 + expect(screen.latest.merged.costUsd).toBe(15);
238 + expect(screen.latest.merged.sessions).toBe(2);
239 });
240 });
apps/web/src/testRender.browser.test.tsx new
+51
@@ -0,0 +1,51 @@
1 +import { Link } from "@tanstack/react-router";
2 +import { useEffect } from "react";
3 +import { expect, it, vi } from "vite-plus/test";
4 +
5 +import { render, stubGlobal, type Screen } from "../test/render";
6 +
7 +function Crash(): never {
8 + throw new Error("crashed while rendering");
9 +}
10 +
11 +it("fails the render when the component throws inside the test router", async () => {
12 + await expect(render(<Crash />)).rejects.toThrow("crashed while rendering");
13 + expect(document.body.childElementCount).toBe(0);
14 +});
15 +
16 +function RoutedProbe({ onUnmount }: { onUnmount: () => void }) {
17 + useEffect(() => onUnmount, [onUnmount]);
18 + return <Link to="/">home</Link>;
19 +}
20 +
21 +it("unmounts, removes the container and detaches the router on dispose", async () => {
22 + const onUnmount = vi.fn();
23 + let mounted: Screen;
24 + {
25 + await using screen = await render(<RoutedProbe onUnmount={onUnmount} />, { router: "/start" });
26 + mounted = screen;
27 + await expect.element(screen.getByRole("link", { name: "home" })).toBeVisible();
28 + expect(screen.router?.state.location.pathname).toBe("/start");
29 + expect(screen.router?.history.subscribers.size).toBeGreaterThan(0);
30 + }
31 + const { container, router } = mounted;
32 +
33 + expect(onUnmount).toHaveBeenCalledOnce();
34 + expect(container.isConnected).toBe(false);
35 + expect(container.childElementCount).toBe(0);
36 + expect(router?.history.subscribers.size).toBe(0);
37 +});
38 +
39 +it("keeps the act environment off outside the helper", async () => {
40 + await using screen = await render(<p>idle</p>, { router: false });
41 + expect(screen.router).toBeUndefined();
42 + expect(globalThis.IS_REACT_ACT_ENVIRONMENT).not.toBe(true);
43 +});
44 +
45 +it("restores exactly the stubbed global", () => {
46 + {
47 + using _stub = stubGlobal("t3TestGlobal", 1);
48 + expect(Reflect.get(globalThis, "t3TestGlobal")).toBe(1);
49 + }
50 + expect("t3TestGlobal" in globalThis).toBe(false);
51 +});
apps/web/test/render.tsx new
+134
@@ -0,0 +1,134 @@
1 +import {
2 + createMemoryHistory,
3 + createRootRoute,
4 + createRouter,
5 + RouterProvider,
6 + type AnyRouter,
7 +} from "@tanstack/react-router";
8 +import { act as reactAct, createContext, use, type ReactNode } from "react";
9 +import { createRoot } from "react-dom/client";
10 +import { vi } from "vite-plus/test";
11 +import { page, utils, type Locator, type LocatorSelectors } from "vite-plus/test/browser";
12 +
13 +declare global {
14 + var IS_REACT_ACT_ENVIRONMENT: boolean | undefined;
15 +}
16 +
17 +// React warns about every update outside act() while this flag is on, and a real
18 +// browser drives updates from userEvent, timers and network that act() cannot wrap.
19 +// So it is on only while act() runs, and nested calls restore the outer value.
20 +export async function act<T>(callback: () => T | Promise<T>): Promise<T> {
21 + const previous = globalThis.IS_REACT_ACT_ENVIRONMENT;
22 + globalThis.IS_REACT_ACT_ENVIRONMENT = true;
23 + try {
24 + return await reactAct(async () => await callback());
25 + } finally {
26 + globalThis.IS_REACT_ACT_ENVIRONMENT = previous;
27 + }
28 +}
29 +
30 +export interface RenderOptions {
31 + /**
32 + * Element to render into, for tests that size or style it before the first render.
33 + * The screen owns it from then on and removes it on dispose.
34 + */
35 + readonly container?: HTMLElement;
36 + /** Initial location of the test router, or `false` to render without one. */
37 + readonly router?: string | false;
38 +}
39 +
40 +/** Queries are scoped to the container; use `page` for portals such as menus and dialogs. */
41 +export interface Screen extends LocatorSelectors, AsyncDisposable {
42 + readonly container: HTMLElement;
43 + readonly locator: Locator;
44 + readonly router: AnyRouter | undefined;
45 + readonly rerender: (ui: ReactNode) => Promise<void>;
46 + /** Unmounts early, to test cleanup effects. Dispose still removes the container. */
47 + readonly unmount: () => Promise<void>;
48 +}
49 +
50 +const RoutedUi = createContext<ReactNode>(null);
51 +
52 +function RoutedUiOutlet() {
53 + return use(RoutedUi);
54 +}
55 +
56 +// Links and navigation hooks need a router even when the test is not about routing.
57 +function createTestRouter(path: string): AnyRouter {
58 + return createRouter({
59 + routeTree: createRootRoute({ component: RoutedUiOutlet }),
60 + history: createMemoryHistory({ initialEntries: [path] }),
61 + // The router's error UI would otherwise turn a crash into a passing negative assertion.
62 + disableGlobalCatchBoundary: true,
63 + });
64 +}
65 +
66 +/**
67 + * Renders `ui` for one test. Acquire it with `await using` so the tree unmounts and the
68 + * container and router go away when the test ends, pass or fail.
69 + */
70 +export async function render(
71 + ui: ReactNode,
72 + { container = document.createElement("div"), router: path = "/" }: RenderOptions = {},
73 +): Promise<Screen> {
74 + if (!container.isConnected) document.body.append(container);
75 + const root = createRoot(container);
76 + const router = path === false ? undefined : createTestRouter(path);
77 + // The router element is created once so a rerender updates the tree instead of remounting it.
78 + const routerElement = router && <RouterProvider router={router} />;
79 + const wrap = (node: ReactNode) =>
80 + routerElement ? <RoutedUi value={node}>{routerElement}</RoutedUi> : node;
81 +
82 + let mounted = true;
83 + const unmount = async () => {
84 + if (!mounted) return;
85 + mounted = false;
86 + await act(() => root.unmount());
87 + };
88 + const screen: Screen = {
89 + ...utils.getElementLocatorSelectors(container),
90 + container,
91 + locator: page.elementLocator(container),
92 + router,
93 + rerender: (next) => act(() => root.render(wrap(next))),
94 + unmount,
95 + async [Symbol.asyncDispose]() {
96 + try {
97 + await unmount();
98 + } finally {
99 + container.remove();
100 + }
101 + },
102 + };
103 +
104 + try {
105 + await screen.rerender(ui);
106 + } catch (error) {
107 + await screen[Symbol.asyncDispose]();
108 + throw error;
109 + }
110 + return screen;
111 +}
112 +
113 +/** Fake timers for one test: `using _timers = fakeTimers()`. */
114 +export function fakeTimers(config?: Parameters<typeof vi.useFakeTimers>[0]): Disposable {
115 + vi.useFakeTimers(config);
116 + return { [Symbol.dispose]: () => void vi.useRealTimers() };
117 +}
118 +
119 +/** Replaces one global for one test and restores exactly that global on dispose. */
120 +export function stubGlobal(name: string, value: unknown): Disposable {
121 + const original = Object.getOwnPropertyDescriptor(globalThis, name);
122 + Object.defineProperty(globalThis, name, {
123 + value,
124 + configurable: true,
125 + enumerable: true,
126 + writable: true,
127 + });
128 + return {
129 + [Symbol.dispose]() {
130 + if (original) Object.defineProperty(globalThis, name, original);
131 + else Reflect.deleteProperty(globalThis, name);
132 + },
133 + };
134 +}
apps/web/tsconfig.json
+1 -1
@@ -7,7 +7,7 @@
7 "erasableSyntaxOnly": false,
8 "verbatimModuleSyntax": false,
9 "jsx": "react-jsx",
10 - "lib": ["ES2023", "DOM", "DOM.Iterable"],
10 + "lib": ["ES2023", "ESNext.Disposable", "DOM", "DOM.Iterable"],
11 "paths": {
12 "~/*": ["./src/*"]
13 },
oxlint-plugin-t3code/index.ts
+2
@@ -21,6 +21,7 @@ import noUnscopedHas from "./rules/no-unscoped-has.ts";
21 import preferCatchTags from "./rules/prefer-catch-tags.ts";
22 import preferEffectFn from "./rules/prefer-effect-fn.ts";
23 import requireCenteredScrollGutter from "./rules/require-centered-scroll-gutter.ts";
24 +import requireDisposableRender from "./rules/require-disposable-render.ts";
25 import requireSuppressionReason from "./rules/require-suppression-reason.ts";
26
27 export default definePlugin({
@@ -49,6 +50,7 @@ export default definePlugin({
50 "prefer-catch-tags": preferCatchTags,
51 "prefer-effect-fn": preferEffectFn,
52 "require-centered-scroll-gutter": requireCenteredScrollGutter,
53 + "require-disposable-render": requireDisposableRender,
54 "require-suppression-reason": requireSuppressionReason,
55 },
56 });
oxlint-plugin-t3code/rules/require-disposable-render.test.ts new
+46
@@ -0,0 +1,46 @@
1 +import { describe } from "@effect/vitest";
2 +
3 +import { createOxlintRuleHarness } from "../test/utils.ts";
4 +
5 +const browserTest = createOxlintRuleHarness("t3code/require-disposable-render", {
6 + filename: "Widget.browser.test.tsx",
7 +});
8 +const unitTest = createOxlintRuleHarness("t3code/require-disposable-render", {
9 + filename: "widget.test.tsx",
10 +});
11 +
12 +describe("t3code/require-disposable-render", () => {
13 + browserTest.valid(
14 + "allows the disposable helper",
15 + [
16 + 'import { act, render } from "../test/render";',
17 + 'import { useState } from "react";',
18 + 'it("renders", async () => {',
19 + " await using screen = await render(null);",
20 + " await act(() => screen.rerender(null));",
21 + "});",
22 + ].join("\n"),
23 + );
24 + browserTest.invalid("rejects react-dom/client", 'import { createRoot } from "react-dom/client";');
25 + browserTest.invalid("rejects act from react", 'import { act } from "react";');
26 + browserTest.invalid(
27 + "rejects a renamed act from react",
28 + 'import { act as reactAct } from "react";',
29 + );
30 + browserTest.invalid(
31 + "rejects setting the act environment",
32 + "globalThis.IS_REACT_ACT_ENVIRONMENT = true;",
33 + );
34 + browserTest.invalid(
35 + "rejects setting the act environment by computed key",
36 + 'window["IS_REACT_ACT_ENVIRONMENT"] = true;',
37 + );
38 + browserTest.invalid(
39 + "rejects stubbing the act environment",
40 + 'vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);',
41 + );
42 + browserTest.invalid("rejects afterEach", "afterEach(async () => {});");
43 + browserTest.invalid("rejects beforeAll", "beforeAll(() => {});");
44 + unitTest.valid("allows lifecycle hooks outside browser tests", "beforeEach(() => {});");
45 + unitTest.invalid("still rejects react-dom/client in unit tests", 'import "react-dom/client";');
46 +});
oxlint-plugin-t3code/rules/require-disposable-render.ts new
+92
@@ -0,0 +1,92 @@
1 +import { defineRule, type ESTree } from "@oxlint/plugins";
2 +import * as Option from "effect/Option";
3 +
4 +import { getPropertyName, unwrapExpression } from "../utils.ts";
5 +
6 +const BROWSER_TEST_FILE = /\.browser\.test\.[cm]?[jt]sx?$/u;
7 +const LIFECYCLE_HOOKS = new Set(["afterAll", "afterEach", "beforeAll", "beforeEach"]);
8 +const REACT_ACT_EXPORTS = new Set(["act", "unstable_act"]);
9 +const ACT_ENVIRONMENT = "IS_REACT_ACT_ENVIRONMENT";
10 +const HELPER = "Render with `await using screen = await render(...)` from apps/web/test/render.tsx";
11 +
12 +const MESSAGES = {
13 + reactDomClient: `${HELPER}; it owns the React root and unmounts it on dispose.`,
14 + reactAct: `${HELPER} and import \`act\` from there; it enables React's act environment only while act runs.`,
15 + actEnvironment: `${HELPER}; its act() sets ${ACT_ENVIRONMENT} for exactly as long as it runs.`,
16 + lifecycleHook:
17 + "Browser tests acquire what they need with `using`/`await using` instead of lifecycle hooks, so nothing outlives the test that created it.",
18 +};
19 +
20 +const stringValue = (node: ESTree.Node | null | undefined) =>
21 + node?.type === "Literal" && typeof node.value === "string" ? node.value : undefined;
22 +
23 +const namesActEnvironment = (node: unknown) => {
24 + const target = unwrapExpression(node);
25 + if (Option.isNone(target)) return false;
26 + if (target.value.type === "Identifier") return target.value.name === ACT_ENVIRONMENT;
27 + if (target.value.type !== "MemberExpression") return false;
28 + const property = target.value.computed
29 + ? Option.fromNullishOr(stringValue(target.value.property))
30 + : getPropertyName(target.value.property);
31 + return Option.getOrUndefined(property) === ACT_ENVIRONMENT;
32 +};
33 +
34 +export default defineRule({
35 + meta: {
36 + type: "problem",
37 + docs: {
38 + description:
39 + "Require web component tests to render through the disposable test helper instead of managing React roots, act, or lifecycle hooks by hand.",
40 + },
41 + },
42 + create(context) {
43 + const isBrowserTest = BROWSER_TEST_FILE.test(context.filename);
44 +
45 + return {
46 + ImportDeclaration(node) {
47 + if (node.source.value === "react-dom/client") {
48 + context.report({ node: node.source, message: MESSAGES.reactDomClient });
49 + return;
50 + }
51 + if (node.source.value !== "react") return;
52 + for (const specifier of node.specifiers) {
53 + if (specifier.type !== "ImportSpecifier") continue;
54 + const imported =
55 + specifier.imported.type === "Identifier"
56 + ? specifier.imported.name
57 + : specifier.imported.value;
58 + if (REACT_ACT_EXPORTS.has(imported)) {
59 + context.report({ node: specifier, message: MESSAGES.reactAct });
60 + }
61 + }
62 + },
63 + AssignmentExpression(node) {
64 + if (namesActEnvironment(node.left)) {
65 + context.report({ node: node.left, message: MESSAGES.actEnvironment });
66 + }
67 + },
68 + CallExpression(node) {
69 + const callee = unwrapExpression(node.callee);
70 + if (Option.isNone(callee)) return;
71 + if (callee.value.type === "MemberExpression") {
72 + // vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true) leaves the flag on for the whole test.
73 + const method = getPropertyName(callee.value.property);
74 + if (
75 + Option.getOrUndefined(method) === "stubGlobal" &&
76 + stringValue(node.arguments[0] as ESTree.Node | undefined) === ACT_ENVIRONMENT
77 + ) {
78 + context.report({ node, message: MESSAGES.actEnvironment });
79 + }
80 + return;
81 + }
82 + if (
83 + isBrowserTest &&
84 + callee.value.type === "Identifier" &&
85 + LIFECYCLE_HOOKS.has(callee.value.name)
86 + ) {
87 + context.report({ node: node.callee, message: MESSAGES.lifecycleHook });
88 + }
89 + },
90 + };
91 + },
92 +});
vite.config.ts
+6
@@ -187,6 +187,12 @@ export default defineConfig({
187 ],
188 rules: { "t3code/prefer-effect-fn": "off" },
189 },
190 + {
191 + // Warns while the remaining web component tests move to apps/web/test/render.tsx.
192 + // Raise to "error" once `vp lint` reports no t3code(require-disposable-render) warnings.
193 + files: ["apps/web/**/*.test.tsx"],
194 + rules: { "t3code/require-disposable-render": "warn" },
195 + },
196 {
197 files: ["apps/**/src/**", "packages/**/src/**"],
198 excludeFiles: DOM_TEST_ENVIRONMENT_ALLOWLIST,