TypeScript
test(web): misc-b tests run in a real browser (#20869)
Julius Marmingea75a6d76435f
diff --git a/apps/web/src/components/ReopenClosedViewShortcut.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsxsimilarity index 71%rename from apps/web/src/components/ReopenClosedViewShortcut.test.tsxrename to apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsxindex 9add737a294..547bde0896d 100644--- a/apps/web/src/components/ReopenClosedViewShortcut.test.tsx+++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx@@ -3,13 +3,12 @@ import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";import * as Cause from "effect/Cause";import { AsyncResult } from "effect/reactivity";import { act } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";+import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";const state = vi.hoisted(() => ({keybindings: [] as ResolvedKeybindingsConfig,params: {} as Record<string, string>,- paletteOpen: false,workspaceAvailable: true,navigate: vi.fn(),openPreview: vi.fn(),@@ -17,48 +16,61 @@ const state = vi.hoisted(() => ({toast: vi.fn(),}));-vi.mock("./preview/openPreviewSession", () => ({ openPreviewSession: state.openPreview }));-vi.mock("@effect/atom-react", () => ({ useAtomValue: () => state.keybindings }));-vi.mock("@tanstack/react-router", () => ({- useNavigate: () => state.navigate,- useParams: () => state.params,+vi.mock(import("./preview/openPreviewSession"), async (original) => ({+ ...(await original()),+ openPreviewSession: state.openPreview,}));-vi.mock("../state/server", () => ({ primaryServerKeybindingsAtom: {} }));-vi.mock("../state/preview", () => ({ previewEnvironment: { open: state.openPreview } }));-vi.mock("../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));-vi.mock("../state/shell", () => ({ environmentShell: { stateValueAtom: () => ({}) } }));-vi.mock("../connection/catalog", () => ({ environmentCatalog: { catalogValueAtom: "catalog" } }));-vi.mock("../rpc/atomRegistry", () => ({- appAtomRegistry: {- get: (atom: unknown) =>- atom === "catalog"- ? { isReady: true, entries: new Map([["remote", {}]]) }- : { status: "live" },- },+vi.mock(import("@effect/atom-react"), async (original) => ({+ ...(await original()),+ useAtomValue: (() => state.keybindings) as never,}));-vi.mock("../state/entities", () => ({- readThreadShell: () => ({ projectId: "project-1", worktreePath: null }),- readProject: () => (state.workspaceAvailable ? { workspaceRoot: "/work/project" } : null),+vi.mock(import("@tanstack/react-router"), async (original) => ({+ ...(await original()),+ useNavigate: (() => state.navigate) as never,+ useParams: (() => state.params) as never,}));-vi.mock("../composerDraftStore", () => {- const store = {- getDraftSession: () => null,- getDraftThreadByRef: () => null,- getDraftIdByRef: () => null,+vi.mock(import("../state/use-atom-command"), async (original) => ({+ ...(await original()),+ useAtomCommand: ((command: unknown) => command) as never,+}));+vi.mock(import("../state/preview"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ previewEnvironment: { ...actual.previewEnvironment, open: state.openPreview as never },+ };+});+// The remote environment is catalogued and its shell is live.+vi.mock(import("../connection/catalog"), async (original) => {+ const actual = await original();+ const { Atom } = await import("effect/reactivity");+ return {+ ...actual,+ environmentCatalog: {+ ...actual.environmentCatalog,+ catalogValueAtom: Atom.make({ isReady: true, entries: new Map([["remote", {}]]) }) as never,+ },};+});+vi.mock(import("../state/shell"), async (original) => {+ const actual = await original();+ const { Atom } = await import("effect/reactivity");+ const live = Atom.make({ status: "live" });return {- useComposerDraftStore: Object.assign(- (select: (value: typeof store) => unknown) => select(store),- { getState: () => store },- ),+ ...actual,+ environmentShell: { ...actual.environmentShell, stateValueAtom: (() => live) as never },};});-vi.mock("../commandPaletteBus", () => ({ isCommandPaletteOpen: () => state.paletteOpen }));-vi.mock("../lib/editableFocus", () => ({ isEditableFocused: () => false }));-vi.mock("../lib/previewFocus", () => ({ isPreviewFocused: () => false }));-vi.mock("../lib/terminalFocus", () => ({ isTerminalFocused: () => false }));-vi.mock("../modelPickerVisibility", () => ({ isModelPickerOpen: () => false }));-vi.mock("./ui/toast", () => ({ toastManager: { add: state.toast } }));+vi.mock(import("../state/entities"), async (original) => ({+ ...(await original()),+ readThreadShell: (() => ({ projectId: "project-1", worktreePath: null })) as never,+ readProject: (() =>+ state.workspaceAvailable ? { workspaceRoot: "/work/project" } : null) as never,+}));+vi.mock(import("./ui/toast"), async (original) => {+ const actual = await original();+ return { ...actual, toastManager: { ...actual.toastManager, add: state.toast } };+});import { useClosedViewStore } from "../closedViewStore";import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore";@@ -74,40 +86,37 @@ const snapshot = {canGoForward: false,updatedAt: "2026-09-22T12:00:00.000Z",} as const;-class TestElement extends EventTarget {- closest(selector: string) {- return selector === "[data-keybinding-capture]" ? this : null;- }-}-let renderer: ReactTestRenderer | undefined;+let root: Root;let menuAction: ((action: string) => void) | undefined;async function render() {- await act(() => {- renderer = create(<ReopenClosedViewShortcut />);- });+ await act(() => root.render(<ReopenClosedViewShortcut />));}-function press(overrides: Record<string, unknown> = {}) {- const event = Object.assign(new Event("keydown", { cancelable: true }), {+function press(target: Element = document.body) {+ const event = new KeyboardEvent("keydown", {key: "T",ctrlKey: true,- metaKey: false,shiftKey: true,- altKey: false,- repeat: false,- ...overrides,+ bubbles: true,+ cancelable: true,});- window.dispatchEvent(event);+ target.dispatchEvent(event);return event;}+function openCommandPalette() {+ const palette = document.createElement("div");+ palette.dataset.commandPalette = "";+ document.body.append(palette);+ return palette;+}+beforeEach(() => {vi.clearAllMocks();Object.assign(state, {keybindings: DEFAULT_RESOLVED_KEYBINDINGS,params: {},- paletteOpen: false,workspaceAvailable: true,});state.navigate.mockResolvedValue(undefined);@@ -119,27 +128,24 @@ beforeEach(() => {suppressedTerminalIdsByThreadKey: {},});vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- vi.stubGlobal("HTMLElement", TestElement);- vi.stubGlobal("navigator", { platform: "Linux" });- vi.stubGlobal(- "window",- Object.assign(new EventTarget(), {- desktopBridge: {- preview: { setForwardedShortcuts: state.setShortcuts },- onMenuAction: (listener: typeof menuAction) => {- menuAction = listener;- return () => {- menuAction = undefined;- };- },- },- }),- );+ vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");+ window.desktopBridge = {+ preview: { setForwardedShortcuts: state.setShortcuts },+ onMenuAction: (listener: (action: string) => void) => {+ menuAction = listener;+ return () => {+ menuAction = undefined;+ };+ },+ } as unknown as NonNullable<typeof window.desktopBridge>;+ root = createRoot(document.createElement("div"));});afterEach(async () => {- await act(() => renderer?.unmount());- renderer = undefined;+ await act(() => root.unmount());+ delete window.desktopBridge;+ document.body.replaceChildren();+ vi.restoreAllMocks();vi.unstubAllGlobals();});@@ -167,7 +173,7 @@ describe("root reopen shortcut", () => {.getState().remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } });});- state.paletteOpen = true;+ openCommandPalette();expect(press().defaultPrevented).toBe(false);expect(state.navigate).not.toHaveBeenCalled();expect(useClosedViewStore.getState().entries).toHaveLength(1);@@ -178,18 +184,10 @@ describe("root reopen shortcut", () => {.getState().remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } });await render();- const recorder = new TestElement();- const event = Object.assign(new Event("keydown", { bubbles: true, cancelable: true }), {- key: "T",- ctrlKey: true,- metaKey: false,- shiftKey: true,- altKey: false,- repeat: false,- });- Object.defineProperty(event, "target", { value: recorder });- window.dispatchEvent(event);- expect(event.defaultPrevented).toBe(false);+ const recorder = document.createElement("input");+ recorder.dataset.keybindingCapture = "";+ document.body.append(recorder);+ expect(press(recorder).defaultPrevented).toBe(false);expect(useClosedViewStore.getState().entries).toHaveLength(1);});diff --git a/apps/web/src/components/RightPanelTabs.browser.test.tsx b/apps/web/src/components/RightPanelTabs.browser.test.tsxnew file mode 100644index 00000000000..56e6419a885--- /dev/null+++ b/apps/web/src/components/RightPanelTabs.browser.test.tsx@@ -0,0 +1,210 @@+import type { DesktopPreviewFavicon, PreviewSessionSnapshot } from "@t3tools/contracts";+import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";++const setAudioMuted = vi.hoisted(() => vi.fn(async () => undefined));++vi.mock(import("~/hooks/useTheme"), async (original) => ({+ ...(await original()),+ useTheme: () => ({ theme: "light", resolvedTheme: "light", themeHalves: null }) as never,+}));+vi.mock(import("~/browser/browserDefaults"), async (original) => ({+ ...(await original()),+ useBrowserDefaults: () => ({ profiles: [] }) as never,+}));+vi.mock(import("./preview/previewBridge"), () => ({+ previewBridge: { setAudioMuted } as never,+}));++import { RightPanelTabs } from "./RightPanelTabs";++// A real 1x1 PNG, so the browser keeps it instead of falling back on a decode error.+const PIXEL_A =+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";+const PIXEL_B =+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";++const previewSurface = {+ id: "browser:tab-1" as const,+ kind: "preview" as const,+ resourceId: "tab-1",+};+const secondSurface = {+ id: "browser:tab-2" as const,+ kind: "preview" as const,+ resourceId: "tab-2",+};+const sessions: Readonly<Record<string, PreviewSessionSnapshot>> = {+ "tab-1": {+ threadId: "thread-1",+ tabId: "tab-1",+ navStatus: { _tag: "Success", url: "http://24x.xf.local/", title: "Local site" },+ canGoBack: false,+ canGoForward: false,+ updatedAt: "2026-08-09T00:00:00.000Z",+ },+ "tab-2": {+ threadId: "thread-1",+ tabId: "tab-2",+ navStatus: { _tag: "Success", url: "http://24x.xf.local/admin", title: "Admin" },+ canGoBack: false,+ canGoForward: false,+ updatedAt: "2026-08-09T00:00:00.000Z",+ },+};++const favicon = (dataUrl: string, pageUrl: string): DesktopPreviewFavicon => ({+ dataUrl,+ pageUrl,+ capturedAt: 1,+});++function overlay(+ icon: DesktopPreviewFavicon | null,+ audio?: { audible?: boolean; audioMuted?: boolean },+) {+ return {+ hasWebContents: true,+ canGoBack: false,+ canGoForward: false,+ loading: false,+ zoomFactor: 1,+ pictureInPicture: false,+ colorScheme: "system" as const,+ audioMuted: audio?.audioMuted ?? false,+ audible: audio?.audible ?? false,+ controller: "none" as const,+ favicon: icon,+ };+}++let root: Root;+let container: HTMLDivElement;+const noop = () => undefined;++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ setAudioMuted.mockClear();+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});++afterEach(async () => {+ await act(() => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+});++async function renderTabs(+ first: DesktopPreviewFavicon | null,+ second?: DesktopPreviewFavicon,+ audio?: { audible?: boolean; audioMuted?: boolean },+ previewRuntimeTabId: ((tabId: string) => string) | null = (tabId) => `runtime:${tabId}`,+) {+ await act(() =>+ root.render(+ <RightPanelTabs+ mode="inline"+ open+ keybindings={DEFAULT_RESOLVED_KEYBINDINGS}+ getShortcutContext={() => ({+ terminalFocus: false,+ terminalOpen: false,+ previewFocus: false,+ previewOpen: false,+ isWeb: true,+ isDesktop: false,+ })}+ surfaces={second ? [previewSurface, secondSurface] : [previewSurface]}+ environmentId={null}+ activeSurfaceId={previewSurface.id}+ pendingSurfaceIds={new Set()}+ previewSessions={sessions}+ desktopByTabId={{+ "tab-1": overlay(first, audio),+ ...(second ? { "tab-2": overlay(second) } : {}),+ }}+ {...(previewRuntimeTabId ? { previewRuntimeTabId } : {})}+ terminalLabelsById={new Map()}+ onActivate={noop}+ onCloseSurface={noop}+ onCloseOtherSurfaces={noop}+ onCloseSurfacesToRight={noop}+ onCloseAllSurfaces={noop}+ onCopyFilePath={noop}+ onAddBrowser={noop}+ onAddBrowserInProfile={noop}+ onAddTerminal={noop}+ onAddPullRequest={noop}+ onAddPullRequests={noop}+ onAddDiff={noop}+ onAddFiles={noop}+ onAddDevice={noop}+ browserAvailable+ terminalAvailable={false}+ diffAvailable={false}+ filesAvailable={false}+ pullRequestAvailable={false}+ pullRequestsAvailable={false}+ deviceAvailable={false}+ >+ <div>content</div>+ </RightPanelTabs>,+ ),+ );+}++const imageSources = () => [...container.querySelectorAll("img")].map((image) => image.src);+const button = (name: string) =>+ [...container.querySelectorAll("button")].find((element) => element.ariaLabel === name);++describe("preview tab favicon", () => {+ it("prefers a live capture and never asks a public provider about a private hostname", async () => {+ await renderTabs(favicon(PIXEL_A, "http://24x.xf.local/"));+ expect(imageSources()).toEqual([PIXEL_A]);++ await renderTabs(null);+ expect(imageSources()).toEqual([]);+ });++ it("keeps route-specific captures isolated between live tabs on one origin", async () => {+ await renderTabs(+ favicon(PIXEL_A, "http://24x.xf.local/"),+ favicon(PIXEL_B, "http://24x.xf.local/admin"),+ );+ expect(imageSources()).toEqual([PIXEL_A, PIXEL_B]);+ });++ it("hides a capture while the server session still describes another origin", async () => {+ await renderTabs(favicon(PIXEL_A, "https://example.com/"));+ expect(imageSources()).not.toContain(PIXEL_A);+ });+});++describe("preview tab audio toggle", () => {+ it.each([+ { audible: false, audioMuted: false },+ { audible: false, audioMuted: true },+ ])("is absent for a silent tab (muted=$audioMuted)", async (audio) => {+ await renderTabs(null, undefined, audio);+ expect(button("Mute Local site")).toBeUndefined();+ expect(button("Unmute Local site")).toBeUndefined();+ });++ it.each([+ { audioMuted: false, label: "Mute Local site", nextMuted: true },+ { audioMuted: true, label: "Unmute Local site", nextMuted: false },+ ])("$label addresses the desktop by runtime tab id", async ({ audioMuted, label, nextMuted }) => {+ await renderTabs(null, undefined, { audible: true, audioMuted });+ await act(() => button(label)!.click());+ expect(setAudioMuted).toHaveBeenCalledExactlyOnceWith("runtime:tab-1", nextMuted);+ });++ it("hides the toggle when no runtime tab id can be resolved", async () => {+ await renderTabs(null, undefined, { audible: true }, null);+ expect(button("Mute Local site")).toBeUndefined();+ });+});diff --git a/apps/web/src/components/RightPanelTabs.test.tsx b/apps/web/src/components/RightPanelTabs.test.tsxindex bcb56ae8e1b..bef1a174631 100644--- a/apps/web/src/components/RightPanelTabs.test.tsx+++ b/apps/web/src/components/RightPanelTabs.test.tsx@@ -1,11 +1,7 @@import { EnvironmentId, type ThreadPullRequestLink } from "@t3tools/contracts";-import type { DesktopPreviewFavicon, PreviewSessionSnapshot } from "@t3tools/contracts";-import { renderToStaticMarkup } from "react-dom/server";-import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";import { describe, expect, it } from "vite-plus/test";import {- RightPanelTabs,resolvePullRequestTabLink,shouldOpenDefaultBrowserProfileFromMenuClick,surfaceShortcutActionForKey,@@ -36,139 +32,6 @@ function shortcutEvent(};}-const previewSurface = {- id: "browser:tab-1" as const,- kind: "preview" as const,- resourceId: "tab-1",-};-const secondSurface = {- id: "browser:tab-2" as const,- kind: "preview" as const,- resourceId: "tab-2",-};-const sessions: Readonly<Record<string, PreviewSessionSnapshot>> = {- "tab-1": {- threadId: "thread-1",- tabId: "tab-1",- navStatus: { _tag: "Success", url: "http://24x.xf.local/", title: "Local site" },- canGoBack: false,- canGoForward: false,- updatedAt: "2026-08-09T00:00:00.000Z",- },- "tab-2": {- threadId: "thread-1",- tabId: "tab-2",- navStatus: { _tag: "Success", url: "http://24x.xf.local/admin", title: "Admin" },- canGoBack: false,- canGoForward: false,- updatedAt: "2026-08-09T00:00:00.000Z",- },-};--const favicon = (dataUrl: string, pageUrl: string): DesktopPreviewFavicon => ({- dataUrl,- pageUrl,- capturedAt: 1,-});--function overlay(- icon: DesktopPreviewFavicon | null,- audio?: { audible?: boolean; audioMuted?: boolean },-) {- return {- hasWebContents: true,- canGoBack: false,- canGoForward: false,- loading: false,- zoomFactor: 1,- pictureInPicture: false,- colorScheme: "system" as const,- audioMuted: audio?.audioMuted ?? false,- audible: audio?.audible ?? false,- controller: "none" as const,- favicon: icon,- };-}--function renderTabs(- first: DesktopPreviewFavicon | null,- second?: DesktopPreviewFavicon,- audio?: { audible?: boolean; audioMuted?: boolean },- previewRuntimeTabId: ((tabId: string) => string) | null = (tabId) => `runtime:${tabId}`,-) {- return renderToStaticMarkup(- <RightPanelTabs- mode="inline"- keybindings={DEFAULT_RESOLVED_KEYBINDINGS}- getShortcutContext={() => ({- terminalFocus: false,- terminalOpen: false,- previewFocus: false,- previewOpen: false,- isWeb: true,- isDesktop: false,- })}- surfaces={second ? [previewSurface, secondSurface] : [previewSurface]}- environmentId={null}- activeSurfaceId={previewSurface.id}- pendingSurfaceIds={new Set()}- previewSessions={sessions}- desktopByTabId={{- "tab-1": overlay(first, audio),- ...(second ? { "tab-2": overlay(second) } : {}),- }}- {...(previewRuntimeTabId ? { previewRuntimeTabId } : {})}- terminalLabelsById={new Map()}- onActivate={() => undefined}- onCloseSurface={() => undefined}- onCloseOtherSurfaces={() => undefined}- onCloseSurfacesToRight={() => undefined}- onCloseAllSurfaces={() => undefined}- onCopyFilePath={() => undefined}- onAddBrowser={() => undefined}- onAddBrowserInProfile={() => undefined}- onAddTerminal={() => undefined}- onAddPullRequest={() => undefined}- onAddPullRequests={() => undefined}- onAddDiff={() => undefined}- onAddFiles={() => undefined}- onAddDevice={() => undefined}- browserAvailable- terminalAvailable={false}- diffAvailable={false}- filesAvailable={false}- pullRequestAvailable={false}- pullRequestsAvailable={false}- deviceAvailable={false}- >- <div>content</div>- </RightPanelTabs>,- );-}--describe("RightPanelTabs preview favicon", () => {- it("prefers a live capture and never asks Google about a private hostname", () => {- const captured = renderTabs(favicon("data:image/png;base64,AAAA", "http://24x.xf.local/"));- expect(captured).toContain("data:image/png;base64,AAAA");- expect(captured).not.toContain("s2/favicons");- expect(renderTabs(null)).not.toContain("s2/favicons");- });-- it("keeps route-specific captures isolated between live tabs on one origin", () => {- const html = renderTabs(- favicon("data:image/png;base64,AAAA", "http://24x.xf.local/"),- favicon("data:image/png;base64,BBBB", "http://24x.xf.local/admin"),- );- expect(html).toContain("data:image/png;base64,AAAA");- expect(html).toContain("data:image/png;base64,BBBB");- });-- it("hides a capture while the server session still describes another origin", () => {- const html = renderTabs(favicon("data:image/png;base64,AAAA", "https://example.com/"));- expect(html).not.toContain("data:image/png;base64,AAAA");- });-});-describe("surface shortcuts", () => {const actions = [{ shortcut: "B", available: true, label: "Browser" },@@ -216,39 +79,6 @@ describe("surface shortcut typing contexts", () => {});});-describe("RightPanelTabs audio indicator", () => {- const cases = [- { audible: false, audioMuted: false, label: null },- { audible: false, audioMuted: true, label: null },- { audible: true, audioMuted: false, label: "Mute Local site" },- { audible: true, audioMuted: true, label: "Unmute Local site" },- ] as const;-- it.each(cases)("audible=$audible muted=$audioMuted", ({ audible, audioMuted, label }) => {- const html = renderTabs(null, undefined, { audible, audioMuted });- if (label === null) {- expect(html).not.toContain("Mute Local site");- expect(html).not.toContain("Unmute Local site");- } else {- expect(html).toContain(`aria-label="${label}"`);- }- });-- it("addresses the desktop by runtime tab id, never the server session id", () => {- const seen: string[] = [];- renderTabs(null, undefined, { audible: true }, (tabId) => {- seen.push(tabId);- return `runtime:${tabId}`;- });- expect(seen).toContain("tab-1");- });-- it("hides the toggle when no runtime tab id can be resolved", () => {- const html = renderTabs(null, undefined, { audible: true }, null);- expect(html).not.toContain("Mute Local site");- });-});-describe("tabMuteMenuItem", () => {const overlay = (audioMuted: boolean) =>({ audioMuted, audible: false }) as Parameters<typeof tabMuteMenuItem>[0]["overlay"];diff --git a/apps/web/src/components/ServerUpdateAction.test.tsx b/apps/web/src/components/ServerUpdateAction.browser.test.tsxsimilarity index 52%rename from apps/web/src/components/ServerUpdateAction.test.tsxrename to apps/web/src/components/ServerUpdateAction.browser.test.tsxindex f607c27ff08..8a86d2d37bb 100644--- a/apps/web/src/components/ServerUpdateAction.test.tsx+++ b/apps/web/src/components/ServerUpdateAction.browser.test.tsx@@ -1,51 +1,59 @@-import { act, type ReactElement } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";-import { renderToStaticMarkup } from "react-dom/server";+import { RegistryContext } from "@effect/atom-react";import { AuthSessionState, type EnvironmentId, type ServerInstallation } from "@t3tools/contracts";import * as Cause from "effect/Cause";import * as Schema from "effect/Schema";-import { AsyncResult } from "effect/reactivity";+import { AsyncResult, Atom } from "effect/reactivity";+import { act, type ReactNode } from "react";+import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;const testState = vi.hoisted(() => ({updateServer: vi.fn(),toast: vi.fn(),clipboard: vi.fn(),continueThreadsAfterServerUpdate: false,- session: null as AsyncResult.AsyncResult<AuthSessionState, Error> | null,- sessionAtom: Symbol("session"),+ sessionAtom: null as unknown,}));-vi.mock("~/hooks/useCopyToClipboard", () => ({- useCopyToClipboard: (options: { onCopy: (context: { command: string }) => void }) => ({+vi.mock(import("~/hooks/useCopyToClipboard"), async (original) => ({+ ...(await original()),+ useCopyToClipboard: ((options: { onCopy: (context: { command: string }) => void }) => ({copyToClipboard: (command: string, context: { command: string }) => {testState.clipboard(command);options.onCopy(context);},- }),+ isCopied: false,+ })) as never,}));-vi.mock("~/hooks/useSettings", () => ({- useEnvironmentSettings: (+vi.mock(import("~/hooks/useSettings"), async (original) => ({+ ...(await original()),+ useEnvironmentSettings: ((_environmentId: EnvironmentId,selector: (settings: { continueThreadsAfterServerUpdate: boolean }) => unknown,- ) => selector({ continueThreadsAfterServerUpdate: testState.continueThreadsAfterServerUpdate }),+ ) =>+ selector({+ continueThreadsAfterServerUpdate: testState.continueThreadsAfterServerUpdate,+ })) as never,}));-vi.mock("@effect/atom-react", () => ({ useAtomValue: () => testState.session }));-vi.mock("~/rpc/atomRegistry", () => ({- appAtomRegistry: { get: () => testState.session },-}));-vi.mock("~/state/session", () => ({- environmentSession: { sessionStateAtom: () => testState.sessionAtom },-}));-vi.mock("~/state/server", () => ({- serverEnvironment: { updateServer: Symbol("updateServer") },-}));-vi.mock("~/state/use-atom-command", () => ({- useAtomCommand: () => testState.updateServer,-}));-vi.mock("./ui/toast", () => ({- toastManager: { add: testState.toast },+vi.mock(import("~/state/session"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ environmentSession: {+ ...actual.environmentSession,+ sessionStateAtom: (() => testState.sessionAtom) as never,+ },+ };+});+vi.mock(import("~/state/use-atom-command"), async (original) => ({+ ...(await original()),+ useAtomCommand: (() => testState.updateServer) as never,}));+vi.mock(import("./ui/toast"), async (original) => {+ const actual = await original();+ return { ...actual, toastManager: { ...actual.toastManager, add: testState.toast } };+});import {readConfirmDialogState,@@ -53,6 +61,7 @@ import {resetConfirmDialogForTests,respondToConfirmDialog,} from "~/confirmDialog";+import { appAtomRegistry } from "~/rpc/atomRegistry";import {ServerUpdateAction,ServerUpdateProgress,@@ -62,24 +71,6 @@ import {const decodeSessionState = Schema.decodeUnknownSync(AuthSessionState);-type ActionElement = ReactElement<{- readonly onClick?: () => void;-}>;--function renderAction(): ActionElement {- return ServerUpdateAction({- environmentId: "env-test" as EnvironmentId,- serverLabel: "Test server",- selfUpdate: "boot-service",- targetVersion: "0.0.31",- }) as ActionElement;-}--async function flushPromises(): Promise<void> {- await Promise.resolve();- await Promise.resolve();-}-const legacyAuth = {policy: "remote-reachable",bootstrapMethods: ["one-time-token"],@@ -96,15 +87,72 @@ const currentSession = {},} as const satisfies AuthSessionState;-describe("ServerUpdateAction", () => {- beforeEach(() => {- testState.updateServer.mockReset();- testState.toast.mockReset();- testState.clipboard.mockReset();- testState.continueThreadsAfterServerUpdate = false;- testState.session = AsyncResult.success(currentSession);- });+const success = (method: "boot-service" | "desktop-app" = "boot-service", version = "0.0.31") =>+ AsyncResult.success({ targetVersion: version, method });++let root: Root;+let container: HTMLDivElement;+let sessionAtom: Atom.Writable<SessionResult>;++function setSession(session: SessionResult) {+ appAtomRegistry.set(sessionAtom, session);+}+async function render(element: ReactNode) {+ await act(() =>+ root.render(+ <RegistryContext.Provider value={appAtomRegistry}>{element}</RegistryContext.Provider>,+ ),+ );+}++function button(name?: string) {+ const buttons = [...container.querySelectorAll("button")];+ return name === undefined+ ? buttons[0]+ : buttons.find((element) => element.textContent?.trim() === name);+}++async function click(name?: string) {+ await act(async () => button(name)!.click());+}++async function renderAction(+ props: Partial<Parameters<typeof ServerUpdateAction>[0]> = {},+): Promise<void> {+ await render(+ <ServerUpdateAction+ environmentId={"env-test" as EnvironmentId}+ serverLabel="Test server"+ selfUpdate="boot-service"+ targetVersion="0.0.31"+ {...props}+ />,+ );+}++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ testState.updateServer.mockReset();+ testState.toast.mockReset();+ testState.clipboard.mockReset();+ testState.continueThreadsAfterServerUpdate = false;+ sessionAtom = Atom.make<SessionResult>(AsyncResult.success(currentSession));+ testState.sessionAtom = sessionAtom;+ resetConfirmDialogForTests();+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});++afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ resetConfirmDialogForTests();+ vi.unstubAllGlobals();+});++describe("ServerUpdateAction", () => {it.each([{ serverUpdateScope: undefined, scopes: ["orchestration:operate"], allowed: true },{ serverUpdateScope: undefined, scopes: ["orchestration:read"], allowed: false },@@ -121,77 +169,75 @@ describe("ServerUpdateAction", () => {] as const)("uses the advertised update scope $serverUpdateScope with grant $scopes",async ({ serverUpdateScope, scopes, allowed }) => {- testState.session = AsyncResult.success(- decodeSessionState({- ...currentSession,- scopes,- auth: {- ...legacyAuth,- ...(serverUpdateScope === undefined ? {} : { serverUpdateScope }),- },- }),- );- testState.updateServer.mockResolvedValue(- AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),+ setSession(+ AsyncResult.success(+ decodeSessionState({+ ...currentSession,+ scopes,+ auth: {+ ...legacyAuth,+ ...(serverUpdateScope === undefined ? {} : { serverUpdateScope }),+ },+ }),+ ),);+ testState.updateServer.mockResolvedValue(success());- renderAction().props.onClick?.();- await flushPromises();+ await renderAction();+ expect(button("Update")!.disabled).toBe(!allowed);+ await click("Update");expect(testState.updateServer).toHaveBeenCalledTimes(allowed ? 1 : 0);},);it("keeps a known grant usable while the session refreshes", async () => {- testState.session = AsyncResult.waiting(AsyncResult.success(currentSession));- testState.updateServer.mockResolvedValue(- AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),- );+ setSession(AsyncResult.waiting(AsyncResult.success(currentSession)));+ testState.updateServer.mockResolvedValue(success());- renderAction().props.onClick?.();- await flushPromises();+ await renderAction();+ await click("Update");expect(testState.updateServer).toHaveBeenCalledOnce();});- it("does not dispatch an update after maintenance access is removed", async () => {- const action = renderAction();- testState.session = AsyncResult.success({ ...currentSession, scopes: [] });- action.props.onClick?.();- await flushPromises();+ it("disables the action once maintenance access is removed", async () => {+ await renderAction();+ await act(() => setSession(AsyncResult.success({ ...currentSession, scopes: [] })));+ expect(button("Update")!.disabled).toBe(true);+ await click("Update");expect(testState.updateServer).not.toHaveBeenCalled();});it.each([[{ kind: "npm-global", prefix: "/opt/node" },+ "Copy update command","npm install --global --prefix '/opt/node' [email protected]","Update command copied","then restart t3",],[{ kind: "npx" },+ "Copy relaunch command","npx [email protected]","Relaunch command copied","This does not update an installed t3 command.",],[undefined,+ "Copy relaunch command","npx [email protected]","Relaunch command copied","This does not update an installed t3 command.",],- ] satisfies ReadonlyArray<readonly [ServerInstallation | undefined, string, string, string]>)(+ ] satisfies ReadonlyArray<+ readonly [ServerInstallation | undefined, string, string, string, string]+ >)("copies an honest manual command for %j without invoking remote update",- (installation, command, title, guidance) => {- const action = ServerUpdateAction({- environmentId: "env-test" as EnvironmentId,- serverLabel: "Test server",- selfUpdate: null,- installation,- targetVersion: "0.0.45",- }) as ActionElement;- action.props.onClick?.();+ async (installation, label, command, title, guidance) => {+ await renderAction({ selfUpdate: null, installation, targetVersion: "0.0.45" });+ await click(label);expect(testState.clipboard).toHaveBeenCalledWith(command);expect(testState.toast).toHaveBeenCalledWith(expect.objectContaining({@@ -204,12 +250,10 @@ describe("ServerUpdateAction", () => {);it("reports success only after the shared update flow reconnects", async () => {- testState.updateServer.mockResolvedValue(- AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),- );+ testState.updateServer.mockResolvedValue(success());- renderAction().props.onClick?.();- await flushPromises();+ await renderAction();+ await click("Update");expect(testState.updateServer).toHaveBeenCalledWith({environmentId: "env-test",@@ -227,61 +271,52 @@ describe("ServerUpdateAction", () => {testState.updateServer.mockImplementation(() =>new Promise((resolve) => {- finishUpdate = () =>- resolve(- AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),- );+ finishUpdate = () => resolve(success());}),);- const action = renderAction();- action.props.onClick?.();- action.props.onClick?.();+ await renderAction();+ await act(async () => {+ button("Update")!.click();+ button("Update")!.click();+ });expect(testState.updateServer).toHaveBeenCalledTimes(1);- finishUpdate?.();- await flushPromises();+ await act(async () => finishUpdate?.());expect(testState.toast).toHaveBeenCalledTimes(1);});it("quietly releases the action when the operation is interrupted", async () => {testState.updateServer.mockResolvedValue(AsyncResult.failure(Cause.interrupt()));- renderAction().props.onClick?.();- await flushPromises();+ await renderAction();+ await click("Update");expect(testState.toast).not.toHaveBeenCalled();});- it("keeps the manual instruction for desktop servers without remote update support", () => {- const markup = renderToStaticMarkup(- <ServerUpdateAction- environmentId={"env-test" as EnvironmentId}- serverLabel="Test server"- selfUpdate="desktop-managed"- targetVersion="0.0.31"- />,- );-- expect(markup).toContain("Update the desktop app on that machine to update this server.");- expect(markup).not.toContain("<button");- });+ it("keeps the manual instruction for desktop servers without remote update support", async () => {+ await renderAction({ selfUpdate: "desktop-managed" });- it("updates remote desktop apps through the shared update flow", async () => {- testState.updateServer.mockResolvedValue(- AsyncResult.success({ targetVersion: "0.0.34", method: "desktop-app" as const }),+ expect(container.textContent).toBe(+ "Update the desktop app on that machine to update this server.",);+ expect(button()).toBeUndefined();+ });- const action = ServerUpdateAction({- environmentId: "env-test" as EnvironmentId,- serverLabel: "Test server",- selfUpdate: "desktop-managed",- desktopAppUpdate: true,- targetVersion: "0.0.31",- }) as ActionElement;+ it("updates remote desktop apps through the shared update flow after confirmation", async () => {+ registerConfirmDialogHost();+ testState.updateServer.mockResolvedValue(success("desktop-app", "0.0.34"));- action.props.onClick?.();- await flushPromises();+ await renderAction({ selfUpdate: "desktop-managed", desktopAppUpdate: true });+ await click("Update");+ expect(readConfirmDialogState()).toEqual(+ expect.objectContaining({+ status: "confirming",+ message: expect.stringContaining("Test server"),+ }),+ );+ await act(async () => respondToConfirmDialog(true));expect(testState.updateServer).toHaveBeenCalledWith({environmentId: "env-test",@@ -295,19 +330,10 @@ describe("ServerUpdateAction", () => {});it("leaves thread continuation off by default", async () => {- testState.updateServer.mockResolvedValue(- AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),- );- const action = ServerUpdateAction({- environmentId: "env-test" as EnvironmentId,- serverLabel: "Test server",- selfUpdate: "boot-service",- threadContinuation: true,- targetVersion: "0.0.31",- }) as ActionElement;+ testState.updateServer.mockResolvedValue(success());- action.props.onClick?.();- await flushPromises();+ await renderAction({ threadContinuation: true });+ await click("Update");expect(testState.updateServer).toHaveBeenCalledWith({environmentId: "env-test",@@ -316,20 +342,11 @@ describe("ServerUpdateAction", () => {});it("applies the saved thread continuation preference automatically", async () => {- testState.updateServer.mockResolvedValue(- AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),- );+ testState.updateServer.mockResolvedValue(success());testState.continueThreadsAfterServerUpdate = true;- const action = ServerUpdateAction({- environmentId: "env-test" as EnvironmentId,- serverLabel: "Test server",- selfUpdate: "boot-service",- threadContinuation: true,- targetVersion: "0.0.31",- }) as ActionElement;- action.props.onClick?.();- await flushPromises();+ await renderAction({ threadContinuation: true });+ await click("Update");expect(testState.updateServer).toHaveBeenCalledWith({environmentId: "env-test",@@ -339,7 +356,6 @@ describe("ServerUpdateAction", () => {});describe("ServerUpdatesAction", () => {- let renderer: ReactTestRenderer | undefined;const targets: ReadonlyArray<ServerUpdateTarget> = [{environmentId: "batch-a" as EnvironmentId,@@ -364,36 +380,13 @@ describe("ServerUpdatesAction", () => {targetVersion: "0.0.31",},];- const success = AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const });- async function mount(batch = targets) {- await act(async () => {- renderer = create(<ServerUpdatesAction targets={batch} />);- });- return renderer!.root.findByType("button");- }-- beforeEach(() => {- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- testState.updateServer.mockReset();- testState.toast.mockReset();- resetConfirmDialogForTests();- });- afterEach(async () => {- await act(async () => {- renderer?.unmount();- });- renderer = undefined;- resetConfirmDialogForTests();- vi.unstubAllGlobals();- });+ const mount = (batch = targets) => render(<ServerUpdatesAction targets={batch} />);it("updates both supported machines with their own continuation preference and skips the manual machine", async () => {- testState.updateServer.mockResolvedValue(success);- const button = await mount();- await act(async () => {- button.props.onClick();- });+ testState.updateServer.mockResolvedValue(success());+ await mount();+ await click("Update all");expect(testState.updateServer.mock.calls.map(([target]) => target)).toEqual([{@@ -411,11 +404,9 @@ describe("ServerUpdatesAction", () => {it("names a failed machine while letting the other machine complete", async () => {testState.updateServer.mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Download failed"))))- .mockResolvedValueOnce(success);- const button = await mount();- await act(async () => {- button.props.onClick();- });+ .mockResolvedValueOnce(success());+ await mount();+ await click("Update all");expect(testState.updateServer).toHaveBeenCalledTimes(2);expect(testState.toast).toHaveBeenCalledWith({@@ -426,7 +417,7 @@ describe("ServerUpdatesAction", () => {expect(testState.toast).toHaveBeenCalledWith(expect.objectContaining({ type: "success", title: "Office updated" }),);- expect(button.props.disabled).toBe(false);+ expect(button("Update all")!.disabled).toBe(false);});it("starts each machine once when double-clicked and disables the action until both finish", async () => {@@ -434,56 +425,47 @@ describe("ServerUpdatesAction", () => {testState.updateServer.mockImplementation(() =>new Promise((resolve) => {- completions.push(() => resolve(success));+ completions.push(() => resolve(success()));}),);- const button = await mount();+ await mount();await act(async () => {- button.props.onClick();- button.props.onClick();+ button("Update all")!.click();+ button("Update all")!.click();});expect(testState.updateServer).toHaveBeenCalledTimes(2);- expect(button.props.disabled).toBe(true);- await act(async () => {- completions[0]!();- });- expect(button.props.disabled).toBe(true);- await act(async () => {- completions[1]!();- });- expect(button.props.disabled).toBe(false);+ expect(button("Update all")!.disabled).toBe(true);+ await act(async () => completions[0]!());+ expect(button("Update all")!.disabled).toBe(true);+ await act(async () => completions[1]!());+ expect(button("Update all")!.disabled).toBe(false);expect(testState.toast).toHaveBeenCalledTimes(2);});it("asks once for desktop machines and cancels the entire batch", async () => {registerConfirmDialogHost();- const button = await mount(+ await mount(targets.map((target, index) =>index < 2 ? { ...target, selfUpdate: "desktop-managed", desktopAppUpdate: true } : target,),);- await act(async () => {- button.props.onClick();- });- const confirmation = readConfirmDialogState();- expect(confirmation).toEqual(+ await click("Update all");+ expect(readConfirmDialogState()).toEqual(expect.objectContaining({status: "confirming",message: expect.stringContaining("Laptop, Office"),}),);expect(testState.updateServer).not.toHaveBeenCalled();- await act(async () => {- respondToConfirmDialog(false);- });+ await act(async () => respondToConfirmDialog(false));expect(testState.updateServer).not.toHaveBeenCalled();- expect(button.props.disabled).toBe(false);+ expect(button("Update all")!.disabled).toBe(false);});});describe("ServerUpdateProgress", () => {- it("shows one calm status row for the restart wait", () => {- const markup = renderToStaticMarkup(+ it("shows one calm status for the restart wait", async () => {+ await render(<ServerUpdateProgressstate={{status: "running",@@ -493,17 +475,11 @@ describe("ServerUpdateProgress", () => {}}/>,);-- expect(markup).toContain("Restarting…");- expect(markup).not.toContain("0.0.30");- expect(markup).not.toContain("Resum");- expect(markup).not.toContain("text-success");- expect(markup).not.toContain("text-primary");- expect(markup).not.toContain("animate-");+ expect(container.textContent).toBe("Restarting…");});- it("folds the sub-second installing handoff into the download phase", () => {- const markup = renderToStaticMarkup(+ it("folds the sub-second installing handoff into the download phase", async () => {+ await render(<ServerUpdateProgressstate={{status: "running",@@ -513,13 +489,11 @@ describe("ServerUpdateProgress", () => {}}/>,);-- expect(markup).toContain("Downloading…");- expect(markup).not.toContain("Install");+ expect(container.textContent).toBe("Downloading…");});- it("keeps the failure visible with its retryable error", () => {- const markup = renderToStaticMarkup(+ it("keeps the failure visible as an alert with its error", async () => {+ await render(<ServerUpdateProgressstate={{status: "failed",@@ -530,9 +504,8 @@ describe("ServerUpdateProgress", () => {}}/>,);-- expect(markup).toContain('role="alert"');- expect(markup).toContain("The package could not be verified.");- expect(markup).not.toContain("animate-status-pulse");+ expect(container.querySelector("[role=alert]")?.textContent).toBe(+ "The package could not be verified.",+ );});});diff --git a/apps/web/src/components/Sidebar.pointer.test.ts b/apps/web/src/components/Sidebar.pointer.browser.test.tsxsimilarity index 91%rename from apps/web/src/components/Sidebar.pointer.test.tsrename to apps/web/src/components/Sidebar.pointer.browser.test.tsxindex 20234e820cf..45ec1d60d17 100644--- a/apps/web/src/components/Sidebar.pointer.test.ts+++ b/apps/web/src/components/Sidebar.pointer.browser.test.tsx@@ -1,20 +1,16 @@import type { SensorProps } from "@dnd-kit/core";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";-import { act, createElement, StrictMode } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";+import { act, StrictMode } from "react";+import { createRoot } from "react-dom/client";import { SidebarDragLifecycle, SidebarPointerSensor } from "./Sidebar.pointer";-class TestDocument extends EventTarget {- hidden = false;- getSelection = () => ({ removeAllRanges() {} });-}--let document: TestDocument;-let window: EventTarget;const sensors: SidebarPointerSensor[] = [];+let hidden = false;-function pointer(type: string, values: Partial<PointerEvent> = {}) {- return Object.assign(new Event(type, { cancelable: true }), {+function pointer(type: string, values: PointerEventInit = {}) {+ return new PointerEvent(type, {+ bubbles: true,+ cancelable: true,pointerId: 1,clientX: 10,clientY: 10,@@ -49,15 +45,16 @@ function gesture(beforeEach(() => {vi.useFakeTimers();vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- document = new TestDocument();- window = Object.assign(new EventTarget(), { setTimeout });- vi.stubGlobal("document", document);- vi.stubGlobal("window", window);+ hidden = false;+ vi.spyOn(document, "hidden", "get").mockImplementation(() => hidden);});afterEach(() => {for (const sensor of sensors.splice(0)) sensor.cancel();+ // Cancelled sensors keep suppressing clicks on the shared document until the next press.+ document.dispatchEvent(pointer("pointerdown"));vi.runAllTimers();vi.useRealTimers();+ vi.restoreAllMocks();vi.unstubAllGlobals();});@@ -89,12 +86,12 @@ describe("sidebar pointer lifecycle", () => {const interruptions = {blur: () => window.dispatchEvent(new Event("blur")),hidden: () => {- document.hidden = true;+ hidden = true;document.dispatchEvent(new Event("visibilitychange"));},pagehide: () => window.dispatchEvent(new Event("pagehide")),resize: () => window.dispatchEvent(new Event("resize")),- escape: () => document.dispatchEvent(Object.assign(new Event("keydown"), { code: "Escape" })),+ escape: () => document.dispatchEvent(new KeyboardEvent("keydown", { code: "Escape" })),pointercancel: () => document.dispatchEvent(pointer("pointercancel")),"missed release": () =>document.dispatchEvent(pointer("pointermove", { buttons: 0, clientY: 100 })),@@ -113,7 +110,7 @@ describe("sidebar pointer lifecycle", () => {expect(drag.onStart).toHaveBeenCalledTimes(started ? 1 : 0);expect(drag.onAbort).toHaveBeenCalledTimes(started ? 0 : 1);- document.hidden = false;+ hidden = false;const next = gesture();document.dispatchEvent(pointer("pointermove", { clientY: 20 }));document.dispatchEvent(pointer("pointerup", { buttons: 0 }));@@ -254,22 +251,18 @@ describe("sidebar pointer lifecycle", () => {});it.each([false, true])("cancels when search unmounts the list, started=%s", (started) => {- let renderer: ReactTestRenderer;+ const root = createRoot(document.createElement("div"));let drag: ReturnType<typeof gesture> | undefined;- act(() => {- renderer = create(- createElement(- StrictMode,- null,- createElement(SidebarDragLifecycle, {- onUnmount: () => drag?.sensor.cancel(),- }),- ),- );- });+ act(() =>+ root.render(+ <StrictMode>+ <SidebarDragLifecycle onUnmount={() => drag?.sensor.cancel()} />+ </StrictMode>,+ ),+ );drag = gesture();if (started) document.dispatchEvent(pointer("pointermove", { clientY: 20 }));- act(() => renderer.unmount());+ act(() => root.unmount());document.dispatchEvent(pointer("pointermove", { clientY: 100 }));document.dispatchEvent(pointer("pointerup", { buttons: 0 }));expect(drag.onStart).toHaveBeenCalledTimes(started ? 1 : 0);diff --git a/apps/web/src/components/SidebarStageBackdrop.browser.test.tsx b/apps/web/src/components/SidebarStageBackdrop.browser.test.tsxnew file mode 100644index 00000000000..a8397d01191--- /dev/null+++ b/apps/web/src/components/SidebarStageBackdrop.browser.test.tsx@@ -0,0 +1,52 @@+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";++import { StageBackdropArt } from "./SidebarStageBackdrop";++let root: Root;+let container: HTMLDivElement;++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});++afterEach(async () => {+ await act(() => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+});++// Gradients and patterns resolve url(#id) document-wide, so a repeated id would paint one+// backdrop with another's definitions.+it.each(["nightly", "dev"] as const)(+ "gives every %s backdrop its own SVG definitions when two are on the page",+ async (variant) => {+ await act(() =>+ root.render(+ <>+ <StageBackdropArt variant={variant} />+ <StageBackdropArt variant={variant} />+ </>,+ ),+ );+ const [first, second] = container.querySelectorAll("svg");+ const ids = (svg: Element | undefined) => [...svg!.querySelectorAll("[id]")].map((el) => el.id);++ expect(ids(first).length).toBeGreaterThan(0);+ for (const id of ids(first)) {+ expect(document.querySelectorAll(`#${CSS.escape(id)}`)).toHaveLength(1);+ }+ expect(ids(second).filter((id) => ids(first).includes(id))).toEqual([]);+ for (const reference of second!.querySelectorAll("[fill^='url(#'], [filter^='url(#']")) {+ const target = (reference.getAttribute("fill") ?? reference.getAttribute("filter"))!.slice(+ 5,+ -1,+ );+ expect(second!.querySelector(`#${CSS.escape(target)}`)).not.toBeNull();+ }+ },+);diff --git a/apps/web/src/components/SidebarStageBackdrop.test.tsx b/apps/web/src/components/SidebarStageBackdrop.test.tsxindex c34eec58316..8f286758ebe 100644--- a/apps/web/src/components/SidebarStageBackdrop.test.tsx+++ b/apps/web/src/components/SidebarStageBackdrop.test.tsx@@ -1,10 +1,8 @@import { describe, expect, it } from "vite-plus/test";-import { renderToStaticMarkup } from "react-dom/server";import {resolveEnvironmentIdentificationPillLabel,resolveSidebarStageBackdropVariant,- StageBackdropArt,} from "./SidebarStageBackdrop";describe("SidebarStageBackdrop", () => {@@ -21,20 +19,4 @@ describe("SidebarStageBackdrop", () => {expect(resolveEnvironmentIdentificationPillLabel("Latest")).toBeNull();expect(resolveEnvironmentIdentificationPillLabel("Alpha")).toBeNull();});-- it.each(["nightly", "dev"] as const)(- "uses unique SVG definition ids when %s artwork is rendered more than once",- (variant) => {- const markup = renderToStaticMarkup(- <>- <StageBackdropArt variant={variant} />- <StageBackdropArt variant={variant} />- </>,- );- const ids = Array.from(markup.matchAll(/\sid="([^"]+)"/g), (match) => match[1]);-- expect(ids.length).toBeGreaterThan(0);- expect(new Set(ids).size).toBe(ids.length);- },- );});diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.test.tsx b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsxsimilarity index 79%rename from apps/web/src/components/ThreadNotificationCoordinator.badge.test.tsxrename to apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsxindex f7f600986a0..695378034f4 100644--- a/apps/web/src/components/ThreadNotificationCoordinator.badge.test.tsx+++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsx@@ -1,38 +1,54 @@+import { RegistryContext } from "@effect/atom-react";import { EnvironmentId } from "@t3tools/contracts";import * as DateTime from "effect/DateTime";import * as Option from "effect/Option";+import { Atom, AtomRegistry } from "effect/reactivity";import { act } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";+import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";const state = vi.hoisted(() => ({mode: "notifications",inApp: false,toast: vi.fn(),- shells: new Map(),+ shells: null as unknown as { set: (id: string, value: unknown) => void },navigate: vi.fn(),sound: vi.fn(),badge: vi.fn(),environmentIds: ["one", "two"],}));-vi.mock("@effect/atom-react", () => ({ useAtomValue: (id: string) => state.shells.get(id) }));-vi.mock("@tanstack/react-router", () => ({- useNavigate: () => state.navigate,- useParams: () => ({}),+vi.mock(import("@tanstack/react-router"), async (original) => ({+ ...(await original()),+ useNavigate: (() => state.navigate) as never,+ useParams: (() => ({})) as never,}));-vi.mock("./ui/toast", () => ({ toastManager: { add: state.toast } }));-vi.mock("../state/shell", () => ({ environmentShell: { stateValueAtom: (id: string) => id } }));-vi.mock("../state/environments", () => ({- useEnvironmentIds: () => state.environmentIds,+vi.mock(import("./ui/toast"), async (original) => {+ const actual = await original();+ return { ...actual, toastManager: { ...actual.toastManager, add: state.toast as never } };+});+vi.mock(import("../state/shell"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ environmentShell: {+ ...actual.environmentShell,+ stateValueAtom: ((id: string) => shellAtom(id)) as never,+ },+ };+});+vi.mock(import("../state/environments"), async (original) => ({+ ...(await original()),+ useEnvironmentIds: (() => state.environmentIds) as never,}));-vi.mock("../hooks/useSettings", () => ({- useClientSettings: (+vi.mock(import("../hooks/useSettings"), async (original) => ({+ ...(await original()),+ useClientSettings: ((select: (settings: { notificationMode: string; inAppNotificationsEnabled: boolean }) => unknown,- ) => select({ notificationMode: state.mode, inAppNotificationsEnabled: state.inApp }),- getClientSettings: () => ({ notificationMode: state.mode }),+ ) => select({ notificationMode: state.mode, inAppNotificationsEnabled: state.inApp })) as never,+ getClientSettings: (() => ({ notificationMode: state.mode })) as never,}));-vi.mock("../threadNotifications", async (importOriginal) => ({- ...(await importOriginal<typeof import("../threadNotifications")>()),+vi.mock(import("../threadNotifications"), async (original) => ({+ ...(await original()),playNotificationSound: state.sound,unlockNotificationAudio: vi.fn(),setNotificationBadge: state.badge,@@ -40,6 +56,10 @@ vi.mock("../threadNotifications", async (importOriginal) => ({import { ThreadNotificationCoordinator } from "./ThreadNotificationCoordinator";+let registry: AtomRegistry.AtomRegistry;+const shellAtom = Atom.family((_id: string) => Atom.make<unknown>(null));+state.shells = { set: (id, value) => registry.set(shellAtom(id), value) };+class TestNotification extends EventTarget {static permission = "granted";static sent: TestNotification[] = [];@@ -65,7 +85,7 @@ const thread = {session: null as { status: string } | null,latestTurn: { turnId: "turn", state: "running", completedAt: null as string | null },};-let renderer: ReactTestRenderer | undefined;+let root: Root;let focused = false;let visibility = "visible";@@ -138,14 +158,18 @@ function complete(environment = "one", completedAt = "2026-09-13T08:00:00Z") {);}async function render() {- await act(async () => {- if (renderer) renderer.update(<ThreadNotificationCoordinator />);- else renderer = create(<ThreadNotificationCoordinator />);- });+ await act(async () =>+ root.render(+ <RegistryContext.Provider value={registry}>+ <ThreadNotificationCoordinator />+ </RegistryContext.Provider>,+ ),+ );}beforeEach(() => {vi.clearAllMocks();+ registry = AtomRegistry.make();state.mode = "notifications";state.inApp = false;state.environmentIds = ["one", "two"];@@ -157,21 +181,19 @@ beforeEach(() => {TestNotification.sent = [];vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);vi.stubGlobal("Notification", TestNotification);- vi.stubGlobal("window", Object.assign(new EventTarget(), { focus: vi.fn() }));- vi.stubGlobal(- "document",- Object.assign(new EventTarget(), {- hasFocus: () => focused,- get visibilityState() {- return visibility;- },- }),+ vi.spyOn(window, "focus").mockImplementation(() => undefined);+ vi.spyOn(document, "hasFocus").mockImplementation(() => focused);+ vi.spyOn(document, "visibilityState", "get").mockImplementation(+ () => visibility as DocumentVisibilityState,);+ root = createRoot(document.createElement("div"));});afterEach(async () => {- await act(async () => renderer?.unmount());- renderer = undefined;+ await act(async () => root.unmount());+ delete window.desktopBridge;+ registry.dispose();+ vi.restoreAllMocks();vi.unstubAllGlobals();});@@ -247,8 +269,8 @@ it("starts a fresh count after another native app window gains focus", async ()complete("two");await render();expect(state.badge).toHaveBeenLastCalledWith(1);- await act(async () => renderer!.unmount());- renderer = undefined;+ await act(async () => root.unmount());+ root = createRoot(document.createElement("div"));expect(unsubscribe).toHaveBeenCalledOnce();expect(state.badge).toHaveBeenLastCalledWith(0);});diff --git a/apps/web/src/components/ThreadNotificationCoordinator.test.tsx b/apps/web/src/components/ThreadNotificationCoordinator.browser.test.tsxsimilarity index 88%rename from apps/web/src/components/ThreadNotificationCoordinator.test.tsxrename to apps/web/src/components/ThreadNotificationCoordinator.browser.test.tsxindex 89425924f7e..93de18b6b3e 100644--- a/apps/web/src/components/ThreadNotificationCoordinator.test.tsx+++ b/apps/web/src/components/ThreadNotificationCoordinator.browser.test.tsx@@ -2,7 +2,7 @@ import type { ClientSettings } from "@t3tools/contracts/settings";import * as DateTime from "effect/DateTime";import * as Option from "effect/Option";import { act } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";+import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";const state = vi.hoisted(() => ({@@ -110,48 +110,50 @@ function mockThreads() {return [stableParent, child];}-vi.mock("@effect/atom-react", () => ({- useAtomValue: () => ({+vi.mock(import("@effect/atom-react"), async (original) => ({+ ...(await original()),+ useAtomValue: (() => ({status: state.live ? "live" : "disconnected",snapshot: Option.some({ threads: mockThreads() }),- }),+ })) as never,}));-vi.mock("@tanstack/react-router", () => ({- useNavigate: () => state.navigate,- useParams: () => state.active,+vi.mock(import("@tanstack/react-router"), async (original) => ({+ ...(await original()),+ useNavigate: (() => state.navigate) as never,+ useParams: (() => state.active) as never,}));-vi.mock("../hooks/useSettings", () => ({- useClientSettings: (+vi.mock(import("../hooks/useSettings"), async (original) => ({+ ...(await original()),+ useClientSettings: ((select: (settings: Pick<ClientSettings, "notificationMode" | "inAppNotificationsEnabled">,) => unknown,- ) => select({ notificationMode: state.mode, inAppNotificationsEnabled: state.inApp }),- getClientSettings: () => ({ notificationMode: state.mode }),-}));-vi.mock("../state/environments", () => ({- useEnvironmentIds: () => ["env-1"],+ ) => select({ notificationMode: state.mode, inAppNotificationsEnabled: state.inApp })) as never,+ getClientSettings: (() => ({ notificationMode: state.mode })) as never,}));-vi.mock("../state/shell", () => ({- environmentShell: { stateValueAtom: vi.fn() },+vi.mock(import("../state/environments"), async (original) => ({+ ...(await original()),+ useEnvironmentIds: (() => ["env-1"]) as never,}));-vi.mock("../threadNotifications", async (importOriginal) => ({- ...(await importOriginal<typeof import("../threadNotifications")>()),+vi.mock(import("../threadNotifications"), async (original) => ({+ ...(await original()),playNotificationSound: state.sound,setNotificationBadge: vi.fn(),}));-vi.mock("./ui/toast", () => ({- toastManager: { add: state.add, close: state.close },-}));+vi.mock(import("./ui/toast"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ toastManager: { ...actual.toastManager, add: state.add as never, close: state.close },+ };+});import { ThreadNotificationCoordinator } from "./ThreadNotificationCoordinator";-let renderer: ReactTestRenderer | undefined;+let root: Root;async function render() {- await act(() => {- if (renderer) renderer.update(<ThreadNotificationCoordinator />);- else renderer = create(<ThreadNotificationCoordinator />);- });+ await act(() => root.render(<ThreadNotificationCoordinator />));}async function complete() {@@ -181,21 +183,17 @@ beforeEach(() => {});stableParent = null;vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- vi.stubGlobal("window", new EventTarget());- vi.stubGlobal("document", {- get visibilityState() {- return state.visible;- },- hasFocus: () => state.focused,- addEventListener: vi.fn(),- removeEventListener: vi.fn(),- });+ vi.spyOn(document, "visibilityState", "get").mockImplementation(+ () => state.visible as DocumentVisibilityState,+ );+ vi.spyOn(document, "hasFocus").mockImplementation(() => state.focused);vi.stubGlobal("Notification", Object.assign(state.notification, { permission: "granted" }));+ root = createRoot(document.createElement("div"));});afterEach(async () => {- await act(() => renderer?.unmount());- renderer = undefined;+ await act(() => root.unmount());+ vi.restoreAllMocks();vi.unstubAllGlobals();});diff --git a/apps/web/src/components/ThreadStatusIndicators.subscriptions.test.tsx b/apps/web/src/components/ThreadStatusIndicators.subscriptions.browser.test.tsxsimilarity index 50%rename from apps/web/src/components/ThreadStatusIndicators.subscriptions.test.tsxrename to apps/web/src/components/ThreadStatusIndicators.subscriptions.browser.test.tsxindex e32fb100094..9d5a2c12293 100644--- a/apps/web/src/components/ThreadStatusIndicators.subscriptions.test.tsx+++ b/apps/web/src/components/ThreadStatusIndicators.subscriptions.browser.test.tsx@@ -1,6 +1,6 @@import { ProjectId, ThreadId, type VcsStatusResult } from "@t3tools/contracts";-import { act, type ComponentProps, type ReactNode } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";+import { act } from "react";+import { createRoot } from "react-dom/client";import { afterEach, expect, it, vi } from "vite-plus/test";import { AppAtomRegistryProvider } from "../rpc/atomRegistry";@@ -8,9 +8,12 @@ import { makeThreadFixture } from "../test-fixtures";const state = vi.hoisted(() => ({ queries: [] as string[] }));-vi.mock("../state/entities", () => ({ useProject: () => null, useServerConfigs: () => new Map() }));-vi.mock("../uiStateStore", () => ({ useUiStateStore: () => undefined }));-vi.mock("../state/vcs", async () => {+vi.mock(import("../state/entities"), async (original) => ({+ ...(await original()),+ useProject: () => null,+ useServerConfigs: () => new Map(),+}));+vi.mock(import("../state/vcs"), async (original) => {const { AsyncResult, Atom } = await import("effect/reactivity");const statuses = Atom.family((cwd: string) =>Atom.make(() => {@@ -36,12 +39,17 @@ vi.mock("../state/vcs", async () => {} satisfies VcsStatusResult);}),);+ const actual = await original();return {- vcsEnvironment: { status: ({ input }: { input: { cwd: string } }) => statuses(input.cwd) },+ ...actual,+ vcsEnvironment: {+ ...actual.vcsEnvironment,+ status: (({ input }: { input: { cwd: string } }) => statuses(input.cwd)) as never,+ },};});-vi.mock("../state/pullRequests", async (importOriginal) => {- const original = await importOriginal<typeof import("../state/pullRequests")>();+vi.mock(import("../state/pullRequests"), async (importOriginal) => {+ const original = await importOriginal();const { AsyncResult, Atom } = await import("effect/reactivity");const { ProjectId } = await import("@t3tools/contracts");const summaries = Atom.family((number: number) =>@@ -63,44 +71,23 @@ vi.mock("../state/pullRequests", async (importOriginal) => {);return {...original,- linkedPullRequestDetailAtom: ({ input }: { input: { number: number } }) =>- summaries(input.number),- };-});-vi.mock("./ui/tooltip", async () => {- const { cloneElement, isValidElement } = await import("react");- return {- Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,- TooltipTrigger({- render,- children,- }: ComponentProps<typeof import("./ui/tooltip").TooltipTrigger>) {- return isValidElement(render) ? cloneElement(render, undefined, children) : children;- },- TooltipPopup: () => null,+ linkedPullRequestDetailAtom: (({ input }: { input: { number: number } }) =>+ summaries(input.number)) as never,};});-import { ThreadRowLeadingStatus } from "./ThreadStatusIndicators";afterEach(() => {vi.unstubAllGlobals();});+// The lease overscans 160px around a 20px viewport, a 340px band. With 45px rows the band+// covers exactly 8 rows at each scroll position below.+const ROW_HEIGHT = 45;+const SPACER = 1000;+it("leases only visible palette results while retaining observed and cached PR badges", async () => {- const observers: Array<{ setVisible: (visible: boolean) => void }> = [];- const scrollRoot = {};vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- vi.stubGlobal(- "IntersectionObserver",- class {- constructor(callback: (entries: ReadonlyArray<{ isIntersecting: boolean }>) => void) {- observers.push({ setVisible: (visible) => callback([{ isIntersecting: visible }]) });- }- observe() {}- disconnect() {}- },- );const threads = Array.from({ length: 128 }, (_, index) =>makeThreadFixture({id: ThreadId.make(`palette-thread-${index}`),@@ -117,64 +104,73 @@ it("leases only visible palette results while retaining observed and cached PR b},}),);- let renderer: ReactTestRenderer | undefined;+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);state.queries.length = 0;- try {+ const viewport = () =>+ container.querySelector<HTMLElement>('[data-slot="scroll-area-viewport"]')!;+ const scrollTo = async (top: number) => {await act(async () => {- renderer = create(+ viewport().scrollTop = top;+ await new Promise((resolve) => requestAnimationFrame(() => setTimeout(resolve, 50)));+ });+ };+ const badgeCount = () =>+ [...container.querySelectorAll("[aria-label]")].filter((node) =>+ node.getAttribute("aria-label")!.startsWith("PR #"),+ ).length;+ try {+ await act(async () =>+ root.render(<AppAtomRegistryProvider>- {threads.map((thread, index) => (- <span key={thread.id}>- <ThreadRowLeadingStatus- thread={thread}- snapshot={- index === 126- ? {- branch: "feature/test",- sourceControlProvider: undefined,- pr: {- number: 126,- title: "Cached badge",- url: "https://github.com/example/repo/pull/126",- baseRef: "main",- headRef: "feature/test",- state: "open",- },- }- : undefined- }- />- {thread.title}- </span>- ))}+ <div data-slot="scroll-area-viewport" style={{ height: 20, overflowY: "auto" }}>+ <div style={{ height: SPACER }} />+ {threads.map((thread, index) => (+ <div key={thread.id} style={{ height: ROW_HEIGHT, overflow: "hidden" }}>+ <ThreadRowLeadingStatus+ thread={thread}+ snapshot={+ index === 126+ ? {+ branch: "feature/test",+ sourceControlProvider: undefined,+ pr: {+ number: 126,+ title: "Cached badge",+ url: "https://github.com/example/repo/pull/126",+ baseRef: "main",+ headRef: "feature/test",+ state: "open",+ },+ }+ : undefined+ }+ />+ {thread.title}+ </div>+ ))}+ </div></AppAtomRegistryProvider>,- { createNodeMock: () => ({ parentElement: { closest: () => scrollRoot } }) },- );- });- const mounted = renderer!;- const badgeCount = () =>- mounted.root.findAll(- (node) => node.type === "span" && String(node.props["aria-label"] ?? "").startsWith("PR #"),- ).length;- expect(observers).toHaveLength(128);+ ),+ );+ await scrollTo(0);expect(state.queries).toEqual([]);expect(badgeCount()).toBe(1);- await act(async () => {- for (const observer of observers.slice(0, 8)) observer.setVisible(true);- });+ // Band [1000, 1340]: rows 0..7.+ await scrollTo(SPACER + 160);expect(state.queries).toHaveLength(8);expect(state.queries.filter((key) => key.startsWith("vcs:"))).toHaveLength(4);expect(state.queries.filter((key) => key.startsWith("pr:"))).toHaveLength(4);expect(badgeCount()).toBe(9);- await act(async () => {- for (const observer of observers.slice(0, 8)) observer.setVisible(false);- for (const observer of observers.slice(8, 16)) observer.setVisible(true);- });+ // Band [1370, 1710]: rows 8..15.+ await scrollTo(SPACER + 8 * ROW_HEIGHT + 10 + 160);expect(state.queries).toHaveLength(16);expect(badgeCount()).toBe(17);} finally {- await act(async () => renderer?.unmount());+ await act(async () => root.unmount());+ container.remove();}});diff --git a/apps/web/src/components/ThreadStatusIndicators.test.tsx b/apps/web/src/components/ThreadStatusIndicators.test.tsxindex 3ae07b40306..d42043b847b 100644--- a/apps/web/src/components/ThreadStatusIndicators.test.tsx+++ b/apps/web/src/components/ThreadStatusIndicators.test.tsx@@ -1,42 +1,7 @@-import { ThreadId, type ThreadPullRequestLink } from "@t3tools/contracts";-import { renderToStaticMarkup } from "react-dom/server";+import type { ThreadPullRequestLink } from "@t3tools/contracts";import { describe, expect, it } from "vite-plus/test";-import { ThreadWorktreeIndicator, linkedPullRequestSnapshotStatus } from "./ThreadStatusIndicators";--describe("ThreadWorktreeIndicator", () => {- it("renders the worktree folder and branch in an accessible label", () => {- const markup = renderToStaticMarkup(- <ThreadWorktreeIndicator- thread={{- id: ThreadId.make("thread-1"),- branch: "feature/sidebar-indicator",- worktreePath: "/tmp/worktrees/sidebar-indicator",- }}- />,- );-- expect(markup).toContain('role="img"');- expect(markup).toContain(- 'aria-label="Worktree: sidebar-indicator (feature/sidebar-indicator)"',- );- expect(markup).toContain('data-testid="thread-worktree-thread-1"');- });-- it.each([null, "", " "])("renders nothing for an absent worktree path", (worktreePath) => {- const markup = renderToStaticMarkup(- <ThreadWorktreeIndicator- thread={{- id: ThreadId.make("thread-1"),- branch: "main",- worktreePath,- }}- />,- );-- expect(markup).toBe("");- });-});+import { linkedPullRequestSnapshotStatus } from "./ThreadStatusIndicators";describe("linked pull request snapshots", () => {const link: ThreadPullRequestLink = {diff --git a/apps/web/src/components/ThreadTerminalDrawer.permissions.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.permissions.browser.test.tsxsimilarity index 68%rename from apps/web/src/components/ThreadTerminalDrawer.permissions.test.tsxrename to apps/web/src/components/ThreadTerminalDrawer.permissions.browser.test.tsxindex b189d729906..adbc8c9ca5b 100644--- a/apps/web/src/components/ThreadTerminalDrawer.permissions.test.tsx+++ b/apps/web/src/components/ThreadTerminalDrawer.permissions.browser.test.tsx@@ -7,7 +7,8 @@ import {import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";import { nextTerminalAttachSeedState } from "@t3tools/client-runtime/state/terminal";import { AsyncResult } from "effect/reactivity";-import { act, create, type ReactTestRenderer } from "react-test-renderer";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";import type {GhosttyTerminalSurface,@@ -28,34 +29,47 @@ const state = vi.hoisted(() => ({>(),}));-vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));-vi.mock("../hooks/useSettings", () => ({+vi.mock(import("@effect/atom-react"), async (original) => ({+ ...(await original()),+ useAtomValue: (() => null) as never,+}));+vi.mock(import("../hooks/useSettings"), async (original) => ({+ ...(await original()),getClientSettings: () => DEFAULT_CLIENT_SETTINGS,- useClientSettings: (select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>- select(DEFAULT_CLIENT_SETTINGS),+ useClientSettings: ((select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>+ select(DEFAULT_CLIENT_SETTINGS)) as never,}));-vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => state.otherCommand }));-vi.mock("../localApi", () => ({ readLocalApi: () => null }));-vi.mock("../state/server", () => ({- serverEnvironment: { configValueAtom: () => "config" },+vi.mock(import("../editorPreferences"), async (original) => ({+ ...(await original()),+ useOpenInPreferredEditor: (() => state.otherCommand) as never,}));-vi.mock("../state/preview", () => ({ previewEnvironment: { open: "open" } }));-vi.mock("../state/terminal", () => ({ terminalEnvironment: { resize: "resize", write: "write" } }));-vi.mock("../state/use-atom-command", () => ({- useAtomCommand: (command: string) => (command === "resize" ? state.resize : state.otherCommand),+vi.mock(import("../state/terminal"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ terminalEnvironment: { ...actual.terminalEnvironment, resize: "resize" as never },+ };+});+vi.mock(import("../state/use-atom-command"), async (original) => ({+ ...(await original()),+ useAtomCommand: ((command: unknown) =>+ command === "resize" ? state.resize : state.otherCommand) as never,}));-vi.mock("../state/terminalSessions", () => ({- useAttachedTerminalSession: () => session,+vi.mock(import("../state/terminalSessions"), async (original) => ({+ ...(await original()),+ useAttachedTerminalSession: (() => session) as never,}));-vi.mock("~/terminal/ghostty/surface", () => ({- GhosttyTerminalSurface: { create: state.createSurface },+vi.mock(import("~/terminal/ghostty/surface"), async (original) => ({+ ...(await original()),+ GhosttyTerminalSurface: { create: state.createSurface } as never,}));-vi.mock("../state/session", async () => {+vi.mock(import("../state/session"), async (original) => {const { useSyncExternalStore } = await import("react");const readEnvironmentScope = (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>id !== null &&(scope !== AuthTerminalOperateScope || id !== threadRef.environmentId || state.allowed);return {+ ...(await original()),readEnvironmentScope,useEnvironmentScope: (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>useSyncExternalStore(@@ -75,7 +89,8 @@ const threadRef = {threadId: ThreadId.make("thread"),};const session = { ...nextTerminalAttachSeedState(), status: "running" as const, version: 1 };-let renderer: ReactTestRenderer | undefined;+let root: Root;+let container: HTMLDivElement;beforeEach(() => {state.allowed = true;@@ -86,29 +101,20 @@ beforeEach(() => {// pending. Keep that unrelated setup pending while exercising its callback.state.createSurface.mockReset().mockReturnValue(new Promise(() => undefined));vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- vi.stubGlobal("document", {- body: {},- documentElement: { classList: { contains: () => false } },- querySelector: () => null,- createElement: () => ({ getContext: () => null }),- });- vi.stubGlobal("getComputedStyle", () => ({- colorScheme: "light",- backgroundColor: "",- color: "",- getPropertyValue: () => "",- }));+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);});afterEach(async () => {- await act(async () => renderer?.unmount());- renderer = undefined;+ await act(async () => root.unmount());+ container.remove();vi.unstubAllGlobals();});it("rechecks the target terminal grant when a retained surface callback reports a resize", async () => {- await act(async () => {- renderer = create(+ await act(async () =>+ root.render(<TerminalViewportadvancedTypography={false}threadRef={threadRef}@@ -124,9 +130,8 @@ it("rechecks the target terminal grant when a retained surface callback reportsdrawerHeight={200}keybindings={[]}/>,- { createNodeMock: () => ({ closest: () => null, contains: () => false }) },- );- });+ ),+ );expect(state.createSurface).toHaveBeenCalledOnce();const onResize = state.createSurface.mock.calls[0]![1].onResize;if (!onResize) throw new Error("The terminal did not register its resize callback.");diff --git a/apps/web/src/components/search/ProjectContentSearchDialog.browser.test.tsx b/apps/web/src/components/search/ProjectContentSearchDialog.browser.test.tsxnew file mode 100644index 00000000000..a9eefdaa582--- /dev/null+++ b/apps/web/src/components/search/ProjectContentSearchDialog.browser.test.tsx@@ -0,0 +1,153 @@+import { scopeThreadRef } from "@t3tools/client-runtime/environment";+import { AuthFilesystemReadScope, EnvironmentId, ThreadId } from "@t3tools/contracts";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";++const state = vi.hoisted(() => ({+ readScope: vi.fn(),+ // The real query hands back the same result array until the search changes.+ matches: [+ {+ resultIndex: 0,+ path: "src/index.ts",+ lineNumber: 3,+ lineContent: "match",+ matchRanges: [],+ },+ ],+ noMatches: [],+ access: { canReadFiles: true, isCheckingAccess: false },+ listeners: new Set<() => void>(),+}));++// The real query is subscription-backed, so access changes reach the dialog without a parent render.+function setAccess(access: { canReadFiles: boolean; isCheckingAccess: boolean }) {+ state.access = access;+ for (const listener of state.listeners) listener();+}++const target = {+ environmentId: EnvironmentId.make("content-search-secondary"),+ cwd: "/project",+ projectName: "Project",+ threadRef: scopeThreadRef(+ EnvironmentId.make("content-search-secondary"),+ ThreadId.make("content-search-thread"),+ ),+};++vi.mock(import("~/hooks/useActiveProjectTarget"), async (original) => ({+ ...(await original()),+ useActiveProjectTarget: () => target,+}));+vi.mock(import("~/state/session"), async (original) => ({+ ...(await original()),+ readEnvironmentScope: state.readScope,+}));+vi.mock(import("~/state/queries"), async (original) => {+ const { useSyncExternalStore } = await import("react");+ const subscribe = (listener: () => void) => {+ state.listeners.add(listener);+ return () => state.listeners.delete(listener);+ };+ return {+ ...(await original()),+ useProjectContentSearch: (({ query }: { query: string }) => {+ const { canReadFiles, isCheckingAccess } = useSyncExternalStore(+ subscribe,+ () => state.access,+ );+ return {+ canReadFiles,+ isCheckingAccess,+ error: null,+ isPending: isCheckingAccess,+ hasQuery: query.length > 0,+ truncated: false,+ invalidRegex: false,+ matches: canReadFiles && query.length > 0 ? state.matches : state.noMatches,+ };+ }) as never,+ };+});++import { useRightPanelStore } from "~/rightPanelStore";+import { ProjectContentSearchDialog } from "./ProjectContentSearchDialog";++let root: Root;+let container: HTMLDivElement;+const onOpenChange = vi.fn();+const openFile = vi.fn();++beforeEach(() => {+ state.access = { canReadFiles: true, isCheckingAccess: false };+ state.listeners.clear();+ state.readScope.mockReset().mockReturnValue(true);+ openFile.mockClear();+ onOpenChange.mockClear();+ vi.spyOn(useRightPanelStore.getState(), "openFile").mockImplementation(openFile);+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});++afterEach(async () => {+ await act(() => root.unmount());+ container.remove();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++const input = () => container.querySelector("input")!;+const result = () => container.querySelector<HTMLButtonElement>("[data-content-search-result]");++async function openSearch() {+ await act(() => root.render(<ProjectContentSearchDialog onOpenChange={onOpenChange} />));+}++async function type(text: string) {+ await act(async () => {+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;+ setValue.call(input(), text);+ input().dispatchEvent(new Event("input", { bubbles: true }));+ });+}++it("enables search after access resolves and opens a result in its own environment", async () => {+ state.access = { canReadFiles: false, isCheckingAccess: true };+ await openSearch();+ expect(input().disabled).toBe(true);+ expect(container.textContent).toContain("Checking file access…");++ await act(() => setAccess({ canReadFiles: true, isCheckingAccess: false }));+ expect(input().disabled).toBe(false);+ await type("match");+ await act(async () => result()!.click());++ expect(state.readScope).toHaveBeenCalledWith(target.environmentId, AuthFilesystemReadScope);+ expect(openFile).toHaveBeenCalledWith(target.threadRef, "src/index.ts", 3);+ expect(onOpenChange).toHaveBeenCalledWith(false);+});++it.each(["pointer", "keyboard"])(+ "rechecks access before a retained %s action opens a result",+ async (action) => {+ await openSearch();+ await type("match");++ state.readScope.mockReturnValue(false);+ await act(async () => {+ if (action === "pointer") result()!.click();+ else+ input().dispatchEvent(+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }),+ );+ });++ expect(state.readScope).toHaveBeenCalled();+ expect(openFile).not.toHaveBeenCalled();+ expect(onOpenChange).not.toHaveBeenCalled();+ },+);diff --git a/apps/web/src/components/search/ProjectContentSearchDialog.test.tsx b/apps/web/src/components/search/ProjectContentSearchDialog.test.tsxdeleted file mode 100644index 40aa0b2cb9a..00000000000--- a/apps/web/src/components/search/ProjectContentSearchDialog.test.tsx+++ /dev/null@@ -1,131 +0,0 @@-import { scopeThreadRef } from "@t3tools/client-runtime/environment";-import { AuthFilesystemReadScope, EnvironmentId, ThreadId } from "@t3tools/contracts";-import type { ReactNode } from "react";-import { act, create, type ReactTestRenderer } from "react-test-renderer";-import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";--const state = vi.hoisted(() => ({- canReadFiles: true,- isCheckingAccess: false,- error: null as string | null,- readScope: vi.fn(),- openFile: vi.fn(),- // The real query hands back the same result array until the search changes.- matches: [- {- resultIndex: 0,- path: "src/index.ts",- lineNumber: 3,- lineContent: "match",- matchRanges: [],- },- ],- noMatches: [],-}));--const target = {- environmentId: EnvironmentId.make("content-search-secondary"),- cwd: "/project",- projectName: "Project",- threadRef: scopeThreadRef(- EnvironmentId.make("content-search-secondary"),- ThreadId.make("content-search-thread"),- ),-};--vi.mock("~/hooks/useActiveProjectTarget", () => ({ useActiveProjectTarget: () => target }));-vi.mock("~/hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "light" }) }));-vi.mock("~/rightPanelStore", () => ({- useRightPanelStore: { getState: () => ({ openFile: state.openFile }) },-}));-vi.mock("~/state/session", () => ({ readEnvironmentScope: state.readScope }));-vi.mock("~/state/queries", () => ({- useProjectContentSearch: ({ query }: { query: string }) => ({- canReadFiles: state.canReadFiles,- isCheckingAccess: state.isCheckingAccess,- error: state.error,- isPending: state.isCheckingAccess,- hasQuery: query.length > 0,- truncated: false,- invalidRegex: false,- matches: state.canReadFiles && query.length > 0 ? state.matches : state.noMatches,- }),-}));-vi.mock("../CommandPaletteContent", () => ({ CommandPaletteContent: "section" }));-vi.mock("../chat/PierreEntryIcon", () => ({ PierreEntryIcon: () => null }));-vi.mock("./HighlightedSearchLine", () => ({ HighlightedSearchLine: () => null }));-vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));-vi.mock("../ui/toggle", () => ({ Toggle: "button" }));-vi.mock("../ui/tooltip", () => ({- Tooltip: "div",- TooltipPopup: "span",- TooltipTrigger: ({ render }: { render: ReactNode }) => render,-}));--import { ProjectContentSearchDialog } from "./ProjectContentSearchDialog";--let renderer: ReactTestRenderer | undefined;-const onOpenChange = vi.fn();--beforeEach(() => {- state.canReadFiles = true;- state.isCheckingAccess = false;- state.error = null;- state.readScope.mockReset().mockReturnValue(true);- state.openFile.mockClear();- onOpenChange.mockClear();- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- vi.stubGlobal("document", { querySelector: () => null });-});--afterEach(async () => {- await act(() => renderer?.unmount());- vi.unstubAllGlobals();-});--async function openSearch() {- await act(() => {- renderer = create(<ProjectContentSearchDialog onOpenChange={onOpenChange} />);- });- return renderer!.root;-}--it("enables search after access resolves and opens a result in its own environment", async () => {- state.canReadFiles = false;- state.isCheckingAccess = true;- const root = await openSearch();- expect(root.findByType("section").props.inputProps.disabled).toBe(true);- expect(- root.findAllByType("div").some((node) => node.children.includes("Checking file access…")),- ).toBe(true);-- state.canReadFiles = true;- state.isCheckingAccess = false;- await act(() => renderer!.update(<ProjectContentSearchDialog onOpenChange={onOpenChange} />));- expect(root.findByType("section").props.inputProps.disabled).toBe(false);- await act(() => root.findByType("section").props.onValueChange("match"));- await act(() => root.findByProps({ "data-content-search-result": 0 }).props.onClick());-- expect(state.readScope).toHaveBeenCalledWith(target.environmentId, AuthFilesystemReadScope);- expect(state.openFile).toHaveBeenCalledWith(target.threadRef, "src/index.ts", 3);- expect(onOpenChange).toHaveBeenCalledWith(false);-});--it.each(["pointer", "keyboard"])(- "rechecks access before a retained %s action opens a result",- async (action) => {- const root = await openSearch();- await act(() => root.findByType("section").props.onValueChange("match"));- const openResult = root.findByProps({ "data-content-search-result": 0 }).props.onClick;- const onKeyDown = root.findByType("section").props.inputProps.onKeyDown;-- state.readScope.mockReturnValue(false);- await act(() => {- if (action === "pointer") openResult();- else onKeyDown({ key: "Enter", preventDefault() {} });- });-- expect(state.openFile).not.toHaveBeenCalled();- expect(onOpenChange).not.toHaveBeenCalled();- },-);diff --git a/apps/web/src/hooks/useActiveThreadRef.test.tsx b/apps/web/src/hooks/useActiveThreadRef.browser.test.tsxsimilarity index 83%rename from apps/web/src/hooks/useActiveThreadRef.test.tsxrename to apps/web/src/hooks/useActiveThreadRef.browser.test.tsxindex 4afc4071f1b..d31ccda34cf 100644--- a/apps/web/src/hooks/useActiveThreadRef.test.tsx+++ b/apps/web/src/hooks/useActiveThreadRef.browser.test.tsx@@ -1,13 +1,13 @@import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";import { act } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";+import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";import { useActiveThreadRef } from "./useActiveThreadRef";type ThreadLike = { environmentId: EnvironmentId; id: ThreadId; status: string } | null;-let renderer: ReactTestRenderer | null = null;+let root: Root;let observed: Array<ScopedThreadRef | null> = [];function Probe({ thread }: { thread: ThreadLike }) {@@ -22,21 +22,18 @@ const thread = (id: string, status = "idle"): ThreadLike => ({});async function render(value: ThreadLike) {- await act(() => {- if (renderer) renderer.update(<Probe thread={value} />);- else renderer = create(<Probe thread={value} />);- });+ await act(() => root.render(<Probe thread={value} />));return observed.at(-1);}beforeEach(() => {observed = [];vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ root = createRoot(document.createElement("div"));});afterEach(async () => {- await act(() => renderer?.unmount());- renderer = null;+ await act(() => root.unmount());vi.unstubAllGlobals();});diff --git a/apps/web/src/hooks/useEnvironmentDisconnectDelay.test.tsx b/apps/web/src/hooks/useEnvironmentDisconnectDelay.browser.test.tsxsimilarity index 51%rename from apps/web/src/hooks/useEnvironmentDisconnectDelay.test.tsxrename to apps/web/src/hooks/useEnvironmentDisconnectDelay.browser.test.tsxindex f584112df4d..669a9e1362e 100644--- a/apps/web/src/hooks/useEnvironmentDisconnectDelay.test.tsx+++ b/apps/web/src/hooks/useEnvironmentDisconnectDelay.browser.test.tsx@@ -1,65 +1,65 @@import { EnvironmentId } from "@t3tools/contracts";-import { act, useLayoutEffect } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";import { useEnvironmentDisconnectDelay } from "./useEnvironmentDisconnectDelay";const environmentId = EnvironmentId.make("remote");-let renderer: ReactTestRenderer;-let elapsed = false;+let root: Root;+let container: HTMLDivElement;function Probe({ unavailableId }: { unavailableId: EnvironmentId | null }) {- const value = useEnvironmentDisconnectDelay(unavailableId);- useLayoutEffect(() => {- elapsed = value;- });- return null;+ return <>{useEnvironmentDisconnectDelay(unavailableId) ? "Disconnected" : "Waiting"}</>;}+const shown = () => container.textContent;+const render = (unavailableId: EnvironmentId | null) =>+ act(() => root.render(<Probe unavailableId={unavailableId} />));+beforeEach(() => {vi.useFakeTimers();vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- act(() => {- renderer = create(<Probe unavailableId={environmentId} />);- });+ container = document.createElement("div");+ root = createRoot(container);+ render(environmentId);});afterEach(() => {- act(() => renderer.unmount());+ act(() => root.unmount());vi.useRealTimers();vi.unstubAllGlobals();});it("waits 20 seconds without restarting on renders for the same environment", () => {act(() => vi.advanceTimersByTime(10_000));- expect(elapsed).toBe(false);- act(() => renderer.update(<Probe unavailableId={environmentId} />));+ expect(shown()).toBe("Waiting");+ render(environmentId);act(() => vi.advanceTimersByTime(9_999));- expect(elapsed).toBe(false);+ expect(shown()).toBe("Waiting");act(() => vi.advanceTimersByTime(1));- expect(elapsed).toBe(true);+ expect(shown()).toBe("Disconnected");});it("cancels a brief outage and starts a fresh delay on the next outage", () => {act(() => vi.advanceTimersByTime(10_000));- act(() => renderer.update(<Probe unavailableId={null} />));+ render(null);act(() => vi.advanceTimersByTime(20_000));- expect(elapsed).toBe(false);- act(() => renderer.update(<Probe unavailableId={environmentId} />));+ expect(shown()).toBe("Waiting");+ render(environmentId);act(() => vi.advanceTimersByTime(19_999));- expect(elapsed).toBe(false);+ expect(shown()).toBe("Waiting");act(() => vi.advanceTimersByTime(1));- expect(elapsed).toBe(true);- act(() => renderer.update(<Probe unavailableId={null} />));- expect(elapsed).toBe(false);+ expect(shown()).toBe("Disconnected");+ render(null);+ expect(shown()).toBe("Waiting");});it("does not carry elapsed time to another environment", () => {act(() => vi.advanceTimersByTime(20_000));- expect(elapsed).toBe(true);- act(() => renderer.update(<Probe unavailableId={EnvironmentId.make("another-remote")} />));- expect(elapsed).toBe(false);+ expect(shown()).toBe("Disconnected");+ render(EnvironmentId.make("another-remote"));+ expect(shown()).toBe("Waiting");act(() => vi.advanceTimersByTime(20_000));- expect(elapsed).toBe(true);+ expect(shown()).toBe("Disconnected");});diff --git a/apps/web/src/hooks/useHtmlRenderTheme.test.ts b/apps/web/src/hooks/useHtmlRenderTheme.browser.test.tsxsimilarity index 82%rename from apps/web/src/hooks/useHtmlRenderTheme.test.tsrename to apps/web/src/hooks/useHtmlRenderTheme.browser.test.tsxindex 83f72b894ce..368b3d9beb0 100644--- a/apps/web/src/hooks/useHtmlRenderTheme.test.ts+++ b/apps/web/src/hooks/useHtmlRenderTheme.browser.test.tsx@@ -1,7 +1,7 @@import { HTML_RENDER_DEFAULT_FONTS, type HtmlRenderTheme } from "@t3tools/shared/htmlRender";import { BUILT_IN_THEME_IDS } from "@t3tools/shared/themePalettes";-import { act, createElement, useEffect } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";+import { act, useEffect } from "react";+import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";import {@@ -19,14 +19,12 @@ const selection = vi.hoisted(() => ({themeHalves: null as ThemeHalves | null,}));-vi.mock("./useTheme", () => ({ useTheme: () => selection }));-vi.mock("./useSettings", () => ({- useClientSettings: (- select: (settings: { fontFamilySans: string; fontFamilyCode: string }) => string,- ) => select({ fontFamilySans: "", fontFamilyCode: "" }),+vi.mock(import("./useTheme"), async (original) => ({+ ...(await original()),+ useTheme: (() => selection) as never,}));-let renderer: ReactTestRenderer | undefined;+let root: Root | undefined;beforeEach(() => {vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);@@ -34,8 +32,8 @@ beforeEach(() => {});afterEach(() => {- act(() => renderer?.unmount());- renderer = undefined;+ act(() => root?.unmount());+ root = undefined;setEnvironmentThemes([]);vi.unstubAllGlobals();});@@ -49,9 +47,9 @@ function readRenderTheme(): HtmlRenderTheme {}, [resolved]);return null;}- act(() => {- renderer = create(createElement(Probe));- });+ act(() => root?.unmount());+ root = createRoot(document.createElement("div"));+ act(() => root!.render(<Probe />));if (!theme) throw new Error("The HTML render theme was not resolved.");return theme;}diff --git a/apps/web/src/hooks/useLiveRefresh.browser.test.tsx b/apps/web/src/hooks/useLiveRefresh.browser.test.tsxnew file mode 100644index 00000000000..803eb0f0534--- /dev/null+++ b/apps/web/src/hooks/useLiveRefresh.browser.test.tsx@@ -0,0 +1,88 @@+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";++import { LIVE_REFRESH_IDLE_AFTER_MS, useLiveRefresh } from "./useLiveRefresh";++let root: Root;+let visibility: DocumentVisibilityState;+const refresh = vi.fn();++function setVisibility(next: DocumentVisibilityState) {+ visibility = next;+ document.dispatchEvent(new Event("visibilitychange"));+}++beforeEach(() => {+ vi.useFakeTimers();+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ visibility = "visible";+ vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility);+ refresh.mockReset();+ root = createRoot(document.createElement("div"));+});++afterEach(() => {+ act(() => root.unmount());+ vi.restoreAllMocks();+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe("live refresh cadence", () => {+ it("polls every 45 seconds, pauses while hidden or busy, respects disabling, and cleans up", () => {+ vi.setSystemTime(0);+ function Probe({ pending = false, enabled = true }) {+ useLiveRefresh(pending ? null : refresh, { intervalMs: 45_000, enabled });+ return null;+ }+ act(() => root.render(<Probe />));+ act(() => vi.advanceTimersByTime(44_999));+ expect(refresh).not.toHaveBeenCalled();+ act(() => vi.advanceTimersByTime(1));+ expect(refresh).toHaveBeenCalledTimes(1);+ act(() => vi.advanceTimersByTime(45_000));+ expect(refresh).toHaveBeenCalledTimes(2);+ setVisibility("hidden");+ act(() => vi.advanceTimersByTime(90_000));+ expect(refresh).toHaveBeenCalledTimes(2);+ setVisibility("visible");+ window.dispatchEvent(new Event("focus"));+ expect(refresh).toHaveBeenCalledTimes(3);+ act(() => root.render(<Probe pending />));+ act(() => vi.advanceTimersByTime(45_000));+ expect(refresh).toHaveBeenCalledTimes(3);+ act(() => root.render(<Probe />));+ act(() => vi.advanceTimersByTime(45_000));+ expect(refresh).toHaveBeenCalledTimes(4);+ act(() => root.render(<Probe enabled={false} />));+ act(() => vi.advanceTimersByTime(90_000));+ window.dispatchEvent(new Event("focus"));+ expect(refresh).toHaveBeenCalledTimes(4);+ act(() => root.render(null));+ act(() => vi.advanceTimersByTime(45_000));+ expect(refresh).toHaveBeenCalledTimes(4);+ });++ it.each(["focus", "visibilitychange"])(+ "keeps an idle view paused after %s until input",+ (event) => {+ vi.setSystemTime(1_000_000);+ function Probe() {+ useLiveRefresh(refresh, { intervalMs: 45_000 });+ return null;+ }+ act(() => root.render(<Probe />));+ act(() => vi.advanceTimersByTime(LIVE_REFRESH_IDLE_AFTER_MS));+ refresh.mockClear();+ act(() => (event === "focus" ? window : document).dispatchEvent(new Event(event)));+ expect(refresh).not.toHaveBeenCalled();+ act(() => vi.advanceTimersByTime(90_000));+ expect(refresh).not.toHaveBeenCalled();+ act(() => document.dispatchEvent(new Event("pointerdown")));+ expect(refresh).toHaveBeenCalledTimes(1);+ act(() => vi.advanceTimersByTime(45_000));+ expect(refresh).toHaveBeenCalledTimes(2);+ },+ );+});diff --git a/apps/web/src/hooks/useLiveRefresh.test.ts b/apps/web/src/hooks/useLiveRefresh.test.tsindex 2be16306c57..69cd828d3a5 100644--- a/apps/web/src/hooks/useLiveRefresh.test.ts+++ b/apps/web/src/hooks/useLiveRefresh.test.ts@@ -1,6 +1,4 @@-import { act, createElement } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";-import { describe, expect, it, vi } from "vite-plus/test";+import { describe, expect, it } from "vite-plus/test";import {LIVE_REFRESH_IDLE_AFTER_MS,@@ -9,105 +7,8 @@ import {shouldLiveRefresh,shouldRefreshOnArrival,shouldRefreshOnInterval,- useLiveRefresh,} from "./useLiveRefresh";-describe("live refresh cadence", () => {- it("polls every 45 seconds, pauses while hidden or busy, respects disabling, and cleans up", () => {- vi.useFakeTimers();- vi.setSystemTime(0);- const document = Object.assign(new EventTarget(), { visibilityState: "visible" });- const window = new EventTarget();- vi.stubGlobal("document", document);- vi.stubGlobal("window", window);- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- const refresh = vi.fn();- let renderer: ReactTestRenderer | undefined;- function Probe({ pending = false, enabled = true }) {- useLiveRefresh(pending ? null : refresh, { intervalMs: 45_000, enabled });- return null;- }- try {- act(() => {- renderer = create(createElement(Probe));- });- act(() => vi.advanceTimersByTime(44_999));- expect(refresh).not.toHaveBeenCalled();- act(() => vi.advanceTimersByTime(1));- expect(refresh).toHaveBeenCalledTimes(1);- act(() => vi.advanceTimersByTime(45_000));- expect(refresh).toHaveBeenCalledTimes(2);- document.visibilityState = "hidden";- document.dispatchEvent(new Event("visibilitychange"));- act(() => vi.advanceTimersByTime(90_000));- expect(refresh).toHaveBeenCalledTimes(2);- document.visibilityState = "visible";- document.dispatchEvent(new Event("visibilitychange"));- window.dispatchEvent(new Event("focus"));- expect(refresh).toHaveBeenCalledTimes(3);- act(() => renderer?.update(createElement(Probe, { pending: true })));- act(() => vi.advanceTimersByTime(45_000));- expect(refresh).toHaveBeenCalledTimes(3);- act(() => renderer?.update(createElement(Probe)));- act(() => vi.advanceTimersByTime(45_000));- expect(refresh).toHaveBeenCalledTimes(4);- act(() => renderer?.update(createElement(Probe, { enabled: false })));- act(() => vi.advanceTimersByTime(90_000));- window.dispatchEvent(new Event("focus"));- expect(refresh).toHaveBeenCalledTimes(4);- act(() => renderer?.unmount());- act(() => vi.advanceTimersByTime(45_000));- expect(refresh).toHaveBeenCalledTimes(4);- } finally {- act(() => renderer?.unmount());- vi.useRealTimers();- vi.unstubAllGlobals();- }- });-- it("waits five minutes between automatic host reads", () => {- expect(LIVE_REFRESH_INTERVAL_MS).toBe(5 * 60_000);- });-- it.each(["focus", "visibilitychange"])(- "keeps an idle view paused after %s until input",- (event) => {- vi.useFakeTimers();- vi.setSystemTime(1_000_000);- const document = Object.assign(new EventTarget(), { visibilityState: "visible" });- const window = new EventTarget();- vi.stubGlobal("document", document);- vi.stubGlobal("window", window);- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- const refresh = vi.fn();- let renderer: ReactTestRenderer | undefined;- function Probe() {- useLiveRefresh(refresh, { intervalMs: 45_000 });- return null;- }- try {- act(() => {- renderer = create(createElement(Probe));- });- act(() => vi.advanceTimersByTime(LIVE_REFRESH_IDLE_AFTER_MS));- refresh.mockClear();- act(() => (event === "focus" ? window : document).dispatchEvent(new Event(event)));- expect(refresh).not.toHaveBeenCalled();- act(() => vi.advanceTimersByTime(90_000));- expect(refresh).not.toHaveBeenCalled();- act(() => document.dispatchEvent(new Event("pointerdown")));- expect(refresh).toHaveBeenCalledTimes(1);- act(() => vi.advanceTimersByTime(45_000));- expect(refresh).toHaveBeenCalledTimes(2);- } finally {- act(() => renderer?.unmount());- vi.useRealTimers();- vi.unstubAllGlobals();- }- },- );-});-describe("shouldLiveRefresh", () => {const at = (now: number, lastRefreshedAt: number, visible = true) =>shouldLiveRefresh({ visible, now, lastRefreshedAt });diff --git a/apps/web/src/hooks/usePullRequestChecksRefresh.browser.test.tsx b/apps/web/src/hooks/usePullRequestChecksRefresh.browser.test.tsxnew file mode 100644index 00000000000..12bee62ca8e--- /dev/null+++ b/apps/web/src/hooks/usePullRequestChecksRefresh.browser.test.tsx@@ -0,0 +1,88 @@+import type { PullRequestCheck } from "@t3tools/contracts";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";++import { usePullRequestChecksRefresh } from "./usePullRequestChecksRefresh";++let root: Root;+let visibility: DocumentVisibilityState;++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(1_000_000);+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ visibility = "visible";+ vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility);+ root = createRoot(document.createElement("div"));+});++afterEach(() => {+ act(() => root.unmount());+ vi.restoreAllMocks();+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++it.each(["pending", "action-required"] as const)(+ "polls quiet PRs each minute, speeds up for %s or missing checks, resumes from idle, and stops for closed PRs",+ (pendingStatus) => {+ const refresh = vi.fn();+ function Probe({+ status = "success",+ enabled = true,+ }: {+ status?: PullRequestCheck["status"] | null;+ enabled?: boolean;+ }) {+ usePullRequestChecksRefresh({+ refresh,+ enabled,+ key: `test-pr-checks:${pendingStatus}`,+ checks: status === null ? [] : [{ name: "CI", status, description: null, url: null }],+ });+ return null;+ }+ const update = (props: Parameters<typeof Probe>[0]) =>+ act(() => root.render(<Probe {...props} />));+ const advance = (ms: number) => act(() => vi.advanceTimersByTime(ms));++ update({});+ advance(59_999);+ expect(refresh).toHaveBeenCalledTimes(0);+ advance(1);+ expect(refresh).toHaveBeenCalledTimes(1);+ update({ status: pendingStatus });+ advance(44_999);+ expect(refresh).toHaveBeenCalledTimes(1);+ advance(1);+ expect(refresh).toHaveBeenCalledTimes(2);+ update({ status: "failure" });+ advance(60_000);+ expect(refresh).toHaveBeenCalledTimes(3);+ update({ status: null });+ for (let tick = 0; tick < 3; tick++) {+ advance(45_000);+ update({ status: null });+ }+ expect(refresh).toHaveBeenCalledTimes(6);+ advance(44_999);+ expect(refresh).toHaveBeenCalledTimes(6);+ advance(1);+ expect(refresh).toHaveBeenCalledTimes(7);+ advance(6 * 60_000);+ const beforeResume = refresh.mock.calls.length;+ act(() => document.dispatchEvent(new Event("pointerdown")));+ expect(refresh).toHaveBeenCalledTimes(beforeResume + 1);+ visibility = "hidden";+ act(() => document.dispatchEvent(new Event("visibilitychange")));+ advance(60_000);+ expect(refresh).toHaveBeenCalledTimes(beforeResume + 1);+ visibility = "visible";+ act(() => document.dispatchEvent(new Event("visibilitychange")));+ expect(refresh).toHaveBeenCalledTimes(beforeResume + 2);+ update({ enabled: false });+ advance(120_000);+ expect(refresh).toHaveBeenCalledTimes(beforeResume + 2);+ },+);diff --git a/apps/web/src/hooks/usePullRequestChecksRefresh.test.ts b/apps/web/src/hooks/usePullRequestChecksRefresh.test.tsdeleted file mode 100644index 749f04d8c62..00000000000--- a/apps/web/src/hooks/usePullRequestChecksRefresh.test.ts+++ /dev/null@@ -1,86 +0,0 @@-import type { PullRequestCheck } from "@t3tools/contracts";-import { act, createElement } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";-import { expect, it, vi } from "vite-plus/test";--import { usePullRequestChecksRefresh } from "./usePullRequestChecksRefresh";--it.each(["pending", "action-required"] as const)(- "polls quiet PRs each minute, speeds up for %s or missing checks, resumes from idle, and stops for closed PRs",- (pendingStatus) => {- vi.useFakeTimers();- vi.setSystemTime(1_000_000);- const document = Object.assign(new EventTarget(), { visibilityState: "visible" });- vi.stubGlobal("document", document);- vi.stubGlobal("window", new EventTarget());- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- const refresh = vi.fn();- let renderer: ReactTestRenderer | undefined;- function Probe({- status = "success",- enabled = true,- busy = false,- }: {- status?: PullRequestCheck["status"] | null;- enabled?: boolean;- busy?: boolean;- }) {- usePullRequestChecksRefresh({- refresh: busy ? null : refresh,- enabled,- key: `test-pr-checks:${pendingStatus}`,- checks: status === null ? [] : [{ name: "CI", status, description: null, url: null }],- });- return null;- }- const update = (props: Parameters<typeof Probe>[0]) => {- act(() => renderer?.update(createElement(Probe, props)));- };- const advance = (ms: number) => act(() => vi.advanceTimersByTime(ms));- try {- act(() => {- renderer = create(createElement(Probe));- });- advance(59_999);- expect(refresh).toHaveBeenCalledTimes(0);- advance(1);- expect(refresh).toHaveBeenCalledTimes(1);- update({ status: pendingStatus });- advance(44_999);- expect(refresh).toHaveBeenCalledTimes(1);- advance(1);- expect(refresh).toHaveBeenCalledTimes(2);- update({ status: "failure" });- advance(60_000);- expect(refresh).toHaveBeenCalledTimes(3);- update({ status: null });- for (let tick = 0; tick < 3; tick++) {- advance(45_000);- update({ status: null });- }- expect(refresh).toHaveBeenCalledTimes(6);- advance(44_999);- expect(refresh).toHaveBeenCalledTimes(6);- advance(1);- expect(refresh).toHaveBeenCalledTimes(7);- advance(6 * 60_000);- const beforeResume = refresh.mock.calls.length;- act(() => document.dispatchEvent(new Event("pointerdown")));- expect(refresh).toHaveBeenCalledTimes(beforeResume + 1);- document.visibilityState = "hidden";- act(() => document.dispatchEvent(new Event("visibilitychange")));- advance(60_000);- expect(refresh).toHaveBeenCalledTimes(beforeResume + 1);- document.visibilityState = "visible";- act(() => document.dispatchEvent(new Event("visibilitychange")));- expect(refresh).toHaveBeenCalledTimes(beforeResume + 2);- update({ enabled: false });- advance(120_000);- expect(refresh).toHaveBeenCalledTimes(beforeResume + 2);- } finally {- act(() => renderer?.unmount());- vi.useRealTimers();- vi.unstubAllGlobals();- }- },-);diff --git a/apps/web/src/hooks/useResizableWidth.browser.test.tsx b/apps/web/src/hooks/useResizableWidth.browser.test.tsxnew file mode 100644index 00000000000..190b7b7c78f--- /dev/null+++ b/apps/web/src/hooks/useResizableWidth.browser.test.tsx@@ -0,0 +1,250 @@+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";++import { RESIZABLE_WIDTH_PROPERTY, useResizableWidth } from "./useResizableWidth";++let root: Root;+let container: HTMLDivElement;+let captured = false;+let frame: FrameRequestCallback | undefined;+const cancelAnimationFrame = vi.fn();+let setItem: ReturnType<typeof vi.spyOn<Storage, "setItem">>;++function Panel({+ edge = "left",+ maxWidth = 800,+ storageKey = "test-panel-width",+}: {+ edge?: "left" | "right";+ maxWidth?: number;+ storageKey?: string;+}) {+ const { width, handlers } = useResizableWidth({+ storageKey,+ defaultWidth: 400,+ minWidth: 200,+ maxWidth,+ edge,+ });+ return (+ <aside data-testid="host">+ <output>{width}</output>+ <div data-testid="handle" {...handlers} />+ </aside>+ );+}++const host = () => container.querySelector<HTMLElement>("[data-testid=host]")!;+const shownWidth = () => Number(container.querySelector("output")!.textContent);+const liveWidth = () => host().style.getPropertyValue(RESIZABLE_WIDTH_PROPERTY);+const bodyStyle = () => document.body.style;++function handle() {+ const element = container.querySelector<HTMLElement>("[data-testid=handle]")!;+ // Synthetic pointers have no active pointer for the browser to capture.+ element.setPointerCapture = () => {+ captured = true;+ };+ element.hasPointerCapture = () => captured;+ element.releasePointerCapture = () => {+ captured = false;+ };+ return element;+}++function pointer(+ type: "pointerdown" | "pointermove" | "pointerup" | "pointercancel" | "lostpointercapture",+ clientX = 100,+) {+ handle().dispatchEvent(+ new PointerEvent(type, { bubbles: true, cancelable: true, button: 0, pointerId: 1, clientX }),+ );+}++async function render(element = <Panel />) {+ await act(() => root.render(element));+}++async function mountFresh(element = <Panel />) {+ root = createRoot(container);+ await render(element);+}++beforeEach(async () => {+ localStorage.clear();+ captured = false;+ frame = undefined;+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {+ frame = callback;+ return 42;+ });+ vi.spyOn(window, "cancelAnimationFrame").mockImplementation(cancelAnimationFrame);+ setItem = vi.spyOn(Storage.prototype, "setItem");+ container = document.createElement("div");+ document.body.append(container);+ await mountFresh();+});++afterEach(async () => {+ await act(() => root.unmount());+ container.remove();+ localStorage.clear();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ cancelAnimationFrame.mockClear();+});++describe("panel resize cleanup", () => {+ it.each(["unmount", "lost capture", "blur", "cancel"])(+ "clears the cursor and pending resize after %s",+ async (reason) => {+ await act(() => {+ pointer("pointerdown");+ pointer("pointermove", 50);+ });+ const resizedHost = host();+ await act(() => frame?.(0));+ expect(liveWidth()).toBe("450px");+ expect(resizedHost.style.getPropertyValue("transition-property")).toBe("none");+ expect(shownWidth()).toBe(400);+ await act(() => pointer("pointermove", 25));+ expect(bodyStyle().cursor).toBe("col-resize");+ expect(bodyStyle().userSelect).toBe("none");+ await act(() => {+ if (reason === "unmount") root.unmount();+ if (reason === "lost capture") pointer("lostpointercapture");+ if (reason === "blur") window.dispatchEvent(new Event("blur"));+ if (reason === "cancel") pointer("pointercancel");+ });+ expect(bodyStyle().cursor).toBe("");+ expect(bodyStyle().userSelect).toBe("");+ expect(captured).toBe(false);+ expect(resizedHost.style.getPropertyValue("transition-property")).toBe("");+ expect(cancelAnimationFrame).toHaveBeenCalledWith(42);+ if (reason === "unmount") {+ expect(setItem).not.toHaveBeenCalled();+ await mountFresh();+ } else {+ expect(shownWidth()).toBe(475);+ expect(setItem).toHaveBeenCalledExactlyOnceWith("test-panel-width", "475");+ }+ },+ );++ it.each(["left", "right"] as const)(+ "uses the release position for a fast %s-edge drag",+ async (edge) => {+ await render(<Panel edge={edge} />);+ await act(() => {+ pointer("pointerdown");+ pointer("pointermove", edge === "left" ? 50 : 150);+ pointer("pointerup", edge === "left" ? 25 : 175);+ });+ expect(shownWidth()).toBe(475);+ expect(setItem).toHaveBeenCalledExactlyOnceWith("test-panel-width", "475");+ expect(cancelAnimationFrame).toHaveBeenCalledWith(42);+ },+ );++ it.each([+ [800, 450],+ [450, 800],+ ])("uses updated bounds during a drag from max %s to %s", async (initialMax, nextMax) => {+ await render(<Panel maxWidth={initialMax} />);+ await act(() => {+ pointer("pointerdown");+ pointer("pointermove", -200);+ });+ await act(() => frame?.(0));+ expect(liveWidth()).toBe(`${Math.min(700, initialMax)}px`);+ await render(<Panel maxWidth={nextMax} />);+ await act(() => pointer("pointermove", -250));+ await act(() => frame?.(0));+ expect(liveWidth()).toBe(`${Math.min(750, nextMax)}px`);+ await act(() => pointer("pointerup", -300));+ expect(shownWidth()).toBe(nextMax);+ expect(setItem).toHaveBeenCalledExactlyOnceWith("test-panel-width", String(nextMax));+ });++ it("handles release before any move event", async () => {+ await act(() => {+ pointer("pointerdown");+ pointer("pointerup", 25);+ });+ expect(shownWidth()).toBe(475);+ expect(setItem).toHaveBeenCalledExactlyOnceWith("test-panel-width", "475");+ });++ it("clamps the release position to the panel bounds", async () => {+ await act(() => {+ pointer("pointerdown");+ pointer("pointerup", -1000);+ });+ expect(shownWidth()).toBe(800);+ expect(setItem).toHaveBeenCalledExactlyOnceWith("test-panel-width", "800");+ });++ it("saves the final width when release is followed by lost capture", async () => {+ await act(() => {+ pointer("pointerdown");+ pointer("pointermove", 50);+ pointer("pointerup", 50);+ pointer("lostpointercapture", 50);+ });+ expect(shownWidth()).toBe(450);+ expect(setItem).toHaveBeenCalledExactlyOnceWith("test-panel-width", "450");+ expect(bodyStyle().cursor).toBe("");+ expect(captured).toBe(false);+ });+});++describe("panel width storage changes", () => {+ it("restores separate thread widths without remounting and retains them after reload", async () => {+ await act(() => {+ pointer("pointerdown");+ pointer("pointermove", 50);+ pointer("pointerup", 50);+ });+ expect(shownWidth()).toBe(450);+ await render(<Panel storageKey="thread-b" />);+ expect(shownWidth()).toBe(400);+ await act(() => {+ pointer("pointerdown");+ pointer("pointermove", -100);+ pointer("pointerup", -100);+ });+ expect(shownWidth()).toBe(600);+ await render(<Panel />);+ expect(shownWidth()).toBe(450);+ await act(() => root.unmount());+ await mountFresh(<Panel storageKey="thread-b" />);+ expect(shownWidth()).toBe(600);+ });++ it("cancels an unfinished drag on a thread switch without saving it to either thread", async () => {+ localStorage.setItem("thread-b", "650");+ setItem.mockClear();+ await act(() => {+ pointer("pointerdown");+ pointer("pointermove", 50);+ });+ await act(() => frame?.(0));+ expect(liveWidth()).toBe("450px");+ await act(() => pointer("pointermove", 25));+ await render(<Panel storageKey="thread-b" />);+ expect(shownWidth()).toBe(650);+ expect(liveWidth()).toBe("650px");+ expect(captured).toBe(false);+ expect(bodyStyle().cursor).toBe("");+ await act(() => {+ frame?.(0);+ pointer("pointerup", 25);+ });+ expect(shownWidth()).toBe(650);+ expect(setItem).not.toHaveBeenCalled();+ await render(<Panel />);+ expect(shownWidth()).toBe(400);+ });+});diff --git a/apps/web/src/hooks/useResizableWidth.test.tsx b/apps/web/src/hooks/useResizableWidth.test.tsxdeleted file mode 100644index 73a7a7cc031..00000000000--- a/apps/web/src/hooks/useResizableWidth.test.tsx+++ /dev/null@@ -1,254 +0,0 @@-import { act, useLayoutEffect, type PointerEvent } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";--import { RESIZABLE_WIDTH_PROPERTY, useResizableWidth } from "./useResizableWidth";--let renderer: ReactTestRenderer;-let result: ReturnType<typeof useResizableWidth>;-let captured = false;-const hostStyle = new Map<string, string>();-const target = {- parentElement: {- style: {- setProperty: (property: string, value: string) => hostStyle.set(property, value),- removeProperty: (property: string) => hostStyle.delete(property),- },- },- setPointerCapture: () => {- captured = true;- },- hasPointerCapture: () => captured,- releasePointerCapture: () => {- captured = false;- },-};-const style = {- cursor: "",- userSelect: "",- removeProperty(property: string) {- if (property === "cursor") this.cursor = "";- if (property === "user-select") this.userSelect = "";- },-};-const savedWidths = new Map<string, string>();-const setItem = vi.fn((key: string, value: string) => savedWidths.set(key, value));-const cancelAnimationFrame = vi.fn();-let events: EventTarget;-let frame: FrameRequestCallback | undefined;--function pointer(clientX = 100) {- return {- button: 0,- pointerId: 1,- clientX,- currentTarget: target,- preventDefault() {},- stopPropagation() {},- } as unknown as PointerEvent<HTMLElement>;-}--function Panel({- edge = "left",- maxWidth = 800,- storageKey = "test-panel-width",-}: {- edge?: "left" | "right";- maxWidth?: number;- storageKey?: string;-}) {- const resize = useResizableWidth({- storageKey,- defaultWidth: 400,- minWidth: 200,- maxWidth,- edge,- });- useLayoutEffect(() => {- result = resize;- });- return null;-}--beforeEach(async () => {- savedWidths.clear();- hostStyle.clear();- captured = false;- frame = undefined;- style.cursor = "";- style.userSelect = "";- events = new EventTarget();- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- vi.stubGlobal("window", {- addEventListener: events.addEventListener.bind(events),- removeEventListener: events.removeEventListener.bind(events),- localStorage: { getItem: (key: string) => savedWidths.get(key) ?? null, setItem },- });- vi.stubGlobal("document", { body: { style } });- vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {- frame = callback;- return 42;- });- vi.stubGlobal("cancelAnimationFrame", cancelAnimationFrame);- await act(() => {- renderer = create(<Panel />);- });-});--afterEach(async () => {- await act(() => renderer.unmount());- vi.unstubAllGlobals();- vi.clearAllMocks();-});--describe("panel resize cleanup", () => {- it.each(["unmount", "lost capture", "blur", "cancel"])(- "clears the cursor and pending resize after %s",- async (reason) => {- await act(() => {- result.handlers.onPointerDown(pointer());- result.handlers.onPointerMove(pointer(50));- });- await act(() => frame?.(0));- expect(hostStyle.get(RESIZABLE_WIDTH_PROPERTY)).toBe("450px");- expect(hostStyle.get("transition-property")).toBe("none");- expect(result.width).toBe(400);- await act(() => result.handlers.onPointerMove(pointer(25)));- expect(style.cursor).toBe("col-resize");- expect(style.userSelect).toBe("none");- await act(() => {- if (reason === "unmount") renderer.unmount();- if (reason === "lost capture") result.handlers.onLostPointerCapture(pointer());- if (reason === "blur") events.dispatchEvent(new Event("blur"));- if (reason === "cancel") result.handlers.onPointerCancel(pointer());- });- expect(style.cursor).toBe("");- expect(style.userSelect).toBe("");- expect(captured).toBe(false);- expect(hostStyle.has("transition-property")).toBe(false);- expect(cancelAnimationFrame).toHaveBeenCalledWith(42);- if (reason === "unmount") {- expect(setItem).not.toHaveBeenCalled();- } else {- expect(result.width).toBe(475);- expect(setItem).toHaveBeenCalledExactlyOnceWith("test-panel-width", "475");- }- },- );-- it.each(["left", "right"] as const)(- "uses the release position for a fast %s-edge drag",- async (edge) => {- await act(() => renderer.update(<Panel edge={edge} />));- await act(() => {- result.handlers.onPointerDown(pointer());- result.handlers.onPointerMove(pointer(edge === "left" ? 50 : 150));- result.handlers.onPointerUp(pointer(edge === "left" ? 25 : 175));- });- expect(result.width).toBe(475);- expect(setItem).toHaveBeenCalledExactlyOnceWith("test-panel-width", "475");- expect(cancelAnimationFrame).toHaveBeenCalledWith(42);- },- );-- it.each([- [800, 450],- [450, 800],- ])("uses updated bounds during a drag from max %s to %s", async (initialMax, nextMax) => {- await act(() => renderer.update(<Panel maxWidth={initialMax} />));- await act(() => {- result.handlers.onPointerDown(pointer());- result.handlers.onPointerMove(pointer(-200));- });- await act(() => frame?.(0));- expect(hostStyle.get(RESIZABLE_WIDTH_PROPERTY)).toBe(`${Math.min(700, initialMax)}px`);- await act(() => renderer.update(<Panel maxWidth={nextMax} />));- await act(() => result.handlers.onPointerMove(pointer(-250)));- await act(() => frame?.(0));- expect(hostStyle.get(RESIZABLE_WIDTH_PROPERTY)).toBe(`${Math.min(750, nextMax)}px`);- await act(() => result.handlers.onPointerUp(pointer(-300)));- expect(result.width).toBe(nextMax);- expect(setItem).toHaveBeenCalledExactlyOnceWith("test-panel-width", String(nextMax));- });-- it("handles release before any move event", async () => {- await act(() => {- result.handlers.onPointerDown(pointer());- result.handlers.onPointerUp(pointer(25));- });- expect(result.width).toBe(475);- expect(setItem).toHaveBeenCalledExactlyOnceWith("test-panel-width", "475");- });-- it("clamps the release position to the panel bounds", async () => {- await act(() => {- result.handlers.onPointerDown(pointer());- result.handlers.onPointerUp(pointer(-1000));- });- expect(result.width).toBe(800);- expect(setItem).toHaveBeenCalledExactlyOnceWith("test-panel-width", "800");- });-- it("saves the final width when release is followed by lost capture", async () => {- await act(() => {- result.handlers.onPointerDown(pointer());- result.handlers.onPointerMove(pointer(50));- result.handlers.onPointerUp(pointer(50));- result.handlers.onLostPointerCapture(pointer(50));- });- expect(result.width).toBe(450);- expect(setItem).toHaveBeenCalledExactlyOnceWith("test-panel-width", "450");- expect(style.cursor).toBe("");- expect(captured).toBe(false);- });-});--describe("panel width storage changes", () => {- it("restores separate thread widths without remounting and retains them after reload", async () => {- await act(() => {- result.handlers.onPointerDown(pointer());- result.handlers.onPointerMove(pointer(50));- result.handlers.onPointerUp(pointer(50));- });- expect(result.width).toBe(450);- await act(() => renderer.update(<Panel storageKey="thread-b" />));- expect(result.width).toBe(400);- await act(() => {- result.handlers.onPointerDown(pointer());- result.handlers.onPointerMove(pointer(-100));- result.handlers.onPointerUp(pointer(-100));- });- expect(result.width).toBe(600);- await act(() => renderer.update(<Panel />));- expect(result.width).toBe(450);- await act(() => renderer.unmount());- await act(() => {- renderer = create(<Panel storageKey="thread-b" />);- });- expect(result.width).toBe(600);- });-- it("cancels an unfinished drag on a thread switch without saving it to either thread", async () => {- savedWidths.set("thread-b", "650");- await act(() => {- result.handlers.onPointerDown(pointer());- result.handlers.onPointerMove(pointer(50));- });- await act(() => frame?.(0));- expect(hostStyle.get(RESIZABLE_WIDTH_PROPERTY)).toBe("450px");- await act(() => result.handlers.onPointerMove(pointer(25)));- await act(() => renderer.update(<Panel storageKey="thread-b" />));- expect(result.width).toBe(650);- expect(hostStyle.get(RESIZABLE_WIDTH_PROPERTY)).toBe("650px");- expect(captured).toBe(false);- expect(style.cursor).toBe("");- await act(() => {- frame?.(0);- result.handlers.onPointerUp(pointer(25));- });- expect(result.width).toBe(650);- expect(setItem).not.toHaveBeenCalled();- await act(() => renderer.update(<Panel />));- expect(result.width).toBe(400);- });-});diff --git a/apps/web/src/hooks/useSettings.favorites.test.tsx b/apps/web/src/hooks/useSettings.favorites.browser.test.tsxsimilarity index 78%rename from apps/web/src/hooks/useSettings.favorites.test.tsxrename to apps/web/src/hooks/useSettings.favorites.browser.test.tsxindex 16b708554f2..90c5cac5fca 100644--- a/apps/web/src/hooks/useSettings.favorites.test.tsx+++ b/apps/web/src/hooks/useSettings.favorites.browser.test.tsx@@ -10,24 +10,27 @@ import * as Cause from "effect/Cause";import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";import { act } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";+import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";const state = vi.hoisted(() => ({- settings: new Map<EnvironmentId, Atom.Writable<ServerSettings | null>>(),+ settings: new Map<string, unknown>(),persist: vi.fn(),}));-vi.mock("~/state/server", () => ({- serverEnvironment: {- settingsValueAtom: (id: EnvironmentId) => state.settings.get(id)!,- updateSettings: Symbol("updateSettings"),- },- primaryServerSettingsAtom: undefined,-}));-vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => state.persist }));-vi.mock("~/localApi", () => ({- ensureLocalApi: () => ({ persistence: { getClientSettings: async () => null } }),+vi.mock(import("~/state/server"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ serverEnvironment: {+ ...actual.serverEnvironment,+ settingsValueAtom: ((id: EnvironmentId) => state.settings.get(id)) as never,+ },+ };+});+vi.mock(import("~/state/use-atom-command"), async (original) => ({+ ...(await original()),+ useAtomCommand: (() => state.persist) as never,}));import { useToggleEnvironmentModelFavorite } from "./useSettings";@@ -42,35 +45,40 @@ const initialSettings = {providerModelPreferences: {},} satisfies ServerSettings;let registry: AtomRegistry.AtomRegistry;-let renderer: ReactTestRenderer | undefined;+let root: Root;+let container: HTMLDivElement;let durable: Map<EnvironmentId, ServerSettings>;+let toggles: Array<() => Promise<void>>;+let pendingClick: Promise<void> | undefined;let writes: Array<{environmentId: EnvironmentId;patch: ServerSettingsPatch;finish: (success?: boolean) => void;}>;+const settingsAtom = (id: EnvironmentId) =>+ state.settings.get(id) as Atom.Writable<ServerSettings | null>;+function FavoriteEditor({ environmentId }: { environmentId: EnvironmentId }) {const toggle = useToggleEnvironmentModelFavorite(environmentId);- return <button onClick={() => toggle(provider, model)}>Toggle favorite</button>;+ const onClick = () => toggle(provider, model);+ toggles.push(onClick);+ return <button onClick={() => void (pendingClick = onClick())}>Toggle favorite</button>;}-function editor(environmentId: EnvironmentId) {- return (- <RegistryContext.Provider value={registry}>- <FavoriteEditor environmentId={environmentId} />- </RegistryContext.Provider>+function mount(environmentId = primaryId) {+ return act(() =>+ root.render(+ <RegistryContext.Provider value={registry}>+ <FavoriteEditor environmentId={environmentId} />+ </RegistryContext.Provider>,+ ),);}-async function mount(environmentId = primaryId) {- await act(() => {- renderer = create(editor(environmentId));- });-}-function click(): Promise<void> {- return renderer!.root.findByType("button").props.onClick();+ container.querySelector("button")!.click();+ return pendingClick!;}beforeEach(() => {@@ -78,6 +86,7 @@ beforeEach(() => {registry = AtomRegistry.make();state.settings.clear();durable = new Map();+ toggles = [];writes = [];for (const id of [primaryId, remoteId]) {state.settings.set(id, Atom.make<ServerSettings | null>(initialSettings));@@ -107,11 +116,14 @@ beforeEach(() => {});}),);+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);});afterEach(async () => {- await act(() => renderer?.unmount());- renderer = undefined;+ await act(() => root.unmount());+ container.remove();registry.dispose();vi.unstubAllGlobals();});@@ -122,7 +134,7 @@ describe("environment favorite toggles", () => {async (initiallyFavorited) => {const favorites = initiallyFavorited ? [{ provider, model }] : [];const settings = { ...initialSettings, favorites };- registry.set(state.settings.get(primaryId)!, settings);+ registry.set(settingsAtom(primaryId), settings);durable.set(primaryId, settings);await mount();const first = click();@@ -180,7 +192,7 @@ describe("environment favorite toggles", () => {await act(async () => {});writes[0]!.finish();await first;- expect(registry.get(state.settings.get(primaryId)!)!.favorites).toEqual([]);+ expect(registry.get(settingsAtom(primaryId))!.favorites).toEqual([]);const second = click();await act(async () => {});writes[1]!.finish();@@ -196,7 +208,7 @@ describe("environment favorite toggles", () => {await first;const remoteSettings = { ...initialSettings, favorites: [] };durable.set(primaryId, remoteSettings);- await act(() => registry.set(state.settings.get(primaryId)!, remoteSettings));+ await act(() => registry.set(settingsAtom(primaryId), remoteSettings));const second = click();await act(async () => {});writes[1]!.finish();@@ -224,7 +236,7 @@ describe("environment favorite toggles", () => {it("does not reuse another environment's pending intent for the same model", async () => {await mount();const primary = click();- await act(() => renderer!.update(editor(remoteId)));+ await mount(remoteId);const remote = click();await act(async () => {});writes[0]!.finish();@@ -237,10 +249,10 @@ describe("environment favorite toggles", () => {it("reads the latest server state even when the click callback predates its echo", async () => {await mount();- const previousClick = renderer!.root.findByType("button").props.onClick as () => Promise<void>;+ const previousClick = toggles.at(-1)!;const updated = { ...initialSettings, favorites: [{ provider, model }] };durable.set(primaryId, updated);- await act(() => registry.set(state.settings.get(primaryId)!, updated));+ await act(() => registry.set(settingsAtom(primaryId), updated));const clicked = previousClick();await act(async () => {});writes[0]!.finish();diff --git a/apps/web/src/hooks/useSettings.sync.test.tsx b/apps/web/src/hooks/useSettings.sync.browser.test.tsxsimilarity index 80%rename from apps/web/src/hooks/useSettings.sync.test.tsxrename to apps/web/src/hooks/useSettings.sync.browser.test.tsxindex 129c5f5469b..c6c9b2f2ab6 100644--- a/apps/web/src/hooks/useSettings.sync.test.tsx+++ b/apps/web/src/hooks/useSettings.sync.browser.test.tsx@@ -8,14 +8,13 @@ import {type ServerSettingsPatch,} from "@t3tools/contracts";import * as Cause from "effect/Cause";-import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";+import { AsyncResult, Atom } from "effect/reactivity";import { act } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";+import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;const state = vi.hoisted(() => ({- registry: null as AtomRegistry.AtomRegistry | null,sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),environments: [] as Array<{environmentId: EnvironmentId;@@ -30,31 +29,29 @@ const state = vi.hoisted(() => ({toast: vi.fn(),}));-vi.mock("~/connection/runtime", () => ({ connectionAtomRuntime: undefined }));-vi.mock("@t3tools/client-runtime/state/session", () => ({- createEnvironmentSessionAtoms: () => ({+vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => ({+ ...(await original()),+ createEnvironmentSessionAtoms: (() => ({sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,- }),+ })) as never,}));-vi.mock("~/rpc/atomRegistry", () => ({- get appAtomRegistry() {- return state.registry;- },-}));-vi.mock("~/state/environments", () => ({- useEnvironments: () => ({ environments: state.environments }),- usePrimaryEnvironment: () =>- state.environments.find((environment) => environment.environmentId === primaryId) ?? null,+vi.mock(import("~/state/environments"), async (original) => ({+ ...(await original()),+ useEnvironments: (() => ({ environments: state.environments })) as never,+ usePrimaryEnvironment: (() =>+ state.environments.find((environment) => environment.environmentId === primaryId) ??+ null) as never,}));-vi.mock("~/state/server", () => ({- serverEnvironment: { updateSettings: Symbol("updateSettings") },- primaryServerSettingsAtom: undefined,+vi.mock(import("~/state/use-atom-command"), async (original) => ({+ ...(await original()),+ useAtomCommand: (() => state.persist) as never,}));-vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => state.persist }));-vi.mock("~/components/ui/toast", () => ({ toastManager: { add: state.toast } }));-vi.mock("~/themePalette", () => ({}));-vi.mock("./useTheme", () => ({}));+vi.mock(import("~/components/ui/toast"), async (original) => {+ const actual = await original();+ return { ...actual, toastManager: { ...actual.toastManager, add: state.toast } };+});+import { appAtomRegistry } from "~/rpc/atomRegistry";import { useUpdatePrimarySettings } from "./useSettings";const primaryId = EnvironmentId.make("primary");@@ -70,30 +67,34 @@ const session = (scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionStatesessionCookieName: "t3_session",},});-let renderer: ReactTestRenderer | undefined;+let root: Root;+let container: HTMLDivElement;+let handlers: Array<() => void> = [];function SettingsEditor() {const updateSettings = useUpdatePrimarySettings();- return <button onClick={() => updateSettings(patch)}>Save shared setting</button>;+ const save = () => void updateSettings(patch);+ handlers.push(save);+ return <button onClick={save}>Save shared setting</button>;}function saveSharedSettings() {- renderer!.root.findByType("button").props.onClick();+ container.querySelector("button")!.click();}async function mountEditor() {- await act(() => {- renderer = create(- <RegistryContext.Provider value={state.registry!}>+ await act(() =>+ root.render(+ <RegistryContext.Provider value={appAtomRegistry}><SettingsEditor /></RegistryContext.Provider>,- );- });+ ),+ );}beforeEach(() => {vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- state.registry = AtomRegistry.make();+ handlers = [];state.sessions.clear();state.sessions.set(primaryId,@@ -112,12 +113,14 @@ beforeEach(() => {state.persist.mockReset();state.persist.mockResolvedValue(AsyncResult.success(DEFAULT_SERVER_SETTINGS));state.toast.mockReset();+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);});afterEach(async () => {- await act(() => renderer?.unmount());- renderer = undefined;- state.registry?.dispose();+ await act(() => root.unmount());+ container.remove();vi.unstubAllGlobals();});@@ -143,7 +146,7 @@ describe("shared settings writes", () => {});it("keeps a single-target failure specific to that environment", async () => {- state.registry!.set(state.sessions.get(remoteId)!, AsyncResult.success(session([])));+ appAtomRegistry.set(state.sessions.get(remoteId)!, AsyncResult.success(session([])));state.persist.mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Permission denied"))),);@@ -178,7 +181,7 @@ describe("shared settings writes", () => {[{ environmentId: primaryId, input: { patch } }],[{ environmentId: remoteId, input: { patch } }],]);- expect(state.registry!.get(state.sessions.get(remoteId)!)).toMatchObject({ _tag: "Initial" });+ expect(appAtomRegistry.get(state.sessions.get(remoteId)!)).toMatchObject({ _tag: "Initial" });});it.each([@@ -189,7 +192,7 @@ describe("shared settings writes", () => {() => AsyncResult.failure<AuthSessionState, Error>(Cause.fail(new Error("session rejected"))),],] as const)("skips a remote whose grant is %s", async (_label, result) => {- state.registry!.set(state.sessions.get(remoteId)!, result());+ appAtomRegistry.set(state.sessions.get(remoteId)!, result());await mountEditor();saveSharedSettings();@@ -224,9 +227,9 @@ describe("shared settings writes", () => {);}await mountEditor();- const previousUpdate = renderer!.root.findByType("button").props.onClick as () => void;+ const previousUpdate = handlers.at(-1)!;await act(() => {- state.registry!.set(state.sessions.get(remoteId)!, AsyncResult.success(session([])));+ appAtomRegistry.set(state.sessions.get(remoteId)!, AsyncResult.success(session([])));});previousUpdate();diff --git a/apps/web/src/hooks/useStableCallback.test.tsx b/apps/web/src/hooks/useStableCallback.browser.test.tsxsimilarity index 62%rename from apps/web/src/hooks/useStableCallback.test.tsxrename to apps/web/src/hooks/useStableCallback.browser.test.tsxindex ddd7fde3520..24b48a12e24 100644--- a/apps/web/src/hooks/useStableCallback.test.tsx+++ b/apps/web/src/hooks/useStableCallback.browser.test.tsx@@ -1,10 +1,10 @@import { act } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";+import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";import { useStableCallback } from "./useStableCallback";-let renderer: ReactTestRenderer | null = null;+let root: Root;let handlers: Array<() => string> = [];function Probe({ label }: { label: string }) {@@ -12,28 +12,21 @@ function Probe({ label }: { label: string }) {return null;}-async function render(label: string) {- await act(() => {- if (renderer) renderer.update(<Probe label={label} />);- else renderer = create(<Probe label={label} />);- });-}-beforeEach(() => {handlers = [];vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ root = createRoot(document.createElement("div"));});afterEach(async () => {- await act(() => renderer?.unmount());- renderer = null;+ await act(() => root.unmount());vi.unstubAllGlobals();});describe("useStableCallback", () => {it("keeps one identity and calls the latest committed function", async () => {- await render("first");- await render("second");+ await act(() => root.render(<Probe label="first" />));+ await act(() => root.render(<Probe label="second" />));expect(new Set(handlers).size).toBe(1);expect(handlers[0]!()).toBe("second");diff --git a/apps/web/src/panelAnimations.test.tsx b/apps/web/src/panelAnimations.browser.test.tsxsimilarity index 66%rename from apps/web/src/panelAnimations.test.tsxrename to apps/web/src/panelAnimations.browser.test.tsxindex 2475425086f..a59f78b2a57 100644--- a/apps/web/src/panelAnimations.test.tsx+++ b/apps/web/src/panelAnimations.browser.test.tsx@@ -1,10 +1,10 @@import { act, useLayoutEffect } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";+import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";import { usePanelNavigationSuppression } from "./panelAnimations";-let renderer: ReactTestRenderer | null = null;+let root: Root;let pendingFrames: FrameRequestCallback[] = [];let observed: boolean[] = [];@@ -20,17 +20,18 @@ beforeEach(() => {pendingFrames = [];observed = [];vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- vi.stubGlobal("window", {- requestAnimationFrame: vi.fn((callback: FrameRequestCallback) => {- pendingFrames.push(callback);- return pendingFrames.length;- }),- cancelAnimationFrame: vi.fn(),+ // Frames are stepped by hand so each assertion lands between two paints.+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {+ pendingFrames.push(callback);+ return pendingFrames.length;});+ vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => undefined);+ root = createRoot(document.createElement("div"));});afterEach(async () => {- await act(() => renderer?.unmount());+ await act(() => root.unmount());+ vi.restoreAllMocks();vi.unstubAllGlobals();});@@ -41,9 +42,7 @@ async function paintPendingFrame() {describe("usePanelNavigationSuppression", () => {it("suppresses initial and navigated panel state until each route has painted", async () => {- await act(() => {- renderer = create(<SuppressionProbe navigationKey="/thread/one" />);- });+ await act(() => root.render(<SuppressionProbe navigationKey="/thread/one" />));expect(observed.at(-1)).toBe(true);await paintPendingFrame();@@ -51,9 +50,7 @@ describe("usePanelNavigationSuppression", () => {await paintPendingFrame();expect(observed.at(-1)).toBe(false);- await act(() => {- renderer?.update(<SuppressionProbe navigationKey="/thread/two" />);- });+ await act(() => root.render(<SuppressionProbe navigationKey="/thread/two" />));expect(observed.at(-1)).toBe(true);await paintPendingFrame();diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.tsindex 0e5929c1b91..7c0b13ef767 100644--- a/apps/web/src/routeTree.gen.ts+++ b/apps/web/src/routeTree.gen.ts@@ -4,6 +4,10 @@// noinspection JSUnusedGlobalSymbols+// This file was automatically generated by TanStack Router.+// You should NOT make any changes in this file as it will be overwritten.+// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.+import { Route as rootRouteImport } from './routes/__root'import { Route as WelcomeRouteImport } from './routes/welcome'import { Route as UsageRouteImport } from './routes/usage'diff --git a/apps/web/src/state/queries.threadSearch.test.tsx b/apps/web/src/state/queries.threadSearch.browser.test.tsxsimilarity index 85%rename from apps/web/src/state/queries.threadSearch.test.tsxrename to apps/web/src/state/queries.threadSearch.browser.test.tsxindex 82ee2acd544..8d3f299e074 100644--- a/apps/web/src/state/queries.threadSearch.test.tsx+++ b/apps/web/src/state/queries.threadSearch.browser.test.tsx@@ -1,6 +1,6 @@import { EnvironmentId } from "@t3tools/contracts";import { act } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";+import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";import { useThreadSearch } from "./queries";@@ -24,14 +24,14 @@ function Probe(props: { query: string; onResult: (result: ThreadSearch) => void}describe("useThreadSearch", () => {- let renderer: ReactTestRenderer | null = null;+ let root: Root;beforeEach(() => {vi.useFakeTimers();- vi.stubGlobal("window", globalThis);+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ root = createRoot(document.createElement("div"));});afterEach(() => {- act(() => renderer?.unmount());- renderer = null;+ act(() => root.unmount());vi.unstubAllGlobals();vi.useRealTimers();});@@ -40,10 +40,7 @@ describe("useThreadSearch", () => {const results: ThreadSearch[] = [];const render = (query: string) => {const element = <Probe query={query} onResult={(result) => results.push(result)} />;- act(() => {- if (renderer) renderer.update(element);- else renderer = create(element);- });+ act(() => root.render(element));return results.at(-1)!;};diff --git a/apps/web/src/state/terminalSessionAvailability.test.ts b/apps/web/src/state/terminalSessionAvailability.browser.test.tsxsimilarity index 69%rename from apps/web/src/state/terminalSessionAvailability.test.tsrename to apps/web/src/state/terminalSessionAvailability.browser.test.tsxindex 1e054680f3c..cbb60e849fc 100644--- a/apps/web/src/state/terminalSessionAvailability.test.ts+++ b/apps/web/src/state/terminalSessionAvailability.browser.test.tsx@@ -1,5 +1,5 @@import { EnvironmentId, ThreadId, type TerminalSummary } from "@t3tools/contracts";-import { act, createElement, useEffect } from "react";+import { act, useEffect } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";@@ -11,11 +11,16 @@ const state = vi.hoisted(() => ({error: null as string | null,}));-vi.mock("./session", () => ({ useEnvironmentScope: () => state.canRead }));-vi.mock("./terminal", () => ({ terminalEnvironment: { metadata: () => ({}) } }));-vi.mock("./query", () => ({- useEnvironmentQuery: (atom: unknown) =>- atom === null ? { data: null, error: null } : { data: state.data, error: state.error },+vi.mock(import("./session"), async (original) => ({+ ...(await original()),+ useEnvironmentScope: () => state.canRead,+}));+vi.mock(import("./query"), async (original) => ({+ ...(await original()),+ useEnvironmentQuery: ((atom: unknown) =>+ atom === null+ ? { data: null, error: null }+ : { data: state.data, error: state.error }) as never,}));let root: Root;@@ -47,26 +52,15 @@ function Probe() {}function render() {- return act(() => root.render(createElement(Probe)));+ return act(() => root.render(<Probe />));}beforeEach(() => {state.canRead = true;state.data = null;state.error = null;- const document = { nodeType: 9, addEventListener() {}, removeEventListener() {} };- const container = {- nodeType: 1,- tagName: "DIV",- namespaceURI: "http://www.w3.org/1999/xhtml",- ownerDocument: document,- addEventListener() {},- removeEventListener() {},- };- vi.stubGlobal("document", document);- vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- root = createRoot(container as unknown as HTMLElement);+ root = createRoot(document.createElement("div"));});afterEach(async () => {diff --git a/apps/web/src/state/usage.test.tsx b/apps/web/src/state/usage.browser.test.tsxsimilarity index 85%rename from apps/web/src/state/usage.test.tsxrename to apps/web/src/state/usage.browser.test.tsxindex 6612ad103c2..78e0ddd075a 100644--- a/apps/web/src/state/usage.test.tsx+++ b/apps/web/src/state/usage.browser.test.tsx@@ -5,7 +5,7 @@ import {type UsageProviderKind,} from "@t3tools/contracts";import { act, useLayoutEffect } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";+import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";import { useUsage, type EnvironmentUsageStatus, type UsageView } from "./usage";@@ -85,7 +85,7 @@ function environment(};}-let renderer: ReactTestRenderer | undefined;+let root: Root;let latest: UsageView;function Probe({@@ -105,21 +105,20 @@ function Probe({}async function select(...ids: string[]) {- await act(() => {- renderer?.update(<Probe selected={new Set(ids.map((id) => EnvironmentId.make(id)))} />);- });+ await act(() =>+ root.render(<Probe selected={new Set(ids.map((id) => EnvironmentId.make(id)))} />),+ );}beforeEach(async () => {vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);testState.environments = [environment("a", 10), environment("b", 20), environment("slow", null)];- await act(() => {- renderer = create(<Probe selected={null} />);- });+ root = createRoot(document.createElement("div"));+ await act(() => root.render(<Probe selected={null} />));});afterEach(async () => {- await act(() => renderer?.unmount());+ await act(() => root.unmount());vi.unstubAllGlobals();});@@ -130,7 +129,7 @@ describe("usage environment selection", () => {expect(latest.isPartial).toBe(true);testState.environments = [...testState.environments.slice(0, 2), environment("slow", 40)];- await act(() => renderer?.update(<Probe selected={null} />));+ await act(() => root.render(<Probe selected={null} />));expect(latest.merged.costUsd).toBe(70);expect(latest.isPartial).toBe(false);});@@ -143,7 +142,7 @@ describe("usage environment selection", () => {expect(latest.isPartial).toBe(false);expect(latest.environments).toHaveLength(3);- await act(() => renderer?.update(<Probe selected={null} />));+ await act(() => root.render(<Probe selected={null} />));expect(latest.merged.costUsd).toBe(30);expect(latest.isPartial).toBe(true);});@@ -166,7 +165,7 @@ describe("usage environment selection", () => {it("deduplicates within the selection so an excluded owner cannot hide usage", async () => {testState.environments = [environment("a", 10, "shared"), environment("b", 20, "shared")];- await act(() => renderer?.update(<Probe selected={null} />));+ await act(() => root.render(<Probe selected={null} />));expect(latest.merged.costUsd).toBe(10);await select("b");@@ -187,30 +186,30 @@ describe("usage environment selection", () => {it("shows the last answered usage until the next window answers, for the same selection", async () => {const selected = new Set([EnvironmentId.make("a")]);- await act(() => renderer?.update(<Probe selected={selected} />));+ await act(() => root.render(<Probe selected={selected} />));expect(latest.shown?.merged.costUsd).toBe(10);const nextWindow = { ...input, sinceDay: UsageDay.make("2026-08-28") };testState.environments = [environment("a", null)];- await act(() => renderer?.update(<Probe selected={selected} window={nextWindow} />));+ await act(() => root.render(<Probe selected={selected} window={nextWindow} />));expect(latest.isPending).toBe(true);expect(latest.shown?.window).toBe(input);expect(latest.shown?.merged.costUsd).toBe(10);testState.environments = [{ ...environment("a", null), isPending: false, error: "Offline" }];- await act(() => renderer?.update(<Probe selected={selected} window={nextWindow} />));+ await act(() => root.render(<Probe selected={selected} window={nextWindow} />));expect(latest.isPending).toBe(false);expect(latest.shown?.window).toBe(input);expect(latest.shown?.merged.costUsd).toBe(10);testState.environments = [environment("a", 30)];- await act(() => renderer?.update(<Probe selected={selected} window={nextWindow} />));+ await act(() => root.render(<Probe selected={selected} window={nextWindow} />));expect(latest.shown?.window).toBe(nextWindow);expect(latest.shown?.merged.costUsd).toBe(30);testState.environments = [environment("a", null)];await act(() =>- renderer?.update(<Probe selected={selected} hidden={new Set(["claude"])} window={input} />),+ root.render(<Probe selected={selected} hidden={new Set(["claude"])} window={input} />),);expect(latest.shown).toBeNull();@@ -223,12 +222,12 @@ describe("usage environment selection", () => {describe("usage provider filter", () => {it("drops hidden providers from totals and sessions, then restores them", async () => {testState.environments = [environment("a", 10), environment("c", 5, "c", "claude")];- await act(() => renderer?.update(<Probe selected={null} hidden={new Set(["codex"])} />));+ await act(() => root.render(<Probe selected={null} hidden={new Set(["codex"])} />));expect(latest.merged.costUsd).toBe(5);expect(latest.merged.sessions).toBe(1);expect(latest.merged.providers.map((entry) => entry.provider)).toEqual(["claude"]);- await act(() => renderer?.update(<Probe selected={null} />));+ await act(() => root.render(<Probe selected={null} />));expect(latest.merged.costUsd).toBe(15);expect(latest.merged.sessions).toBe(2);});