Skip to content
TypeScript

test(web): misc-a tests run in a real browser (#20868)

Julius Marmingeecd95d5eb5c0
diff --git a/apps/web/src/browser/HostedBrowserWebview.test.tsx b/apps/web/src/browser/HostedBrowserWebview.browser.test.tsx
similarity index 72%
rename from apps/web/src/browser/HostedBrowserWebview.test.tsx
rename to apps/web/src/browser/HostedBrowserWebview.browser.test.tsx
index aa582251cb0..b534fae0215 100644
--- a/apps/web/src/browser/HostedBrowserWebview.test.tsx
+++ b/apps/web/src/browser/HostedBrowserWebview.browser.test.tsx
@@ -7,7 +7,7 @@ import {
type DesktopPreviewBridge,
} 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";
const mocks = vi.hoisted(() => ({
@@ -20,28 +20,32 @@ const mocks = vi.hoisted(() => ({
activeRecordings: new Set<string>(),
}));
-vi.mock("~/localApi", () => ({
- ensureLocalApi: () => ({ persistence: mocks }),
-}));
+vi.mock(import("~/localApi"), async (original) => {
+ const actual = await original();
+ return {
+ ...actual,
+ ensureLocalApi: () => ({ ...actual.ensureLocalApi(), persistence: mocks as never }),
+ };
+});
+
+vi.mock(import("./desktopTabLifetime"), { spy: true });
-vi.mock("~/components/preview/previewBridge", () => ({
+// The Electron desktop bridge; a browser has none.
+vi.mock(import("~/components/preview/previewBridge"), async (original) => ({
+ ...(await original()),
previewBridge: {
createTab: mocks.createTab,
closeTab: mocks.closeTab,
registerWebview: mocks.registerWebview,
getPreviewConfig: mocks.getPreviewConfig,
- },
+ } as unknown as DesktopPreviewBridge,
}));
-vi.mock("~/components/preview/usePreviewBridge", () => ({
+vi.mock(import("~/components/preview/usePreviewBridge"), async (original) => ({
+ ...(await original()),
usePreviewBridge: () => undefined,
}));
-vi.mock("./browserRecording", () => ({
- useActiveBrowserRecordingTabIds: () => mocks.activeRecordings,
- stopBrowserRecording: async () => null,
-}));
-
import {
__resetClientSettingsPersistenceForTests,
ensureClientSettingsHydrated,
@@ -50,7 +54,8 @@ import { useBrowserSurfaceStore } from "./browserSurfaceStore";
import * as desktopTabLifetime from "./desktopTabLifetime";
import { HostedBrowserWebview } from "./HostedBrowserWebview";
-let renderer: ReactTestRenderer | undefined;
+let root: Root | undefined;
+let container: HTMLDivElement;
function deferred<A>() {
let resolve!: (value: A) => void;
@@ -76,20 +81,16 @@ beforeEach(() => {
preloadUrl: null,
});
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- vi.stubGlobal("window", globalThis);
- vi.stubGlobal("navigator", { platform: "Linux" });
- vi.stubGlobal(
- "requestAnimationFrame",
- vi.fn(() => 0),
- );
- vi.stubGlobal("cancelAnimationFrame", vi.fn());
vi.spyOn(console, "error").mockImplementation(() => undefined);
+ container = document.createElement("div");
+ document.body.append(container);
});
afterEach(async () => {
vi.useFakeTimers();
- await act(() => renderer?.unmount());
- renderer = undefined;
+ await act(async () => root?.unmount());
+ root = undefined;
+ container.remove();
await vi.advanceTimersByTimeAsync(0);
vi.useRealTimers();
__resetClientSettingsPersistenceForTests();
@@ -107,10 +108,21 @@ describe("HostedBrowserWebview settings hydration", () => {
.mockReturnValueOnce(firstRead.promise)
.mockReturnValueOnce(retryRead.promise);
mocks.createTab.mockReturnValueOnce(tabCreation.promise);
- const acquire = vi.spyOn(desktopTabLifetime, "acquireDesktopTab");
- const createGuest = vi.fn((_attributes: unknown) =>
- Object.assign(new EventTarget(), { getWebContentsId: () => 41 }),
- );
+ const acquire = vi.mocked(desktopTabLifetime.acquireDesktopTab);
+ // Chromium treats <webview> as an unknown element; give it the one Electron method the
+ // host calls once the guest attaches.
+ const createElement = document.createElement.bind(document);
+ const createGuest = vi.spyOn(document, "createElement").mockImplementation(((
+ tagName: string,
+ options?: ElementCreationOptions,
+ ) => {
+ const element = createElement(tagName, options);
+ return tagName === "webview"
+ ? Object.assign(element, { getWebContentsId: () => 41 })
+ : element;
+ }) as typeof document.createElement);
+ const guests = () => createGuest.mock.calls.filter(([tagName]) => tagName === "webview");
+ const guest = () => container.querySelector("webview");
const threadRef = {
environmentId: EnvironmentId.make("host-settings-retry"),
threadId: ThreadId.make("thread-settings-retry"),
@@ -118,8 +130,9 @@ describe("HostedBrowserWebview settings hydration", () => {
const runtimeTabId = "retained-background-tab";
useBrowserSurfaceStore.getState().acquireActivity(runtimeTabId);
- await act(() => {
- renderer = create(
+ root = createRoot(container);
+ await act(async () =>
+ root!.render(
<HostedBrowserWebview
threadRef={threadRef}
tabId="server-tab"
@@ -130,18 +143,12 @@ describe("HostedBrowserWebview settings hydration", () => {
profileId="work"
zoomFactor={1.25}
/>,
- {
- createNodeMock: (element) =>
- element.type === "webview"
- ? createGuest(element.props)
- : { scrollLeft: 0, scrollTop: 0, scrollTo: () => undefined },
- },
- );
- });
+ ),
+ );
expect(mocks.getClientSettings).toHaveBeenCalledOnce();
expect(acquire).not.toHaveBeenCalled();
- expect(createGuest).not.toHaveBeenCalled();
+ expect(guest()).toBeNull();
expect(mocks.createTab).not.toHaveBeenCalled();
const failure = new Error("Saved settings are unavailable");
@@ -151,7 +158,7 @@ describe("HostedBrowserWebview settings hydration", () => {
await expect(hydration).rejects.toBe(failure);
});
expect(acquire).not.toHaveBeenCalled();
- expect(createGuest).not.toHaveBeenCalled();
+ expect(guest()).toBeNull();
expect(mocks.createTab).not.toHaveBeenCalled();
let retry!: Promise<void>;
@@ -160,7 +167,7 @@ describe("HostedBrowserWebview settings hydration", () => {
});
expect(mocks.getClientSettings).toHaveBeenCalledTimes(2);
expect(acquire).not.toHaveBeenCalled();
- expect(createGuest).not.toHaveBeenCalled();
+ expect(guest()).toBeNull();
expect(mocks.createTab).not.toHaveBeenCalled();
await act(async () => {
@@ -176,13 +183,9 @@ describe("HostedBrowserWebview settings hydration", () => {
expect(acquire).toHaveBeenCalledExactlyOnceWith(runtimeTabId, undefined);
expect(mocks.getPreviewConfig).toHaveBeenCalledExactlyOnceWith(threadRef.environmentId, "work");
- expect(createGuest).toHaveBeenCalledOnce();
- expect(createGuest).toHaveBeenCalledWith(
- expect.objectContaining({
- partition: "persist:t3-preview-work",
- src: "https://example.com",
- }),
- );
+ expect(guests()).toHaveLength(1);
+ expect(guest()?.getAttribute("partition")).toBe("persist:t3-preview-work");
+ expect(guest()?.getAttribute("src")).toBe("https://example.com");
expect(mocks.createTab).toHaveBeenCalledExactlyOnceWith(runtimeTabId, {
zoomFactor: 1.25,
colorScheme: "dark",
diff --git a/apps/web/src/cloud/useCloudLinkController.test.tsx b/apps/web/src/cloud/useCloudLinkController.browser.test.tsx
similarity index 81%
rename from apps/web/src/cloud/useCloudLinkController.test.tsx
rename to apps/web/src/cloud/useCloudLinkController.browser.test.tsx
index 1bd7f0b22cd..2eae7bb8430 100644
--- a/apps/web/src/cloud/useCloudLinkController.test.tsx
+++ b/apps/web/src/cloud/useCloudLinkController.browser.test.tsx
@@ -7,7 +7,7 @@ import {
import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay";
import { AsyncResult } from "effect/reactivity";
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";
const testState = vi.hoisted(() => ({
@@ -24,8 +24,9 @@ const testState = vi.hoisted(() => ({
toast: vi.fn(),
}));
-vi.mock("@effect/atom-react", () => ({
- useAtomValue: () => ({
+vi.mock(import("@effect/atom-react"), async (original) => ({
+ ...(await original()),
+ useAtomValue: (() => ({
environments: new Map(
testState.relayProviderKind === null
? []
@@ -36,35 +37,56 @@ vi.mock("@effect/atom-react", () => ({
],
],
),
- }),
+ })) as never,
}));
-vi.mock("@clerk/react", () => ({
- useAuth: () => ({ getToken: testState.getToken, isSignedIn: true }),
+vi.mock(import("@clerk/react"), async (original) => ({
+ ...(await original()),
+ useAuth: (() => ({ getToken: testState.getToken, isSignedIn: true })) as never,
}));
-vi.mock("../components/ui/toast", () => ({ toastManager: { add: testState.toast } }));
-vi.mock("../state/relay", () => ({
- relayEnvironmentDiscovery: { refresh: testState.refreshDiscovery, stateValueAtom: {} },
+vi.mock(import("../components/ui/toast"), async (original) => {
+ const actual = await original();
+ return { ...actual, toastManager: { ...actual.toastManager, add: testState.toast } as never };
+});
+vi.mock(import("../state/relay"), async (original) => {
+ const actual = await original();
+ return {
+ ...actual,
+ relayEnvironmentDiscovery: {
+ ...actual.relayEnvironmentDiscovery,
+ refresh: testState.refreshDiscovery,
+ } as never,
+ };
+});
+vi.mock(import("../state/session"), async (original) => ({
+ ...(await original()),
+ readEnvironmentScope: (_environmentId, scope) => testState.scopes.has(scope),
}));
-vi.mock("../state/session", () => ({
- readEnvironmentScope: (_environmentId: string, scope: string) => testState.scopes.has(scope),
+vi.mock(import("../state/use-atom-command"), async (original) => ({
+ ...(await original()),
+ useAtomCommand: ((command: unknown) => command) as never,
}));
-vi.mock("../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));
-vi.mock("./linkEnvironmentAtoms", () => ({
- linkPrimaryEnvironment: testState.link,
- unlinkPrimaryEnvironment: testState.unlink,
- updatePrimaryEnvironmentPreferences: testState.preferences,
+vi.mock(import("./linkEnvironmentAtoms"), async (original) => ({
+ ...(await original()),
+ linkPrimaryEnvironment: testState.link as never,
+ unlinkPrimaryEnvironment: testState.unlink as never,
+ updatePrimaryEnvironmentPreferences: testState.preferences as never,
}));
-vi.mock("./primaryCloudLinkState", () => ({
+vi.mock(import("./primaryCloudLinkState"), async (original) => ({
+ ...(await original()),
readCachedPrimaryCloudLinkState: () => testState.snapshot,
- usePrimaryCloudLinkState: () => ({
+ usePrimaryCloudLinkState: (() => ({
target,
data: testState.renderedSnapshot,
error: null,
isPending: false,
refresh: testState.refreshLink,
- }),
+ })) as never,
+}));
+// The Clerk JWT template is build-time config the test environment does not set.
+vi.mock(import("./publicConfig"), async (original) => ({
+ ...(await original()),
+ resolveRelayClerkTokenOptions: () => ({}) as never,
}));
-vi.mock("./publicConfig", () => ({ resolveRelayClerkTokenOptions: () => ({}) }));
import { useCloudLinkController, type CloudLinkDesiredState } from "./useCloudLinkController";
@@ -83,7 +105,7 @@ const linkedState: EnvironmentCloudLinkStateResult = {
publishAgentActivity: false,
};
-let renderer: ReactTestRenderer | null = null;
+let root: Root | null = null;
let controller: ReturnType<typeof useCloudLinkController> | null = null;
function ControllerProbe() {
@@ -95,9 +117,8 @@ function ControllerProbe() {
}
async function mountController() {
- await act(() => {
- renderer = create(<ControllerProbe />);
- });
+ root = createRoot(document.createElement("div"));
+ await act(async () => root!.render(<ControllerProbe />));
}
async function reconcile(desired: CloudLinkDesiredState) {
@@ -136,8 +157,8 @@ beforeEach(() => {
});
afterEach(async () => {
- await act(() => renderer?.unmount());
- renderer = null;
+ await act(async () => root?.unmount());
+ root = null;
controller = null;
vi.restoreAllMocks();
vi.unstubAllGlobals();
diff --git a/apps/web/src/components/KeybindingsConfigWarning.browser.test.tsx b/apps/web/src/components/KeybindingsConfigWarning.browser.test.tsx
new file mode 100644
index 00000000000..b3f00642ee0
--- /dev/null
+++ b/apps/web/src/components/KeybindingsConfigWarning.browser.test.tsx
@@ -0,0 +1,117 @@
+import { RegistryContext } from "@effect/atom-react";
+import {
+ AuthOrchestrationOperateScope,
+ EnvironmentId,
+ type AuthEnvironmentScope,
+ type AuthSessionState,
+} from "@t3tools/contracts";
+import { AsyncResult, Atom } from "effect/reactivity";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
+
+type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
+const state = vi.hoisted(() => ({
+ sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),
+ run: vi.fn(),
+ toast: vi.fn(),
+}));
+
+vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => {
+ const actual = await original();
+ return {
+ ...actual,
+ createEnvironmentSessionAtoms: ((runtime: never) => ({
+ ...actual.createEnvironmentSessionAtoms(runtime),
+ sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,
+ })) as never,
+ };
+});
+vi.mock(import("../state/use-atom-command"), async (original) => ({
+ ...(await original()),
+ useAtomCommand: (() => state.run) as never,
+}));
+vi.mock(import("./ui/toast"), async (original) => {
+ const actual = await original();
+ return { ...actual, toastManager: { ...actual.toastManager, add: state.toast } as never };
+});
+
+import { appAtomRegistry } from "../rpc/atomRegistry";
+import { KeybindingsConfigWarning } from "./KeybindingsConfigWarning";
+
+const environmentId = EnvironmentId.make("warning-environment");
+let root: Root;
+let container: HTMLDivElement;
+const session = (scopes: readonly AuthEnvironmentScope[]): AuthSessionState => ({
+ authenticated: true,
+ scopes,
+ auth: {
+ policy: "remote-reachable",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["bearer-access-token"],
+ sessionCookieName: "t3_session",
+ },
+});
+const setScopes = (scopes: readonly AuthEnvironmentScope[]) =>
+ appAtomRegistry.set(state.sessions.get(environmentId)!, AsyncResult.success(session(scopes)));
+const button = () => container.querySelector("button")!;
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ localStorage.setItem("t3code:last-editor", JSON.stringify("vscode"));
+ state.sessions.set(
+ environmentId,
+ Atom.make<SessionResult>(AsyncResult.success(session([AuthOrchestrationOperateScope]))).pipe(
+ Atom.keepAlive,
+ ),
+ );
+ state.run.mockReset().mockResolvedValue(AsyncResult.success(undefined));
+ state.toast.mockReset();
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ container.remove();
+ localStorage.clear();
+ state.sessions.clear();
+ vi.unstubAllGlobals();
+});
+
+it("updates a visible warning on revocation and blocks a click that raced it until regrant", async () => {
+ await act(async () =>
+ root.render(
+ <RegistryContext.Provider value={appAtomRegistry}>
+ <KeybindingsConfigWarning
+ environmentId={environmentId}
+ configPath="/t3/keybindings.json"
+ availableEditors={["vscode"]}
+ message="Invalid shortcut"
+ />
+ </RegistryContext.Provider>,
+ ),
+ );
+ expect(container.textContent).toContain("Invalid shortcut");
+ expect(button().disabled).toBe(false);
+
+ // The click lands before React re-renders the revoked grant.
+ await act(async () => {
+ setScopes([]);
+ button().click();
+ });
+ expect(button().disabled).toBe(true);
+ expect(state.run).not.toHaveBeenCalled();
+ expect(state.toast).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Unable to open keybindings file" }),
+ );
+
+ await act(async () => setScopes([AuthOrchestrationOperateScope]));
+ expect(button().disabled).toBe(false);
+ await act(async () => button().click());
+ expect(state.run).toHaveBeenCalledExactlyOnceWith({
+ environmentId,
+ input: { cwd: "/t3/keybindings.json", editor: "vscode" },
+ });
+});
diff --git a/apps/web/src/components/KeybindingsConfigWarning.test.tsx b/apps/web/src/components/KeybindingsConfigWarning.test.tsx
deleted file mode 100644
index 3059b46b2bd..00000000000
--- a/apps/web/src/components/KeybindingsConfigWarning.test.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-import { RegistryContext } from "@effect/atom-react";
-import {
- AuthOrchestrationOperateScope,
- EnvironmentId,
- type AuthEnvironmentScope,
- type AuthSessionState,
-} from "@t3tools/contracts";
-import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
-import { act, create, type ReactTestRenderer } from "react-test-renderer";
-import { afterEach, beforeEach, 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>>(),
- run: vi.fn(),
- toast: vi.fn(),
-}));
-
-vi.mock("../connection/runtime", () => ({ connectionAtomRuntime: undefined }));
-vi.mock("@t3tools/client-runtime/state/session", () => ({
- createEnvironmentSessionAtoms: () => ({
- sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,
- }),
-}));
-vi.mock("../rpc/atomRegistry", () => ({
- get appAtomRegistry() {
- return state.registry;
- },
-}));
-vi.mock("../state/shell", () => ({ shellEnvironment: { openInEditor: "openInEditor" } }));
-vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => state.run }));
-vi.mock("../hooks/useLocalStorage", () => ({
- getLocalStorageItem: () => "vscode",
- setLocalStorageItem: vi.fn(),
- useLocalStorage: vi.fn(),
-}));
-vi.mock("./ui/button", () => ({ Button: "button" }));
-vi.mock("./ui/toast", () => ({
- toastManager: { add: state.toast },
- stackedThreadToast: (value: unknown) => value,
-}));
-
-import { KeybindingsConfigWarning } from "./KeybindingsConfigWarning";
-
-const environmentId = EnvironmentId.make("warning-environment");
-let renderer: ReactTestRenderer | undefined;
-const session = (scopes: readonly AuthEnvironmentScope[]): AuthSessionState => ({
- authenticated: true,
- scopes,
- auth: {
- policy: "remote-reachable",
- bootstrapMethods: ["one-time-token"],
- sessionMethods: ["bearer-access-token"],
- sessionCookieName: "t3_session",
- },
-});
-
-beforeEach(() => {
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- state.registry = AtomRegistry.make();
- state.sessions.set(
- environmentId,
- Atom.make<SessionResult>(AsyncResult.success(session([AuthOrchestrationOperateScope]))).pipe(
- Atom.keepAlive,
- ),
- );
- state.run.mockReset().mockResolvedValue(AsyncResult.success(undefined));
- state.toast.mockReset();
-});
-
-afterEach(async () => {
- await act(async () => renderer?.unmount());
- renderer = undefined;
- state.registry?.dispose();
- state.sessions.clear();
- vi.unstubAllGlobals();
-});
-
-it("updates a visible warning on revocation and blocks its retained action until regrant", async () => {
- await act(async () => {
- renderer = create(
- <RegistryContext.Provider value={state.registry!}>
- <KeybindingsConfigWarning
- environmentId={environmentId}
- configPath="/t3/keybindings.json"
- availableEditors={["vscode"]}
- message="Invalid shortcut"
- />
- </RegistryContext.Provider>,
- );
- });
- const open = renderer!.root.findByType("button").props.onClick;
- expect(renderer!.root.findByType("button").props.disabled).toBe(false);
- await act(async () => {
- state.registry!.set(state.sessions.get(environmentId)!, AsyncResult.success(session([])));
- await open();
- });
- expect(renderer!.root.findByType("button").props.disabled).toBe(true);
- expect(state.run).not.toHaveBeenCalled();
- expect(state.toast).toHaveBeenCalledWith(
- expect.objectContaining({
- title: "Unable to open keybindings file",
- }),
- );
-
- await act(async () => {
- state.registry!.set(
- state.sessions.get(environmentId)!,
- AsyncResult.success(session([AuthOrchestrationOperateScope])),
- );
- });
- expect(renderer!.root.findByType("button").props.disabled).toBe(false);
- await act(async () => open());
- expect(state.run).toHaveBeenCalledExactlyOnceWith({
- environmentId,
- input: { cwd: "/t3/keybindings.json", editor: "vscode" },
- });
-});
diff --git a/apps/web/src/components/PermissionUpdateNotice.browser.test.tsx b/apps/web/src/components/PermissionUpdateNotice.browser.test.tsx
new file mode 100644
index 00000000000..58542edf62e
--- /dev/null
+++ b/apps/web/src/components/PermissionUpdateNotice.browser.test.tsx
@@ -0,0 +1,113 @@
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
+
+type Session = {
+ _tag: "Success" | "Failure";
+ waiting: boolean;
+ value: { authenticated: boolean; permissions: string[] };
+};
+const state = vi.hoisted(() => ({
+ id: 0,
+ session: null as unknown as Session,
+ add: vi.fn((_notice: unknown) => "notice"),
+ close: vi.fn(),
+ navigate: vi.fn(),
+}));
+vi.mock(import("@effect/atom-react"), async (original) => ({
+ ...(await original()),
+ useAtomValue: (() => state.session) as never,
+}));
+vi.mock(import("@tanstack/react-router"), async (original) => ({
+ ...(await original()),
+ useNavigate: (() => state.navigate) as never,
+}));
+vi.mock(import("../state/environments"), async (original) => ({
+ ...(await original()),
+ useEnvironments: (() => ({
+ environments: [{ environmentId: `env-${state.id}`, label: "Work laptop" }],
+ })) as never,
+}));
+vi.mock(import("./ui/toast"), async (original) => {
+ const actual = await original();
+ return {
+ ...actual,
+ toastManager: { ...actual.toastManager, add: state.add, close: state.close } as never,
+ };
+});
+import { PermissionUpdateNotice } from "./PermissionUpdateNotice";
+
+let root: Root;
+let container: HTMLDivElement;
+const storageKey = () => `t3code:permission-update:v1:env-${state.id}`;
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ state.id++;
+ state.session = {
+ _tag: "Success",
+ waiting: false,
+ value: { authenticated: true, permissions: ["orchestration:operate"] },
+ };
+ vi.clearAllMocks();
+ container = document.createElement("div");
+ root = createRoot(container);
+});
+afterEach(async () => {
+ await act(async () => root.unmount());
+ localStorage.clear();
+ vi.unstubAllGlobals();
+});
+const render = () => act(async () => root.render(<PermissionUpdateNotice />));
+type Notice = {
+ timeout: number;
+ actionProps: { onClick: () => void };
+ data: { secondaryActionProps: { onClick: () => void } };
+};
+const notice = () => state.add.mock.calls[0]![0] as Notice;
+
+it("keeps the notice visible and persists dismissal, with a route to pairing settings", async () => {
+ await render();
+ expect(notice().timeout).toBe(0);
+ expect(localStorage.getItem(storageKey())).toBeNull();
+ notice().actionProps.onClick();
+ expect(state.navigate).toHaveBeenCalledWith({ to: "/settings/connections" });
+ expect(state.close).toHaveBeenCalledWith("notice");
+ expect(localStorage.getItem(storageKey())).toBe("true");
+});
+it("does not repeat on session refresh or remount", async () => {
+ await render();
+ await act(async () => root.unmount());
+ root = createRoot(container);
+ state.session = { ...state.session };
+ await render();
+ expect(state.add).toHaveBeenCalledTimes(1);
+});
+it("skips a notice dismissed on an earlier launch", async () => {
+ localStorage.setItem(storageKey(), "true");
+ await render();
+ expect(state.add).not.toHaveBeenCalled();
+});
+it("waits for a successful, settled session check", async () => {
+ state.session._tag = "Failure";
+ await render();
+ expect(state.add).not.toHaveBeenCalled();
+ state.session = { ...state.session, _tag: "Success", waiting: true };
+ await render();
+ expect(state.add).not.toHaveBeenCalled();
+ state.session = { ...state.session, waiting: false };
+ await render();
+ expect(state.add).toHaveBeenCalledTimes(1);
+});
+it("does not warn for a granular grant", async () => {
+ state.session.value.permissions.push("filesystem:read");
+ await render();
+ expect(state.add).not.toHaveBeenCalled();
+});
+
+it("persists the secondary dismissal without relying on the toast close callback", async () => {
+ await render();
+ notice().data.secondaryActionProps.onClick();
+ expect(localStorage.getItem(storageKey())).toBe("true");
+ expect(state.close).toHaveBeenCalledWith("notice");
+});
diff --git a/apps/web/src/components/PermissionUpdateNotice.test.tsx b/apps/web/src/components/PermissionUpdateNotice.test.tsx
deleted file mode 100644
index f96a2d410f1..00000000000
--- a/apps/web/src/components/PermissionUpdateNotice.test.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-import { act, create, type ReactTestRenderer } from "react-test-renderer";
-import { beforeEach, afterEach, expect, it, vi } from "vite-plus/test";
-
-const state = vi.hoisted(() => ({
- id: 0,
- saved: false,
- session: {
- _tag: "Success",
- waiting: false,
- value: { authenticated: true, permissions: ["orchestration:operate"] },
- },
- add: vi.fn((_notice: unknown) => "notice"),
- close: vi.fn(),
- save: vi.fn(),
- navigate: vi.fn(),
-}));
-vi.mock("@effect/atom-react", () => ({ useAtomValue: () => state.session }));
-vi.mock("@tanstack/react-router", () => ({ useNavigate: () => state.navigate }));
-vi.mock("../state/environments", () => ({
- useEnvironments: () => ({
- environments: [{ environmentId: `env-${state.id}`, label: "Work laptop" }],
- }),
-}));
-vi.mock("../state/session", () => ({ environmentSession: { sessionStateAtom: () => null } }));
-vi.mock("../hooks/useLocalStorage", () => ({
- getLocalStorageItem: () => state.saved,
- setLocalStorageItem: (...args: unknown[]) => state.save(...args),
-}));
-vi.mock("./ui/toast", () => ({ toastManager: { add: state.add, close: state.close } }));
-import { PermissionUpdateNotice } from "./PermissionUpdateNotice";
-
-let renderer: ReactTestRenderer;
-beforeEach(() => {
- state.id++;
- state.saved = false;
- state.session = {
- _tag: "Success",
- waiting: false,
- value: { authenticated: true, permissions: ["orchestration:operate"] },
- };
- vi.clearAllMocks();
-});
-afterEach(async () => {
- if (renderer) await act(async () => renderer.unmount());
-});
-async function render() {
- await act(async () => {
- renderer = create(<PermissionUpdateNotice />);
- });
-}
-
-it("keeps the notice visible and persists dismissal, with a route to pairing settings", async () => {
- await render();
- const notice = state.add.mock.calls[0]![0] as unknown as {
- timeout: number;
- onClose: () => void;
- actionProps: { onClick: () => void };
- };
- expect(notice.timeout).toBe(0);
- expect(state.save).not.toHaveBeenCalled();
- notice.actionProps.onClick();
- expect(state.navigate).toHaveBeenCalledWith({ to: "/settings/connections" });
- expect(state.close).toHaveBeenCalledWith("notice");
- expect(state.save).toHaveBeenCalledWith(
- `t3code:permission-update:v1:env-${state.id}`,
- true,
- expect.anything(),
- );
-});
-it("does not repeat on session refresh or remount", async () => {
- await render();
- await act(async () => renderer.unmount());
- state.session = { ...state.session };
- await render();
- expect(state.add).toHaveBeenCalledTimes(1);
-});
-it("skips a notice dismissed on an earlier launch", async () => {
- state.saved = true;
- await render();
- expect(state.add).not.toHaveBeenCalled();
-});
-it("waits for a successful, settled session check", async () => {
- state.session._tag = "Failure";
- await render();
- expect(state.add).not.toHaveBeenCalled();
- state.session = { ...state.session, _tag: "Success", waiting: true };
- await act(async () => renderer.update(<PermissionUpdateNotice />));
- expect(state.add).not.toHaveBeenCalled();
- state.session = { ...state.session, waiting: false };
- await act(async () => renderer.update(<PermissionUpdateNotice />));
- expect(state.add).toHaveBeenCalledTimes(1);
-});
-it("does not warn for a granular grant", async () => {
- state.session.value.permissions.push("filesystem:read");
- await render();
- expect(state.add).not.toHaveBeenCalled();
-});
-
-it("persists the secondary dismissal without relying on the toast close callback", async () => {
- await render();
- const notice = state.add.mock.calls[0]![0] as {
- data: { secondaryActionProps: { onClick: () => void } };
- };
- notice.data.secondaryActionProps.onClick();
- expect(state.save).toHaveBeenCalledWith(
- `t3code:permission-update:v1:env-${state.id}`,
- true,
- expect.anything(),
- );
- expect(state.close).toHaveBeenCalledWith("notice");
-});
diff --git a/apps/web/src/components/clerk/T3ConnectUserProfilePage.test.tsx b/apps/web/src/components/clerk/T3ConnectUserProfilePage.test.tsx
deleted file mode 100644
index 377c9c94555..00000000000
--- a/apps/web/src/components/clerk/T3ConnectUserProfilePage.test.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import type { EnvironmentId } from "@t3tools/contracts";
-import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
-import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it, vi } from "vite-plus/test";
-
-import { T3ConnectEnvironmentRow } from "./T3ConnectUserProfilePage";
-
-const environment: RelayClientEnvironmentRecord = {
- environmentId: "environment-1" as EnvironmentId,
- label: "Studio Mac",
- endpoint: {
- httpBaseUrl: "https://studio.example.com",
- wsBaseUrl: "wss://studio.example.com",
- providerKind: "cloudflare_tunnel",
- },
- linkedAt: "2026-08-12T12:00:00.000Z",
-};
-
-function renderRow({
- confirmationOpen = false,
- mutationPending = false,
-}: {
- readonly confirmationOpen?: boolean;
- readonly mutationPending?: boolean;
-} = {}) {
- return renderToStaticMarkup(
- <T3ConnectEnvironmentRow
- environment={environment}
- confirmationOpen={confirmationOpen}
- mutationPending={mutationPending}
- onConfirmationChange={vi.fn()}
- onDeregister={vi.fn()}
- />,
- );
-}
-
-describe("T3 Connect environment row", () => {
- it("keeps deregistration confirmation inline and collapsed by default", () => {
- const markup = renderRow();
-
- expect(markup).toContain("Studio Mac");
- expect(markup).toContain("Deregister");
- expect(markup).not.toContain("Deregister server");
- expect(markup).not.toContain("Confirm deregistration of Studio Mac");
- });
-
- it("expands Clerk-style confirmation content beneath the environment row", () => {
- const markup = renderRow({ confirmationOpen: true });
-
- expect(markup).toContain("Deregister server");
- expect(markup).toContain("“Studio Mac” will be removed from this account.");
- expect(markup).toContain("Confirm deregistration of Studio Mac");
- expect(markup).toContain("Local connections on your devices are not changed.");
- expect(markup).toContain("Cancel");
- });
-
- it("locks the confirmation actions while deregistration is pending", () => {
- const markup = renderRow({ confirmationOpen: true, mutationPending: true });
-
- expect(markup).toContain("Deregistering…");
- expect(markup.match(/ disabled=""/g)).toHaveLength(3);
- });
-});
diff --git a/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx b/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx
index 284655babbb..d0342005e6f 100644
--- a/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx
+++ b/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx
@@ -38,7 +38,7 @@ function endpointLabel(environment: RelayClientEnvironmentRecord): string {
: "Activity publishing only";
}
-export function T3ConnectEnvironmentRow(props: {
+function T3ConnectEnvironmentRow(props: {
readonly environment: RelayClientEnvironmentRecord;
readonly confirmationOpen: boolean;
readonly mutationPending: boolean;
diff --git a/apps/web/src/components/cloud/CloudEnvironmentConnectList.test.tsx b/apps/web/src/components/cloud/CloudEnvironmentConnectList.browser.test.tsx
similarity index 65%
rename from apps/web/src/components/cloud/CloudEnvironmentConnectList.test.tsx
rename to apps/web/src/components/cloud/CloudEnvironmentConnectList.browser.test.tsx
index f6ea5be6229..dfe3880654f 100644
--- a/apps/web/src/components/cloud/CloudEnvironmentConnectList.test.tsx
+++ b/apps/web/src/components/cloud/CloudEnvironmentConnectList.browser.test.tsx
@@ -3,8 +3,8 @@ import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import { EnvironmentId, ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { AsyncResult } from "effect/reactivity";
-import { act, useState, type ButtonHTMLAttributes, type ReactNode } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
+import { act, useState } from "react";
+import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
type DiscoveredEnvironments = Discovery.RelayEnvironmentDiscoveryState["environments"];
@@ -12,24 +12,22 @@ type DiscoveredEnvironments = Discovery.RelayEnvironmentDiscoveryState["environm
const discovery = vi.hoisted(() => ({
state: null as Discovery.RelayEnvironmentDiscoveryState | null,
listeners: new Set<() => void>(),
- refreshCommand: Symbol("refresh"),
- registerCommand: Symbol("register"),
refresh: vi.fn<() => Promise<AtomCommandResult<void, never>>>(),
register: vi.fn(),
listEnvironments: vi.fn<() => Promise<DiscoveredEnvironments>>(),
}));
-vi.mock("~/state/relay", () => ({
- relayEnvironmentDiscovery: { refresh: discovery.refreshCommand },
-}));
-vi.mock("~/connection/catalog", () => ({
- environmentCatalog: { register: discovery.registerCommand },
-}));
-vi.mock("~/state/use-atom-command", () => ({
- useAtomCommand: (command: unknown) =>
- command === discovery.refreshCommand ? discovery.refresh : discovery.register,
-}));
-vi.mock("~/state/environments", async () => {
+vi.mock(import("~/state/use-atom-command"), async (original) => {
+ const { relayEnvironmentDiscovery } = await import("~/state/relay");
+ return {
+ ...(await original()),
+ useAtomCommand: ((command: unknown) =>
+ command === relayEnvironmentDiscovery.refresh
+ ? discovery.refresh
+ : discovery.register) as never,
+ };
+});
+vi.mock(import("~/state/environments"), async (original) => {
const { useSyncExternalStore } = await import("react");
const subscribe = (listener: () => void) => {
discovery.listeners.add(listener);
@@ -39,34 +37,11 @@ vi.mock("~/state/environments", async () => {
if (discovery.state === null) throw new Error("Discovery fixture is not initialized");
return discovery.state;
};
- return { useRelayEnvironmentDiscovery: () => useSyncExternalStore(subscribe, read, read) };
+ return {
+ ...(await original()),
+ useRelayEnvironmentDiscovery: () => useSyncExternalStore(subscribe, read, read),
+ };
});
-vi.mock("../ConnectionStatusDot", () => ({ ConnectionStatusDot: () => null }));
-vi.mock("../ui/tooltip", () => ({
- Tooltip: ({ children }: { children: ReactNode }) => children,
- TooltipTrigger: ({ children }: { children: ReactNode }) => <span>{children}</span>,
- TooltipPopup: () => null,
-}));
-vi.mock("../ui/checkbox", () => ({
- Checkbox: (props: {
- checked: boolean;
- disabled: boolean;
- onCheckedChange: (checked: boolean) => void;
- }) => (
- <input
- type="checkbox"
- checked={props.checked}
- disabled={props.disabled}
- onChange={(event) => props.onCheckedChange(event.target.checked)}
- />
- ),
-}));
-vi.mock("../ui/button", () => ({
- Button: ({ children, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) => (
- <button {...props}>{children}</button>
- ),
-}));
-vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));
import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList";
@@ -92,27 +67,41 @@ const linkedMachines: DiscoveredEnvironments = new Map([
],
]);
-let renderer: ReactTestRenderer | null;
-let page: EventTarget & { visibilityState: DocumentVisibilityState };
-let browserWindow: EventTarget;
+let root: Root | null;
+let container: HTMLDivElement;
+let visibility: DocumentVisibilityState;
function publish(state: Discovery.RelayEnvironmentDiscoveryState) {
discovery.state = state;
for (const listener of discovery.listeners) listener();
}
+async function render(element: React.ReactElement) {
+ root ??= createRoot(container);
+ await act(async () => root!.render(element));
+}
+
async function mount(refreshWhileEmpty = true) {
- await act(async () => {
- renderer = create(
- <CloudEnvironmentConnectRows
- primaryEnvironmentId={null}
- savedEnvironments={[]}
- showSavedEnvironments
- refreshWhileEmpty={refreshWhileEmpty}
- empty={<p>Waiting for your computer to connect.</p>}
- />,
- );
- });
+ await render(
+ <CloudEnvironmentConnectRows
+ primaryEnvironmentId={null}
+ savedEnvironments={[]}
+ showSavedEnvironments
+ refreshWhileEmpty={refreshWhileEmpty}
+ empty={<p>Waiting for your computer to connect.</p>}
+ />,
+ );
+}
+
+const text = () => container.textContent ?? "";
+const button = () =>
+ [...container.querySelectorAll("button")].find((element) => element.textContent !== "");
+const checkbox = () => container.querySelector<HTMLElement>('[role="checkbox"]')!;
+const checked = () => checkbox().getAttribute("aria-checked") === "true";
+const toggle = () => act(async () => checkbox().click());
+function setVisibility(next: DocumentVisibilityState) {
+ visibility = next;
+ document.dispatchEvent(new Event("visibilitychange"));
}
async function advance(milliseconds: number) {
@@ -124,11 +113,11 @@ async function advance(milliseconds: number) {
beforeEach(() => {
vi.useFakeTimers();
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- page = Object.assign(new EventTarget(), { visibilityState: "visible" as const });
- browserWindow = new EventTarget();
- vi.stubGlobal("document", page);
- vi.stubGlobal("window", browserWindow);
- renderer = null;
+ visibility = "visible";
+ vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility);
+ container = document.createElement("div");
+ document.body.append(container);
+ root = null;
discovery.listeners.clear();
discovery.state = {
environments: new Map(),
@@ -147,8 +136,10 @@ beforeEach(() => {
});
afterEach(async () => {
- await act(async () => renderer?.unmount());
+ await act(async () => root?.unmount());
+ container.remove();
vi.useRealTimers();
+ vi.restoreAllMocks();
vi.unstubAllGlobals();
});
@@ -167,12 +158,10 @@ describe("cloud environment offline reasons", () => {
...(offlineReason ? { offlineReason } : {}),
}),
});
- const rowText = () =>
- renderer!.root.findAllByType("p").flatMap((paragraph) => paragraph.children);
discovery.listEnvironments.mockResolvedValue(new Map([[newMachineId, offlineEntry()]]));
await mount();
- expect(rowText()).toContain("T3 Connect · Not added · Relay offline");
+ expect(text()).toContain("T3 Connect · Not added · Relay offline");
await act(async () => {
publish({
@@ -182,7 +171,7 @@ describe("cloud environment offline reasons", () => {
error: Option.none(),
});
});
- expect(rowText()).toContain(RELAY_TUNNEL_RELEASED_MESSAGE);
+ expect(text()).toContain(RELAY_TUNNEL_RELEASED_MESSAGE);
});
});
@@ -195,21 +184,19 @@ describe("cloud onboarding discovery", () => {
}),
);
const onDiscoveryReady = vi.fn();
- await act(async () => {
- renderer = create(
- <CloudEnvironmentConnectRows
- primaryEnvironmentId={null}
- savedEnvironments={[]}
- onDiscoveryReady={onDiscoveryReady}
- />,
- );
- });
+ await render(
+ <CloudEnvironmentConnectRows
+ primaryEnvironmentId={null}
+ savedEnvironments={[]}
+ onDiscoveryReady={onDiscoveryReady}
+ />,
+ );
expect(onDiscoveryReady).not.toHaveBeenCalled();
await act(async () => {
finishDiscovery(linkedMachines);
});
expect(onDiscoveryReady).toHaveBeenCalledTimes(1);
- expect(renderer!.root.findByType("button").children).toEqual(["Add"]);
+ expect(button()?.textContent).toBe("Add");
});
it("keeps incompatible discoveries unselected until the user enables a compatible server", async () => {
@@ -261,19 +248,13 @@ describe("cloud onboarding discovery", () => {
/>
);
}
- await act(async () => {
- renderer = create(<Setup />);
- });
+ await render(<Setup />);
expect(discovery.register).not.toHaveBeenCalled();
expect(onSelectionChange).toHaveBeenCalledWith(newMachineId, false);
- expect(renderer!.root.findByType("input").props.checked).toBe(false);
- expect(renderer!.root.findByType("input").props.disabled).toBe(true);
- expect(renderer!.root.findAllByType("span").flatMap((span) => span.children)).toContain(
- "Client not supported",
- );
- await act(async () => {
- await renderer!.root.findByType("input").props.onChange({ target: { checked: true } });
- });
+ expect(checked()).toBe(false);
+ expect(checkbox().hasAttribute("data-disabled")).toBe(true);
+ expect(text()).toContain("Client not supported");
+ await toggle();
expect(discovery.register).not.toHaveBeenCalled();
await act(async () =>
publish({
@@ -282,11 +263,9 @@ describe("cloud onboarding discovery", () => {
}),
);
expect(discovery.register).not.toHaveBeenCalled();
- expect(renderer!.root.findByType("input").props.checked).toBe(false);
- expect(renderer!.root.findByType("input").props.disabled).toBe(false);
- await act(async () => {
- await renderer!.root.findByType("input").props.onChange({ target: { checked: true } });
- });
+ expect(checked()).toBe(false);
+ expect(checkbox().hasAttribute("data-disabled")).toBe(false);
+ await toggle();
expect(discovery.register).toHaveBeenCalledTimes(1);
});
@@ -314,19 +293,15 @@ describe("cloud onboarding discovery", () => {
/>
);
}
- await act(async () => {
- renderer = create(<Setup />);
- });
+ await render(<Setup />);
expect(discovery.register).toHaveBeenCalledTimes(1);
- expect(renderer!.root.findByType("input").props.checked).toBe(true);
- await act(async () => {
- await renderer!.root.findByType("input").props.onChange({ target: { checked: false } });
- });
+ expect(checked()).toBe(true);
+ await toggle();
await act(async () => {
publish({ ...discovery.state!, environments: new Map(linkedMachines) });
});
- expect(renderer!.root.findByType("input").props.checked).toBe(false);
+ expect(checked()).toBe(false);
expect(discovery.register).toHaveBeenCalledTimes(1);
});
@@ -335,16 +310,12 @@ describe("cloud onboarding discovery", () => {
.mockResolvedValueOnce(new Map())
.mockResolvedValueOnce(linkedMachines);
await mount();
- expect(renderer!.root.findByType("p").children).toEqual([
- "Waiting for your computer to connect.",
- ]);
+ expect(text()).toBe("Waiting for your computer to connect.");
await advance(5_000);
- expect(renderer!.root.findAllByType("p").map((node) => node.children)).toContainEqual([
- "Work laptop",
- ]);
- expect(renderer!.root.findByType("button").children).toEqual(["Add"]);
+ expect(text()).toContain("Work laptop");
+ expect(button()?.textContent).toBe("Add");
await advance(30_000);
expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
});
@@ -352,44 +323,36 @@ describe("cloud onboarding discovery", () => {
it("keeps a discovered computer visible when it is added to the browser", async () => {
discovery.listEnvironments.mockResolvedValue(linkedMachines);
await mount();
- expect(renderer!.root.findByType("button").children).toEqual(["Add"]);
- await act(async () => {
- renderer!.update(
- <CloudEnvironmentConnectRows
- primaryEnvironmentId={null}
- savedEnvironments={[
- {
- environmentId: newMachineId,
- connection: { phase: "connected", error: null, traceId: null },
- relayManaged: true,
- },
- ]}
- showSavedEnvironments
- refreshWhileEmpty
- />,
- );
- });
- expect(renderer!.root.findAllByType("p").map((node) => node.children)).toContainEqual([
- "Work laptop",
- ]);
- expect(renderer!.root.findByType("button").children).toEqual(["Connected"]);
+ expect(button()?.textContent).toBe("Add");
+ await render(
+ <CloudEnvironmentConnectRows
+ primaryEnvironmentId={null}
+ savedEnvironments={[
+ {
+ environmentId: newMachineId,
+ connection: { phase: "connected", error: null, traceId: null },
+ relayManaged: true,
+ },
+ ]}
+ showSavedEnvironments
+ refreshWhileEmpty
+ />,
+ );
+ expect(text()).toContain("Work laptop");
+ expect(button()?.textContent).toBe("Connected");
});
it("waits while hidden and refreshes immediately when visible again", async () => {
- page.visibilityState = "hidden";
+ visibility = "hidden";
await mount();
await advance(30_000);
expect(discovery.listEnvironments).not.toHaveBeenCalled();
- await act(async () => {
- page.visibilityState = "visible";
- page.dispatchEvent(new Event("visibilitychange"));
- });
+ await act(async () => setVisibility("visible"));
expect(discovery.listEnvironments).toHaveBeenCalledTimes(1);
- page.visibilityState = "hidden";
- page.dispatchEvent(new Event("visibilitychange"));
- browserWindow.dispatchEvent(new Event("focus"));
+ setVisibility("hidden");
+ window.dispatchEvent(new Event("focus"));
await advance(30_000);
expect(discovery.listEnvironments).toHaveBeenCalledTimes(1);
});
@@ -402,17 +365,15 @@ describe("cloud onboarding discovery", () => {
discovery.listEnvironments.mockResolvedValueOnce(new Map()).mockReturnValueOnce(pending);
await mount();
await advance(5_000);
- expect(renderer!.root.findByType("p").children).toEqual([
- "Waiting for your computer to connect.",
- ]);
+ expect(text()).toBe("Waiting for your computer to connect.");
- browserWindow.dispatchEvent(new Event("focus"));
- page.dispatchEvent(new Event("visibilitychange"));
+ window.dispatchEvent(new Event("focus"));
+ document.dispatchEvent(new Event("visibilitychange"));
await advance(30_000);
expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
- await act(async () => renderer!.unmount());
- renderer = null;
+ await act(async () => root!.unmount());
+ root = null;
await act(async () => resolveRefresh(new Map()));
await advance(30_000);
expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
diff --git a/apps/web/src/components/device/DeviceStreamView.test.tsx b/apps/web/src/components/device/DeviceStreamView.browser.test.tsx
similarity index 54%
rename from apps/web/src/components/device/DeviceStreamView.test.tsx
rename to apps/web/src/components/device/DeviceStreamView.browser.test.tsx
index 38d83f0f029..843849df0ff 100644
--- a/apps/web/src/components/device/DeviceStreamView.test.tsx
+++ b/apps/web/src/components/device/DeviceStreamView.browser.test.tsx
@@ -1,7 +1,7 @@
import { act, useEffect, useSyncExternalStore } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
+import { createRoot, type Root } from "react-dom/client";
import { EnvironmentId } from "@t3tools/contracts";
-import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
+import { afterEach, beforeEach, expect, it, onTestFinished, vi } from "vite-plus/test";
const accessStore = {
value: { httpBase: "http://test", wsBase: "ws://test", query: {}, credentials: true },
@@ -15,50 +15,102 @@ const accessStore = {
return () => accessStore.listeners.delete(listener);
},
};
-vi.mock("~/state/device", () => ({
+vi.mock(import("~/state/device"), async (original) => ({
+ ...(await original()),
useDeviceHubAccess: () => useSyncExternalStore(accessStore.subscribe, () => accessStore.value),
refreshDeviceHubAccess: () => accessStore.refresh(),
}));
let viewerMounts = 0;
let viewerUnmounts = 0;
-vi.mock("./DevicePhoneViewport", () => ({
- DevicePhoneViewport: function Viewer() {
+// The 3D phone frame needs WebGL; the test only cares whether it stays mounted.
+vi.mock(import("./DevicePhoneViewport"), async (original) => ({
+ ...(await original()),
+ DevicePhoneViewport: function Viewer(): React.ReactElement {
useEffect(() => {
viewerMounts++;
return () => {
viewerUnmounts++;
};
}, []);
- return null;
+ return <></>;
},
}));
import { DeviceStreamView } from "./DeviceStreamView";
-class Image extends EventTarget {
- src = "";
- naturalWidth = 0;
- naturalHeight = 0;
- removeAttribute(name: string) {
- if (name === "src") this.src = "";
+// MJPEG frames come from the device hub, so images keep their src without loading it and a
+// test publishes a frame by setting the natural size and firing "load".
+const imageSources = new WeakMap<HTMLImageElement, string>();
+const framedImages = new WeakSet<HTMLImageElement>();
+let images: HTMLImageElement[] = [];
+const srcDescriptor = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, "src")!;
+const naturalWidthDescriptor = Object.getOwnPropertyDescriptor(
+ HTMLImageElement.prototype,
+ "naturalWidth",
+)!;
+const naturalHeightDescriptor = Object.getOwnPropertyDescriptor(
+ HTMLImageElement.prototype,
+ "naturalHeight",
+)!;
+const removeAttribute = Element.prototype.removeAttribute;
+function stubImages() {
+ Object.defineProperty(HTMLImageElement.prototype, "src", {
+ configurable: true,
+ get(this: HTMLImageElement) {
+ return imageSources.get(this) ?? "";
+ },
+ set(this: HTMLImageElement, value: string) {
+ if (!images.includes(this)) images.push(this);
+ imageSources.set(this, value);
+ },
+ });
+ for (const name of ["naturalWidth", "naturalHeight"]) {
+ Object.defineProperty(HTMLImageElement.prototype, name, {
+ configurable: true,
+ get(this: HTMLImageElement) {
+ if (!framedImages.has(this)) return 0;
+ return name === "naturalWidth" ? 400 : 800;
+ },
+ });
}
+ Element.prototype.removeAttribute = function (this: Element, name: string) {
+ if (this instanceof HTMLImageElement && name === "src") imageSources.delete(this);
+ return removeAttribute.call(this, name);
+ };
}
-let renderer: ReactTestRenderer | undefined;
+function restoreImages() {
+ Object.defineProperty(HTMLImageElement.prototype, "src", srcDescriptor);
+ Object.defineProperty(HTMLImageElement.prototype, "naturalWidth", naturalWidthDescriptor);
+ Object.defineProperty(HTMLImageElement.prototype, "naturalHeight", naturalHeightDescriptor);
+ Element.prototype.removeAttribute = removeAttribute;
+}
+async function publishFrame(image: HTMLImageElement) {
+ framedImages.add(image);
+ await act(async () => image.dispatchEvent(new Event("load")));
+}
+let root: Root;
+let container: HTMLDivElement;
let primes = 0;
beforeEach(() => {
primes = 0;
viewerMounts = 0;
viewerUnmounts = 0;
+ images = [];
+ stubImages();
+ container = document.createElement("div");
+ container.style.cssText = "width: 400px; height: 800px; display: flex";
+ document.body.append(container);
+ root = createRoot(container);
});
afterEach(async () => {
- await act(async () => renderer?.unmount());
- renderer = undefined;
+ await act(async () => root.unmount());
+ container.remove();
+ restoreImages();
vi.useRealTimers();
vi.unstubAllGlobals();
});
async function setup(h264 = false) {
vi.useFakeTimers();
- vi.stubGlobal("window", globalThis);
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
let videoBody: ReadableStreamDefaultController<Uint8Array> | undefined;
let output: VideoFrameOutputCallback | undefined;
@@ -80,6 +132,15 @@ async function setup(h264 = false) {
},
);
vi.stubGlobal("EncodedVideoChunk", vi.fn());
+ } else {
+ // Without WebCodecs the iOS client streams MJPEG.
+ const videoDecoder = Object.getOwnPropertyDescriptor(globalThis, "VideoDecoder");
+ if (videoDecoder) {
+ Reflect.deleteProperty(globalThis, "VideoDecoder");
+ onTestFinished(() => {
+ Object.defineProperty(globalThis, "VideoDecoder", videoDecoder);
+ });
+ }
}
vi.stubGlobal("fetch", (url: string, init: RequestInit) => {
if (url.endsWith("stream.avcc")) {
@@ -111,14 +172,6 @@ async function setup(h264 = false) {
close() {}
},
);
- vi.stubGlobal(
- "ResizeObserver",
- class {
- observe() {}
- disconnect() {}
- },
- );
- const images: Image[] = [];
const view = (visible: boolean) => (
<DeviceStreamView
hostId="local"
@@ -129,22 +182,7 @@ async function setup(h264 = false) {
allowPhoneView={h264}
/>
);
- await act(async () => {
- renderer = create(view(true), {
- createNodeMock: (node) => {
- if (node.type === "img") {
- const image = new Image();
- images.push(image);
- return image;
- }
- return {
- getContext: () => ({ drawImage() {} }),
- style: { setProperty() {} },
- getBoundingClientRect: () => ({ width: 400, height: 800 }),
- };
- },
- });
- });
+ await act(async () => root.render(view(true)));
return {
images,
view,
@@ -160,19 +198,29 @@ async function setup(h264 = false) {
videoBody?.enqueue(new Uint8Array([0, 0, 0, 5, 1, 1, 0x64, 0, 0x1f]));
},
frame() {
- output?.({ displayWidth: 400, displayHeight: 800, close() {} } as VideoFrame);
+ const source = new OffscreenCanvas(400, 800);
+ source.getContext("2d")!.fillRect(0, 0, 400, 800);
+ output?.(new VideoFrame(source, { timestamp: 0 }));
},
};
}
+const alert = () => container.querySelector('[role="alert"]');
+const reconnect = () =>
+ act(async () =>
+ [...container.querySelectorAll("button")]
+ .find((button) => button.textContent?.includes("Reconnect"))!
+ .click(),
+ );
+
it("removes MJPEG requests while hidden and reconnects when shown", async () => {
const { images, view } = await setup();
expect(images[0]!.src).toContain("stream.mjpeg");
- await act(async () => renderer!.update(view(false)));
- expect(renderer!.root.findAllByType("img")).toHaveLength(0);
+ await act(async () => root.render(view(false)));
+ expect(container.querySelectorAll("img")).toHaveLength(0);
expect(images[0]!.src).toBe("");
expect(vi.getTimerCount()).toBe(0);
- await act(async () => renderer!.update(view(true)));
+ await act(async () => root.render(view(true)));
expect(images.at(-1)!.src).toContain("stream.mjpeg");
});
@@ -181,20 +229,14 @@ it("offers Reconnect after the shared timeout and receives a frame after retry w
await act(async () => {
await vi.advanceTimersByTimeAsync(15_000);
});
- expect(
- renderer!.root.findByProps({ role: "alert" }).findByType("span").children.join(""),
- ).toContain("No video");
+ expect(alert()?.textContent).toContain("No video");
expect(images[0]!.src).toBe("");
- await act(async () => renderer!.root.findByType("button").props.onClick());
- expect(renderer!.root.findAllByProps({ role: "alert" })).toHaveLength(0);
+ await reconnect();
+ expect(alert()).toBeNull();
expect(images[1]!.src).toContain("stream.mjpeg");
- await act(async () => {
- images[1]!.naturalWidth = 400;
- images[1]!.naturalHeight = 800;
- images[1]!.dispatchEvent(new Event("load"));
- });
- expect(renderer!.root.findAllByProps({ role: "status" })).toHaveLength(0);
- expect(renderer!.root.findAllByType("button")).toHaveLength(0);
+ await publishFrame(images[1]!);
+ expect(container.querySelector('[role="status"]')).toBeNull();
+ expect(container.querySelectorAll("button")).toHaveLength(0);
expect(vi.getTimerCount()).toBe(0);
});
@@ -204,7 +246,7 @@ it("starts exactly one new stream per Reconnect press", async () => {
await vi.advanceTimersByTimeAsync(15_000);
});
expect(primes).toBe(1);
- await act(async () => renderer!.root.findByType("button").props.onClick());
+ await reconnect();
expect(primes).toBe(2);
});
@@ -225,7 +267,7 @@ it("keeps the 3D viewer mounted across iOS video recovery and releases it when h
});
await act(async () => frame());
expect(viewerMounts).toBe(1);
- await act(async () => renderer!.update(view(false)));
+ await act(async () => root.render(view(false)));
expect(viewerUnmounts).toBe(1);
expect(vi.getTimerCount()).toBe(0);
});
diff --git a/apps/web/src/components/device/useDeviceControls.test.tsx b/apps/web/src/components/device/useDeviceControls.browser.test.tsx
similarity index 76%
rename from apps/web/src/components/device/useDeviceControls.test.tsx
rename to apps/web/src/components/device/useDeviceControls.browser.test.tsx
index cadc0c7852e..cd5df4f7c06 100644
--- a/apps/web/src/components/device/useDeviceControls.test.tsx
+++ b/apps/web/src/components/device/useDeviceControls.browser.test.tsx
@@ -1,9 +1,9 @@
import { EnvironmentId, type DeviceDetail, type DeviceSummary } from "@t3tools/contracts";
import type { DeviceHubAccess } from "@t3tools/client-runtime/device/hub-access";
+import * as Cause from "effect/Cause";
import { act, useEffect } 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";
-import { useDeviceControls, type DeviceControls } from "./useDeviceControls";
type Result = { _tag: "Success"; value: DeviceDetail } | { _tag: "Failure"; cause: unknown };
const { read, action, subscribe } = vi.hoisted(() => ({
@@ -12,13 +12,22 @@ const { read, action, subscribe } = vi.hoisted(() => ({
subscribe:
vi.fn<(_target: unknown, onChange: (app: { id: string } | null) => void) => () => void>(),
}));
-vi.mock("~/state/device", () => ({ deviceEnvironment: { detail: "detail", action: "action" } }));
-vi.mock("~/state/use-atom-command", () => ({
- useAtomCommand: (command: string) => (command === "detail" ? read : action),
+vi.mock(import("~/state/use-atom-command"), async (original) => {
+ const { deviceEnvironment } = await import("~/state/device");
+ return {
+ ...(await original()),
+ useAtomCommand: ((command: unknown) =>
+ command === deviceEnvironment.detail ? read : action) as never,
+ };
+});
+vi.mock(import("./deviceHubApi"), async (original) => ({
+ ...(await original()),
+ subscribeDeviceForeground: subscribe as never,
}));
-vi.mock("~/state/query", () => ({ formatEnvironmentQueryError: () => "Device action failed" }));
-vi.mock("./deviceHubApi", () => ({ subscribeDeviceForeground: subscribe }));
+import { useDeviceControls, type DeviceControls } from "./useDeviceControls";
+
+const offline = Cause.fail(new Error("Device offline"));
const device: DeviceSummary = {
hostId: "remote",
id: "phone",
@@ -45,7 +54,7 @@ function deferred() {
});
return { promise, resolve };
}
-let renderer: ReactTestRenderer | undefined;
+let root: Root;
let controls: DeviceControls;
function Probe({ visible, access = null }: { visible: boolean; access?: DeviceHubAccess | null }) {
const next = useDeviceControls({
@@ -66,14 +75,15 @@ beforeEach(() => {
subscribe.mockReset();
subscribe.mockReturnValue(() => {});
read.mockResolvedValue(snapshot("light"));
+ root = createRoot(document.createElement("div"));
});
afterEach(async () => {
- await act(async () => renderer?.unmount());
+ await act(async () => root.unmount());
vi.unstubAllGlobals();
});
async function mount() {
await act(async () => {
- renderer = create(<Probe visible />);
+ root.render(<Probe visible />);
});
}
@@ -94,10 +104,10 @@ it("serializes rapid actions and retains confirmed settings while pending or aft
await pending;
});
expect(controls.detail?.settings.appearance).toBe("dark");
- action.mockResolvedValueOnce({ _tag: "Failure", cause: "offline" });
+ action.mockResolvedValueOnce({ _tag: "Failure", cause: offline });
await act(async () => controls.act({ type: "setAppearance", value: "light" }));
expect(controls.detail?.settings.appearance).toBe("dark");
- expect(controls.error).toBe("Device action failed");
+ expect(controls.error).toBe("Device offline");
expect(controls.disabled).toBe(false);
});
@@ -109,9 +119,9 @@ it("serializes host actions across hide/reopen and discards detached results", a
await act(async () => {
pending = controls.act({ type: "setAppearance", value: "dark" });
});
- await act(async () => renderer!.update(<Probe visible={false} />));
+ await act(async () => root.render(<Probe visible={false} />));
expect(controls.disabled).toBe(true);
- await act(async () => renderer!.update(<Probe visible />));
+ await act(async () => root.render(<Probe visible />));
await act(async () => controls.act({ type: "setAppearance", value: "light" }));
expect(action).toHaveBeenCalledOnce();
expect(controls.disabled).toBe(true);
@@ -143,36 +153,36 @@ it("keeps actions disabled when settings cannot be confirmed after a detached co
await act(async () => {
pending = controls.act({ type: "setAppearance", value: "dark" });
});
- await act(async () => renderer!.update(<Probe visible={false} />));
- await act(async () => renderer!.update(<Probe visible />));
- read.mockResolvedValueOnce({ _tag: "Failure", cause: "offline" });
+ await act(async () => root.render(<Probe visible={false} />));
+ await act(async () => root.render(<Probe visible />));
+ read.mockResolvedValueOnce({ _tag: "Failure", cause: offline });
await act(async () => {
response.resolve(snapshot("dark"));
await pending;
});
expect(controls.detail).toBeNull();
expect(controls.disabled).toBe(true);
- expect(controls.error).toBe("Device action failed");
+ expect(controls.error).toBe("Device offline");
await act(async () => controls.act({ type: "setAppearance", value: "light" }));
expect(action).toHaveBeenCalledOnce();
- await act(async () => renderer!.update(<Probe visible={false} />));
- await act(async () => renderer!.update(<Probe visible />));
+ await act(async () => root.render(<Probe visible={false} />));
+ await act(async () => root.render(<Probe visible />));
expect(controls.disabled).toBe(false);
expect(controls.error).toBeNull();
});
it("disables stale settings after a failed reopen read and recovers on a successful read", async () => {
await mount();
- await act(async () => renderer!.update(<Probe visible={false} />));
- read.mockResolvedValueOnce({ _tag: "Failure", cause: "offline" });
- await act(async () => renderer!.update(<Probe visible />));
+ await act(async () => root.render(<Probe visible={false} />));
+ read.mockResolvedValueOnce({ _tag: "Failure", cause: offline });
+ await act(async () => root.render(<Probe visible />));
expect(controls.detail).toBeNull();
expect(controls.disabled).toBe(true);
- expect(controls.error).toBe("Device action failed");
+ expect(controls.error).toBe("Device offline");
await act(async () => controls.act({ type: "setAppearance", value: "dark" }));
expect(action).not.toHaveBeenCalled();
- await act(async () => renderer!.update(<Probe visible={false} />));
- await act(async () => renderer!.update(<Probe visible />));
+ await act(async () => root.render(<Probe visible={false} />));
+ await act(async () => root.render(<Probe visible />));
expect(controls.detail?.settings.appearance).toBe("light");
expect(controls.disabled).toBe(false);
expect(controls.error).toBeNull();
@@ -180,10 +190,10 @@ it("disables stale settings after a failed reopen read and recovers on a success
it("does not let an older refresh overwrite a newer confirmed action", async () => {
await mount();
- await act(async () => renderer!.update(<Probe visible={false} />));
+ await act(async () => root.render(<Probe visible={false} />));
const refresh = deferred();
read.mockReturnValueOnce(refresh.promise);
- await act(async () => renderer!.update(<Probe visible />));
+ await act(async () => root.render(<Probe visible />));
action.mockResolvedValueOnce(snapshot("dark"));
await act(async () => controls.act({ type: "setAppearance", value: "dark" }));
await act(async () => {
@@ -209,17 +219,17 @@ it.each(["hidden", "access renewed"] as const)(
value: { ...detail.value, foregroundApp: { id: "snapshot.app" } },
});
await act(async () => {
- renderer = create(<Probe visible access={access} />);
+ root.render(<Probe visible access={access} />);
});
const oldEvent = subscribe.mock.calls[0]![1];
await act(async () => oldEvent({ id: "previous.live.app" }));
expect(controls.foregroundApp?.id).toBe("previous.live.app");
if (restart === "hidden") {
- await act(async () => renderer!.update(<Probe visible={false} access={access} />));
- await act(async () => renderer!.update(<Probe visible access={access} />));
+ await act(async () => root.render(<Probe visible={false} access={access} />));
+ await act(async () => root.render(<Probe visible access={access} />));
} else {
await act(async () =>
- renderer!.update(<Probe visible access={{ ...access, query: { ticket: "renewed" } }} />),
+ root.render(<Probe visible access={{ ...access, query: { ticket: "renewed" } }} />),
);
}
expect(controls.foregroundApp?.id).toBe("snapshot.app");
diff --git a/apps/web/src/components/diffs/DiffCommentAnnotation.test.tsx b/apps/web/src/components/diffs/DiffCommentAnnotation.test.tsx
deleted file mode 100644
index 5ec3b21db07..00000000000
--- a/apps/web/src/components/diffs/DiffCommentAnnotation.test.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it, vi } from "vite-plus/test";
-
-import { DiffCommentAnnotation } from "./DiffCommentAnnotation";
-
-const callbacks = {
- onTextChange: vi.fn(),
- onCancel: vi.fn(),
- onComment: vi.fn(),
- onDelete: vi.fn(),
-};
-
-describe("DiffCommentAnnotation", () => {
- it("renders the shared draft composer directly in the selected diff", () => {
- const markup = renderToStaticMarkup(
- <DiffCommentAnnotation kind="draft" rangeLabel="+78" text="" {...callbacks} />,
- );
-
- expect(markup).toContain("font-sans");
- expect(markup).not.toContain("chat-composer-glass");
- expect(markup).not.toContain("font-mono");
- expect(markup).not.toContain("Local comment");
- expect(markup).not.toContain("on +78");
- expect(markup).toContain("⌘/Ctrl Enter to send");
- expect(markup).toContain("Add a comment…");
- expect(markup).toContain(">Comment</button>");
- expect(markup).toContain("autofocus");
- expect(markup).toMatch(/<span[^>]*data-size="sm"[^>]*data-slot="textarea-control"/);
- });
-
- it("lets a pull-request diff configure actions without replacing the composer", () => {
- const markup = renderToStaticMarkup(
- <DiffCommentAnnotation
- kind="draft"
- rangeLabel="src/app.ts:4"
- text=""
- {...callbacks}
- submitLabel="Add to review"
- secondaryAction={{
- label: "Add to agent",
- onAction: vi.fn(),
- }}
- />,
- );
-
- expect(markup).toContain("Add a comment…");
- expect(markup).toContain(">Add to review</button>");
- expect(markup.match(/<button[^>]*disabled[^>]*>Add to review<\/button>/)).not.toBeNull();
- expect(markup.match(/<button[^>]*disabled[^>]*>Add to agent<\/button>/)).not.toBeNull();
- });
-
- it("renders a saved comment without a nested card or redundant range label", () => {
- const markup = renderToStaticMarkup(
- <DiffCommentAnnotation
- kind="comment"
- rangeLabel="+78"
- text="Please keep this branch explicit."
- {...callbacks}
- />,
- );
-
- expect(markup).toContain("font-sans");
- expect(markup).not.toContain("chat-composer-glass");
- expect(markup).not.toContain("on +78");
- expect(markup).toContain("Please keep this branch explicit.");
- expect(markup).toContain('aria-label="Delete comment"');
- expect(markup).toContain("border-s-2");
- expect(markup).toContain("bg-primary/[0.045]");
- expect(markup).toContain("lucide-message-circle");
- });
-
- it("renders draft text owned by the annotation wrapper", () => {
- const markup = renderToStaticMarkup(
- <DiffCommentAnnotation
- kind="draft"
- rangeLabel="+78"
- text="Keep this unsaved draft"
- {...callbacks}
- />,
- );
-
- expect(markup).toContain("Keep this unsaved draft");
- });
-});
diff --git a/apps/web/src/components/diffs/DiffFileTree.test.tsx b/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx
similarity index 74%
rename from apps/web/src/components/diffs/DiffFileTree.test.tsx
rename to apps/web/src/components/diffs/DiffFileTree.browser.test.tsx
index 826d1096099..1e5814cef2e 100644
--- a/apps/web/src/components/diffs/DiffFileTree.test.tsx
+++ b/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx
@@ -1,8 +1,7 @@
import type { CodeViewScrollTarget } from "@pierre/diffs";
import type { FileTree as FileTreeModel } from "@pierre/trees";
-import { FileTree } from "@pierre/trees/react";
-import { act, type MouseEvent, type ReactNode } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
+import { act, type ComponentProps } from "react";
+import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import type { FileDiffMetadata } from "@pierre/diffs";
@@ -11,12 +10,19 @@ import { DiffFileTree, type DiffFileTreeEntry } from "./DiffFileTree";
import { diffFileTreeEntries } from "./diffFileTree.logic";
import { useCodeViewFileReveal } from "./useCodeViewFileReveal";
-vi.mock("../../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
-vi.mock("../ui/tooltip", () => ({
- Tooltip: ({ children }: { children: ReactNode }) => children,
- TooltipTrigger: ({ render }: { render: ReactNode }) => render,
- TooltipPopup: () => null,
-}));
+const captured = vi.hoisted(() => ({ model: null as unknown }));
+// Read the tree model the component builds, so tests can assert its selection and expansion.
+vi.mock(import("@pierre/trees/react"), async (original) => {
+ const actual = await original();
+ const RealFileTree = actual.FileTree;
+ return {
+ ...actual,
+ FileTree: ((props: ComponentProps<typeof RealFileTree>) => {
+ captured.model = props.model;
+ return <RealFileTree {...props} />;
+ }) as typeof RealFileTree,
+ };
+});
const entries: DiffFileTreeEntry[] = [
{ path: "01-tall.ts", status: "modified" },
@@ -24,16 +30,9 @@ const entries: DiffFileTreeEntry[] = [
{ path: "03-medium.ts", status: "modified" },
];
-class TreeRow {
- constructor(readonly path: string) {}
-
- getAttribute(name: string) {
- return name === "data-item-path" ? this.path : null;
- }
-}
-
describe("diff tree file activation", () => {
- let renderer: ReactTestRenderer | undefined;
+ let root: Root | undefined;
+ let container: HTMLDivElement;
const targets: CodeViewScrollTarget[] = [];
const viewer = {
getInstance: () => viewer,
@@ -58,56 +57,48 @@ describe("diff tree file activation", () => {
);
}
- const model = (): FileTreeModel => renderer!.root.findByType(FileTree).props.model;
+ const model = (): FileTreeModel => captured.model as FileTreeModel;
async function mount(props: Parameters<typeof Panel>[0] = {}) {
- await act(async () => {
- renderer = create(<Panel {...props} />);
- });
+ root ??= createRoot(container);
+ await act(async () => root!.render(<Panel {...props} />));
+ }
+
+ function row(path: string): HTMLElement {
+ const host = container.querySelector("file-tree-container");
+ const element = (host?.shadowRoot ?? container).querySelector<HTMLElement>(
+ `[data-item-path="${CSS.escape(path)}"]`,
+ );
+ expect(element, `row ${path}`).not.toBeNull();
+ return element!;
}
- async function activate(path: string, modifiers: Partial<MouseEvent<HTMLElement>> = {}) {
- const event = {
- button: 0,
- ctrlKey: false,
- metaKey: false,
- shiftKey: false,
- altKey: false,
- defaultPrevented: false,
- nativeEvent: { composedPath: () => [{}, new TreeRow(path), {}] },
- ...modifiers,
- } as MouseEvent<HTMLElement>;
+ async function activate(path: string, modifiers: MouseEventInit = {}) {
await act(async () => {
- renderer!.root
- .find((node) => String(node.type) === "file-tree-container")
- .props.onClickCapture?.(event);
- const tree = model();
- const item = tree.getItem(path)!;
- if (event.ctrlKey || event.metaKey) {
- item.toggleSelect();
- } else {
- for (const selected of tree.getSelectedPaths()) {
- if (selected !== path) tree.getItem(selected)?.deselect();
- }
- item.select();
- }
- item.focus();
- if ("toggle" in item && !event.ctrlKey && !event.metaKey && !event.shiftKey) item.toggle();
+ row(path).dispatchEvent(
+ new MouseEvent("click", {
+ bubbles: true,
+ composed: true,
+ button: 0,
+ detail: 1,
+ ...modifiers,
+ }),
+ );
});
}
beforeEach(() => {
targets.length = 0;
- vi.useFakeTimers();
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- vi.stubGlobal("HTMLElement", TreeRow);
+ container = document.createElement("div");
+ container.style.cssText = "display: flex; flex-direction: column; width: 320px; height: 480px";
+ document.body.append(container);
});
afterEach(async () => {
- await act(async () => renderer?.unmount());
- renderer = undefined;
- vi.runOnlyPendingTimers();
- vi.useRealTimers();
+ await act(async () => root?.unmount());
+ root = undefined;
+ container.remove();
vi.unstubAllGlobals();
});
@@ -202,7 +193,7 @@ describe("diff tree file activation", () => {
if (!("collapse" in initialFolder)) throw new Error("Expected the directory handle");
await act(async () => initialFolder.collapse());
await act(async () => {
- renderer!.update(<Panel files={[files[1]!, files[0]!]} />);
+ root!.render(<Panel files={[files[1]!, files[0]!]} />);
});
const folder = model().getItem("src/features/")!;
if (!("isExpanded" in folder)) throw new Error("Expected the directory handle");
@@ -216,7 +207,7 @@ describe("diff tree file activation", () => {
await activate("02-short.ts");
expect(targets).toHaveLength(1);
await act(async () => {
- renderer!.update(<Panel selectedPath="03-medium.ts" />);
+ root!.render(<Panel selectedPath="03-medium.ts" />);
});
expect(model().getSelectedPaths()).toEqual(["03-medium.ts"]);
expect(targets).toHaveLength(1);
diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
new file mode 100644
index 00000000000..14a24dbc9c6
--- /dev/null
+++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
@@ -0,0 +1,117 @@
+import { EnvironmentId } from "@t3tools/contracts";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+const { refresh } = vi.hoisted(() => ({ refresh: vi.fn<() => Promise<string | null>>() }));
+
+vi.mock(import("~/assets/assetUrls"), async (original) => ({
+ ...(await original()),
+ useAssetUrlRefresh: () => refresh,
+}));
+// The real source view highlights through a worker pool; the text it receives is what matters here.
+vi.mock(import("./ReadOnlySourcePreview"), async (original) => ({
+ ...(await original()),
+ default: ({ text }: { text: string }) => <pre>{text}</pre>,
+}));
+
+import { AttachmentFilePreview } from "./AttachmentFilePreview";
+
+describe("attachment HTML preview recovery", () => {
+ const originalUrl = "data:text/html,original";
+ const renewedUrl = "data:text/html,renewed";
+ let now = 0;
+ let root: Root;
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ now = 0;
+ vi.spyOn(Date, "now").mockImplementation(() => now);
+ refresh.mockReset().mockResolvedValueOnce(originalUrl).mockResolvedValue(renewedUrl);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => new Response("<p>Captured HTML</p>")),
+ );
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ });
+
+ afterEach(async () => {
+ await act(async () => root.unmount());
+ container.remove();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ const openRemote = () =>
+ act(async () =>
+ root.render(
+ <AttachmentFilePreview
+ name="document.html"
+ mimeType="text/html"
+ sizeBytes={100}
+ asset={{ environmentId: EnvironmentId.make("test-environment"), attachmentId: "html" }}
+ />,
+ ),
+ );
+
+ const toggleMode = async (label: string) => {
+ const button = container.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);
+ expect(button, label).not.toBeNull();
+ await act(async () => button!.click());
+ };
+ const alert = () => container.querySelector('[role="alert"]');
+
+ it("keeps a renewed URL for subsequent rendered and source views", async () => {
+ await openRemote();
+ expect(container.querySelector("iframe")?.getAttribute("src")).toBe(originalUrl);
+ now = 61 * 60_000;
+ await toggleMode("Show HTML source");
+ expect(fetch).toHaveBeenCalledExactlyOnceWith(renewedUrl, expect.any(Object));
+ await vi.waitFor(() =>
+ expect(container.querySelector("pre")?.textContent).toBe("<p>Captured HTML</p>"),
+ );
+
+ await toggleMode("Show rendered page");
+ expect(container.querySelector("iframe")?.getAttribute("src")).toBe(renewedUrl);
+ await toggleMode("Show HTML source");
+ expect(refresh).toHaveBeenCalledTimes(2);
+ expect(vi.mocked(fetch).mock.calls.map(([url]) => url)).toEqual([renewedUrl, renewedUrl]);
+ });
+
+ it("does not fetch or mark an expired URL fresh when reauthorization is unavailable", async () => {
+ await openRemote();
+ now = 61 * 60_000;
+ refresh.mockResolvedValue(null);
+ await toggleMode("Show HTML source");
+ expect(fetch).not.toHaveBeenCalled();
+ expect(alert()?.textContent).toContain("Reconnect to the environment and try again.");
+
+ await toggleMode("Show rendered page");
+ await toggleMode("Show HTML source");
+ expect(refresh).toHaveBeenCalledTimes(3);
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it("can return to rendered HTML after local source decoding fails", async () => {
+ const file = new Blob([new Uint8Array([0x3c, 0x70, 0x3e, 0xe9])], { type: "text/html" });
+ await act(async () =>
+ root.render(
+ <AttachmentFilePreview
+ name="document.html"
+ mimeType="text/html"
+ sizeBytes={file.size}
+ file={file}
+ />,
+ ),
+ );
+ await toggleMode("Show HTML source");
+ await vi.waitFor(() => expect(alert()?.textContent).toContain("not UTF-8"));
+
+ await toggleMode("Show rendered page");
+ expect(alert()).toBeNull();
+ expect(container.querySelector("iframe")?.title).toBe("document.html");
+ });
+});
diff --git a/apps/web/src/components/files/AttachmentFilePreview.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.test.tsx
deleted file mode 100644
index 6bd25ce313e..00000000000
--- a/apps/web/src/components/files/AttachmentFilePreview.test.tsx
+++ /dev/null
@@ -1,133 +0,0 @@
-import { EnvironmentId } from "@t3tools/contracts";
-import { act, type ReactNode } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
-
-import { AttachmentFilePreview } from "./AttachmentFilePreview";
-
-const { refresh } = vi.hoisted(() => ({ refresh: vi.fn<() => Promise<string | null>>() }));
-
-vi.mock("~/assets/assetUrls", () => ({ useAssetUrlRefresh: () => refresh }));
-vi.mock("~/hooks/useCopyToClipboard", () => ({
- useCopyToClipboard: () => ({ copyToClipboard: vi.fn(), isCopied: false }),
-}));
-vi.mock("~/components/ui/toast", () => ({ toastManager: { add: vi.fn() } }));
-vi.mock("~/components/ChatMarkdown", () => ({ default: () => null }));
-vi.mock("~/components/ui/scroll-area", () => ({
- ScrollArea: ({ children }: { children: ReactNode }) => children,
-}));
-vi.mock("./ReadOnlySourcePreview", () => ({
- default: ({ text }: { text: string }) => <pre>{text}</pre>,
-}));
-vi.mock("./fileSurfaceChrome", () => ({
- FILE_SURFACE_SUBHEADER_CLASS: "",
- FileSurfaceAction: ({ label, onPress }: { label: string; onPress: () => void }) => (
- <button aria-label={label} onClick={onPress} />
- ),
- FileSurfaceFailure: ({ message }: { message: string }) => <div role="alert">{message}</div>,
- FileSurfaceLoading: () => <div role="status">Loading</div>,
- FileSurfaceNotice: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}));
-
-describe("attachment HTML preview recovery", () => {
- const originalUrl = "https://environment.test/original.html";
- const renewedUrl = "https://environment.test/renewed.html";
- let now = 0;
- let renderer: ReactTestRenderer;
-
- beforeEach(() => {
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- now = 0;
- vi.spyOn(Date, "now").mockImplementation(() => now);
- refresh.mockReset().mockResolvedValueOnce(originalUrl).mockResolvedValue(renewedUrl);
- vi.stubGlobal(
- "fetch",
- vi.fn(async () => new Response("<p>Captured HTML</p>")),
- );
- });
-
- afterEach(async () => {
- if (renderer) await act(() => renderer.unmount());
- vi.restoreAllMocks();
- vi.unstubAllGlobals();
- });
-
- const openRemote = async () => {
- await act(async () => {
- renderer = create(
- <AttachmentFilePreview
- name="document.html"
- mimeType="text/html"
- sizeBytes={100}
- asset={{ environmentId: EnvironmentId.make("test-environment"), attachmentId: "html" }}
- />,
- );
- });
- };
-
- const toggleMode = async (label: string) => {
- await act(async () => {
- renderer.root.findByProps({ "aria-label": label }).props.onClick();
- });
- };
-
- it("keeps a renewed URL for subsequent rendered and source views", async () => {
- await openRemote();
- now = 61 * 60_000;
- await toggleMode("Show HTML source");
- expect(fetch).toHaveBeenCalledExactlyOnceWith(renewedUrl, expect.any(Object));
-
- await toggleMode("Show rendered page");
- expect(renderer.root.findByType("iframe").props.src).toBe(renewedUrl);
- await toggleMode("Show HTML source");
- expect(refresh).toHaveBeenCalledTimes(2);
- expect(fetch).toHaveBeenCalledTimes(2);
- expect(vi.mocked(fetch).mock.calls.map(([url]) => url)).toEqual([renewedUrl, renewedUrl]);
- });
-
- it("does not fetch or mark an expired URL fresh when reauthorization is unavailable", async () => {
- await openRemote();
- now = 61 * 60_000;
- refresh.mockResolvedValue(null);
- await toggleMode("Show HTML source");
- expect(fetch).not.toHaveBeenCalled();
- expect(renderer.root.findByProps({ role: "alert" }).children).toEqual([
- "Reconnect to the environment and try again.",
- ]);
-
- await toggleMode("Show rendered page");
- await toggleMode("Show HTML source");
- expect(refresh).toHaveBeenCalledTimes(3);
- expect(fetch).not.toHaveBeenCalled();
- });
-
- it("can return to rendered HTML after local source decoding fails", async () => {
- const bytes = new Uint8Array([0x3c, 0x70, 0x3e, 0xe9]);
- const file = new Blob([bytes], { type: "text/html" });
- vi.spyOn(file, "stream").mockImplementation(
- () =>
- new ReadableStream({
- start: (controller) => {
- controller.enqueue(bytes);
- controller.close();
- },
- }),
- );
- await act(async () => {
- renderer = create(
- <AttachmentFilePreview
- name="document.html"
- mimeType="text/html"
- sizeBytes={file.size}
- file={file}
- />,
- );
- });
- await toggleMode("Show HTML source");
- expect(renderer.root.findByProps({ role: "alert" }).children.join("")).toContain("not UTF-8");
-
- await toggleMode("Show rendered page");
- expect(renderer.root.findAllByProps({ role: "alert" })).toHaveLength(0);
- expect(renderer.root.findByType("iframe").props.title).toBe("document.html");
- });
-});
diff --git a/apps/web/src/components/files/useFileSaveCoordinator.test.tsx b/apps/web/src/components/files/useFileSaveCoordinator.browser.test.tsx
similarity index 79%
rename from apps/web/src/components/files/useFileSaveCoordinator.test.tsx
rename to apps/web/src/components/files/useFileSaveCoordinator.browser.test.tsx
index 733c2c5f52d..7d8e230b56d 100644
--- a/apps/web/src/components/files/useFileSaveCoordinator.test.tsx
+++ b/apps/web/src/components/files/useFileSaveCoordinator.browser.test.tsx
@@ -1,7 +1,7 @@
import { EnvironmentId } from "@t3tools/contracts";
import { AsyncResult } from "effect/reactivity";
-import { act, StrictMode } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
+import { act, StrictMode, useEffect } from "react";
+import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
const { writeFile, confirmFile, readScope, getUnsavedFile } = vi.hoisted(() => ({
@@ -10,13 +10,17 @@ const { writeFile, confirmFile, readScope, getUnsavedFile } = vi.hoisted(() => (
readScope: vi.fn(),
getUnsavedFile: vi.fn(),
}));
-vi.mock("~/state/projects", () => ({ projectEnvironment: { writeFile: {} } }));
-vi.mock("~/state/session", () => ({
+vi.mock(import("~/state/session"), async (original) => ({
+ ...(await original()),
readEnvironmentScope: readScope,
useEnvironmentScope: readScope,
}));
-vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => writeFile }));
-vi.mock("./projectFilesQueryState", () => ({
+vi.mock(import("~/state/use-atom-command"), async (original) => ({
+ ...(await original()),
+ useAtomCommand: (() => writeFile) as never,
+}));
+vi.mock(import("./projectFilesQueryState"), async (original) => ({
+ ...(await original()),
confirmProjectFileQueryData: confirmFile,
getUnsavedProjectFileQueryData: getUnsavedFile,
}));
@@ -32,33 +36,40 @@ const defaultProps = {
relativePath: "file.txt",
onPendingChange,
};
-let renderer: ReactTestRenderer | null;
-
-function ChangeSource(_props: { onChange: (contents: string) => void }) {
- return null;
-}
+let root: Root | null;
+// The editor's change callback from the latest commit, as an editor would hold it.
+let latestChange: (contents: string) => void;
function FileSurface(props: Parameters<typeof useFileSaveCoordinator>[0]) {
const coordinator = useFileSaveCoordinator(props);
- return <ChangeSource onChange={(contents) => coordinator.change(contents)} />;
+ const onChange = (contents: string) => coordinator.change(contents);
+ useEffect(() => {
+ latestChange = onChange;
+ });
+ return null;
}
-function mount(props = defaultProps) {
- act(() => {
- renderer = create(
+async function render(props = defaultProps) {
+ root ??= createRoot(document.createElement("div"));
+ await act(async () =>
+ root!.render(
<StrictMode>
<FileSurface {...props} />
</StrictMode>,
- );
- });
+ ),
+ );
}
+const mount = render;
-function changeHandler(): (contents: string) => void {
- return renderer!.root.findByType(ChangeSource).props.onChange;
+async function unmountSurface() {
+ await act(async () => root!.unmount());
+ root = null;
}
+const changeHandler = () => latestChange;
+
beforeEach(() => {
- renderer = null;
+ root = null;
vi.useFakeTimers();
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
writeFile.mockReset().mockResolvedValue(AsyncResult.success(undefined));
@@ -69,14 +80,14 @@ beforeEach(() => {
});
afterEach(async () => {
- await act(async () => renderer?.unmount());
+ if (root) await unmountSurface();
vi.useRealTimers();
vi.unstubAllGlobals();
});
describe("file-save React lifecycle", () => {
it("persists editor model changes after StrictMode setup replay", async () => {
- mount();
+ await mount();
changeHandler()("AUDIT7907NATIVE\n");
expect(onPendingChange).toHaveBeenCalledWith("file.txt", true);
await vi.advanceTimersByTimeAsync(500);
@@ -94,7 +105,7 @@ describe("file-save React lifecycle", () => {
});
it("persists rendered Markdown task changes after StrictMode setup replay", async () => {
- mount({ ...defaultProps, relativePath: "README.md" });
+ await mount({ ...defaultProps, relativePath: "README.md" });
const nextContents = setMarkdownTaskChecked("- [ ] task\n", 2, true);
changeHandler()(nextContents);
await vi.advanceTimersByTimeAsync(500);
@@ -105,16 +116,10 @@ describe("file-save React lifecycle", () => {
});
it("keeps the debounce across rerenders of the same file", async () => {
- mount();
+ await mount();
changeHandler()("first");
await vi.advanceTimersByTimeAsync(300);
- act(() =>
- renderer!.update(
- <StrictMode>
- <FileSurface {...defaultProps} />
- </StrictMode>,
- ),
- );
+ await render(defaultProps);
changeHandler()("latest");
await vi.advanceTimersByTimeAsync(499);
expect(writeFile).not.toHaveBeenCalled();
@@ -124,11 +129,10 @@ describe("file-save React lifecycle", () => {
});
it("flushes on unmount and ignores a retired editor callback", async () => {
- mount();
+ await mount();
const retiredChange = changeHandler();
retiredChange("pending edit");
- await act(async () => renderer!.unmount());
- renderer = null;
+ await unmountSurface();
retiredChange("stale editor contents");
await vi.runAllTimersAsync();
expect(writeFile).toHaveBeenCalledTimes(1);
@@ -138,12 +142,11 @@ describe("file-save React lifecycle", () => {
it.each([false, true])(
"keeps edits pending after permission is revoked before a React update (unmount: %s)",
async (unmount) => {
- mount();
+ await mount();
changeHandler()("pending edit");
readScope.mockReturnValue(false);
if (unmount) {
- await act(async () => renderer!.unmount());
- renderer = null;
+ await unmountSurface();
}
await vi.runAllTimersAsync();
expect(writeFile).not.toHaveBeenCalled();
@@ -155,18 +158,12 @@ describe("file-save React lifecycle", () => {
it("resumes an unsaved draft when write permission returns after effect replay", async () => {
readScope.mockReturnValue(false);
getUnsavedFile.mockReturnValue({ contents: "pending draft" });
- mount();
+ await mount();
await vi.runAllTimersAsync();
expect(writeFile).not.toHaveBeenCalled();
readScope.mockReturnValue(true);
- act(() =>
- renderer!.update(
- <StrictMode>
- <FileSurface {...defaultProps} />
- </StrictMode>,
- ),
- );
+ await render(defaultProps);
await vi.advanceTimersByTimeAsync(500);
expect(writeFile).toHaveBeenCalledExactlyOnceWith({
environmentId,
@@ -177,7 +174,7 @@ describe("file-save React lifecycle", () => {
it("recovers an existing draft once after StrictMode setup replay", async () => {
getUnsavedFile.mockReturnValue({ contents: "reopened draft" });
- mount();
+ await mount();
await vi.runAllTimersAsync();
expect(writeFile).toHaveBeenCalledExactlyOnceWith({
environmentId,
@@ -191,17 +188,11 @@ describe("file-save React lifecycle", () => {
{ cwd: "/other-workspace" },
{ environmentId: EnvironmentId.make("other-environment") },
])("retires callbacks when the file identity changes: %j", async (change) => {
- mount();
+ await mount();
const retiredChange = changeHandler();
retiredChange("old file edit");
const nextProps = { ...defaultProps, ...change };
- act(() =>
- renderer!.update(
- <StrictMode>
- <FileSurface {...nextProps} />
- </StrictMode>,
- ),
- );
+ await render(nextProps);
retiredChange("stale editor contents");
changeHandler()("new file edit");
await vi.runAllTimersAsync();
@@ -222,11 +213,10 @@ describe("file-save React lifecycle", () => {
});
it("does not reactivate a retired callback when the same file mounts again", async () => {
- mount();
+ await mount();
const retiredChange = changeHandler();
- await act(async () => renderer!.unmount());
- renderer = null;
- mount();
+ await unmountSurface();
+ await mount();
retiredChange("stale contents");
changeHandler()("current contents");
await vi.runAllTimersAsync();
diff --git a/apps/web/src/components/preview/PreviewEmptyState.browser.test.tsx b/apps/web/src/components/preview/PreviewEmptyState.browser.test.tsx
new file mode 100644
index 00000000000..a00a79bbf0d
--- /dev/null
+++ b/apps/web/src/components/preview/PreviewEmptyState.browser.test.tsx
@@ -0,0 +1,113 @@
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+import type { PreviewableServer } from "./useDiscoveredLocalServers";
+
+const mocks = vi.hoisted(() => ({ servers: [] as PreviewableServer[] }));
+
+vi.mock(import("./useDiscoveredLocalServers"), async (original) => ({
+ ...(await original()),
+ useDiscoveredLocalServers: () => mocks.servers,
+}));
+
+import { PreviewEmptyState } from "./PreviewEmptyState";
+
+const environmentId = EnvironmentId.make("env-1");
+const threadRef = { environmentId, threadId: ThreadId.make("thread-1") };
+const onOpenUrl = vi.fn();
+const onRemoveRecent = vi.fn();
+
+let root: Root;
+let container: HTMLDivElement;
+
+function server(port: number): PreviewableServer {
+ return {
+ host: "localhost",
+ port,
+ url: `http://localhost:${port}`,
+ requestedUrl: `http://localhost:${port}`,
+ processName: "node",
+ pid: 1,
+ terminal: null,
+ source: "scanner",
+ } as PreviewableServer;
+}
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ vi.clearAllMocks();
+ mocks.servers = [];
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+});
+
+async function render(
+ recentEntries: Array<{ url: string; lastVisitedAt: number; title?: string }>,
+) {
+ await act(async () =>
+ root.render(
+ <PreviewEmptyState
+ threadRef={threadRef}
+ environmentId={environmentId}
+ recentEntries={recentEntries}
+ onRemoveRecent={onRemoveRecent}
+ onOpenUrl={onOpenUrl}
+ />,
+ ),
+ );
+}
+
+function button(name: string) {
+ const match = [...container.querySelectorAll("button")].find(
+ (element) => element.getAttribute("aria-label") === name || element.textContent?.includes(name),
+ );
+ expect(match, `button ${name}`).toBeDefined();
+ return match!;
+}
+
+describe("PreviewEmptyState", () => {
+ it("lists a recent entry and a live server matching its host:port, and opens or forgets entries", async () => {
+ mocks.servers = [server(5173)];
+ await render([
+ { url: "https://myapp.test/admin#users", lastVisitedAt: Date.now(), title: "Admin" },
+ { url: "http://localhost:5173/", lastVisitedAt: Date.now(), title: "Recent Local" },
+ ]);
+ const text = container.textContent;
+ expect(text).toContain("Recently used");
+ expect(text).toContain("Local servers");
+ expect(text).toContain("Recent Local");
+ expect(text).toContain("node");
+
+ await act(async () => button("Admin").click());
+ expect(onOpenUrl).toHaveBeenCalledExactlyOnceWith("https://myapp.test/admin#users");
+
+ await act(async () => button("Remove myapp.test/admin#users from history").click());
+ expect(onRemoveRecent).toHaveBeenCalledExactlyOnceWith("https://myapp.test/admin#users");
+ });
+
+ it("shows only the recents group when no servers are found", async () => {
+ await render([{ url: "https://myapp.test/", lastVisitedAt: 0 }]);
+ expect(container.textContent).toContain("Recently used");
+ expect(container.textContent).not.toContain("Local servers");
+ });
+
+ it("keeps the original empty state when both groups are empty", async () => {
+ await render([]);
+ expect(container.textContent).toContain("No preview yet");
+ });
+
+ it("shows an entry with an out-of-range lastVisitedAt instead of crashing", async () => {
+ await render([{ url: "https://myapp.test/", lastVisitedAt: 1e20 }]);
+ expect(container.textContent).toContain("myapp.test");
+ button("Remove myapp.test from history");
+ });
+});
diff --git a/apps/web/src/components/preview/PreviewEmptyState.test.tsx b/apps/web/src/components/preview/PreviewEmptyState.test.tsx
deleted file mode 100644
index 0f9da0fdb3b..00000000000
--- a/apps/web/src/components/preview/PreviewEmptyState.test.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-import { EnvironmentId, ThreadId } from "@t3tools/contracts";
-import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it, vi } from "vite-plus/test";
-
-const mocks = vi.hoisted(() => ({
- servers: [] as Array<{
- host: string;
- port: number;
- url: string;
- requestedUrl: string;
- processName: string | null;
- pid: number | null;
- terminal: null;
- source: "scanner";
- }>,
-}));
-
-vi.mock("./useDiscoveredLocalServers", () => ({
- useDiscoveredLocalServers: () => mocks.servers,
-}));
-vi.mock("./PreviewFaviconIcon", () => ({
- PreviewFaviconIcon: () => <span data-favicon-icon />,
-}));
-
-import { PreviewEmptyState } from "./PreviewEmptyState";
-
-const environmentId = EnvironmentId.make("env-1");
-const threadRef = { environmentId, threadId: ThreadId.make("thread-1") };
-
-function server(port: number) {
- return {
- host: "localhost",
- port,
- url: `http://localhost:${port}`,
- requestedUrl: `http://localhost:${port}`,
- processName: "node",
- pid: 1,
- terminal: null,
- source: "scanner" as const,
- };
-}
-
-function render(recentEntries: Array<{ url: string; lastVisitedAt: number; title?: string }>) {
- return renderToStaticMarkup(
- <PreviewEmptyState
- threadRef={threadRef}
- environmentId={environmentId}
- recentEntries={recentEntries}
- onRemoveRecent={() => undefined}
- onOpenUrl={() => undefined}
- />,
- );
-}
-
-describe("PreviewEmptyState", () => {
- it("renders a history entry in both groups when its host:port matches a live server", () => {
- mocks.servers = [server(5173)];
- const html = render([
- { url: "https://myapp.test/admin#users", lastVisitedAt: Date.now(), title: "Admin" },
- { url: "http://localhost:5173/", lastVisitedAt: Date.now(), title: "Recent Local" },
- ]);
- expect(html).toContain("Recently used");
- expect(html).toContain("Local servers");
- expect(html).toContain("myapp.test/admin#users");
- expect(html).toContain("Admin");
- expect(html).toContain("Recent Local");
- expect(html).toContain("node");
- });
-
- it("renders only the recents group when no servers are found", () => {
- mocks.servers = [];
- const html = render([{ url: "https://myapp.test/", lastVisitedAt: 0 }]);
- expect(html).toContain("Recently used");
- expect(html).not.toContain("Local servers");
- });
-
- it("keeps the original empty state when both groups are empty", () => {
- mocks.servers = [];
- const html = render([]);
- expect(html).toContain("No preview yet");
- });
-
- it("renders an out-of-range lastVisitedAt entry without throwing", () => {
- mocks.servers = [];
- let html = "";
- expect(() => {
- html = render([{ url: "https://myapp.test/", lastVisitedAt: 1e20 }]);
- }).not.toThrow();
- expect(html).toContain("myapp.test");
- expect(html).toContain("Remove");
- });
-});
diff --git a/apps/web/src/components/preview/PreviewFaviconIcon.browser.test.tsx b/apps/web/src/components/preview/PreviewFaviconIcon.browser.test.tsx
new file mode 100644
index 00000000000..010f4d2438a
--- /dev/null
+++ b/apps/web/src/components/preview/PreviewFaviconIcon.browser.test.tsx
@@ -0,0 +1,49 @@
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
+
+import { FaviconImage } from "./PreviewFaviconIcon";
+
+const GIF = "data:image/gif;base64,R0lGODlhAQABAAAAACw=";
+const captured = `${GIF}#captured`;
+const remote = `${GIF}#remote`;
+
+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(async () => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+});
+
+const image = () => container.querySelector("img");
+const failImage = () => act(async () => image()!.dispatchEvent(new Event("error")));
+
+it("falls through failed favicon sources and retries when the source list changes", async () => {
+ await act(async () =>
+ root.render(<FaviconImage sources={[captured, remote]} fallback={<span>fallback</span>} />),
+ );
+ expect(image()?.getAttribute("src")).toBe(captured);
+
+ await failImage();
+ expect(image()?.getAttribute("src")).toBe(remote);
+
+ await failImage();
+ expect(image()).toBeNull();
+ expect(container.textContent).toBe("fallback");
+
+ await act(async () =>
+ root.render(
+ <FaviconImage sources={[captured, `${GIF}#new-icon`]} fallback={<span>fallback</span>} />,
+ ),
+ );
+ expect(image()?.getAttribute("src")).toBe(captured);
+});
diff --git a/apps/web/src/components/preview/PreviewFaviconIcon.test.tsx b/apps/web/src/components/preview/PreviewFaviconIcon.test.tsx
deleted file mode 100644
index 5ab8552b36f..00000000000
--- a/apps/web/src/components/preview/PreviewFaviconIcon.test.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { act } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
-import { afterEach, expect, it, vi } from "vite-plus/test";
-
-vi.mock("~/browserFaviconStore", () => ({ useFaviconForThreadUrl: () => null }));
-
-import { FaviconImage } from "./PreviewFaviconIcon";
-
-let renderer: ReactTestRenderer | undefined;
-
-afterEach(async () => {
- await act(async () => renderer?.unmount());
- vi.unstubAllGlobals();
-});
-
-it("falls through failed favicon sources and retries when the source list changes", async () => {
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- const captured = "data:image/png;base64,AAAA";
- const remote = "https://public.example/icon";
- await act(async () => {
- renderer = create(
- <FaviconImage sources={[captured, remote]} fallback={<span>fallback</span>} />,
- );
- });
- expect(renderer!.root.findByType("img").props.src).toBe(captured);
-
- await act(async () => renderer!.root.findByType("img").props.onError());
- expect(renderer!.root.findByType("img").props.src).toBe(remote);
-
- await act(async () => renderer!.root.findByType("img").props.onError());
- expect(renderer!.root.findAllByType("img")).toHaveLength(0);
- expect(renderer!.root.findByType("span").children).toEqual(["fallback"]);
-
- await act(async () => {
- renderer!.update(
- <FaviconImage
- sources={[captured, "https://public.example/new-icon"]}
- fallback={<span>fallback</span>}
- />,
- );
- });
- expect(renderer!.root.findByType("img").props.src).toBe(captured);
-});
diff --git a/apps/web/src/components/projectScriptEditor.browser.test.tsx b/apps/web/src/components/projectScriptEditor.browser.test.tsx
new file mode 100644
index 00000000000..6e589b38e2e
--- /dev/null
+++ b/apps/web/src/components/projectScriptEditor.browser.test.tsx
@@ -0,0 +1,179 @@
+import { EnvironmentId } from "@t3tools/contracts";
+import * as Cause from "effect/Cause";
+import { AsyncResult } from "effect/reactivity";
+import { act, StrictMode } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+vi.mock(import("~/state/session"), async (original) => ({
+ ...(await original()),
+ readEnvironmentScope: () => true,
+ useEnvironmentScope: () => true,
+}));
+
+import {
+ EMPTY_PROJECT_SCRIPT_INPUT,
+ ProjectScriptEditorDialog,
+ type ProjectScriptActionResult,
+ type ProjectScriptEditorRequest,
+} from "./projectScriptEditor";
+
+const onSubmit = vi.fn<Parameters<typeof ProjectScriptEditorDialog>[0]["onSubmit"]>();
+const onClose = vi.fn();
+const onDelete = vi.fn();
+let root: Root;
+let mounted: boolean;
+
+function request(name: string, error?: string): ProjectScriptEditorRequest {
+ return {
+ scriptId: name,
+ initial: { ...EMPTY_PROJECT_SCRIPT_INPUT, name, command: `run-${name}` },
+ ...(error === undefined ? {} : { error }),
+ };
+}
+
+const open = (nextRequest: ProjectScriptEditorRequest) =>
+ act(async () =>
+ root.render(
+ <StrictMode>
+ <ProjectScriptEditorDialog
+ environmentId={EnvironmentId.make("test")}
+ request={nextRequest}
+ scripts={[]}
+ onSubmit={onSubmit}
+ onClose={onClose}
+ onDelete={onDelete}
+ />
+ </StrictMode>,
+ ),
+ );
+
+const submit = () => document.querySelector("form")!.requestSubmit();
+const button = (label: string) =>
+ [...document.querySelectorAll("button")].find((element) => element.textContent === label)!;
+const saveButton = () => document.querySelector<HTMLButtonElement>('button[type="submit"]')!;
+const fieldset = () => document.querySelector("fieldset")!;
+const messages = () => [...document.querySelectorAll("form p")].map((p) => p.textContent);
+
+function deferredSave() {
+ let resolve!: (result: ProjectScriptActionResult) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<ProjectScriptActionResult>((resolveResult, rejectResult) => {
+ resolve = resolveResult;
+ reject = rejectResult;
+ });
+ return { promise, resolve, reject };
+}
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ onSubmit.mockReset();
+ onClose.mockReset();
+ onDelete.mockReset();
+ root = createRoot(document.createElement("div"));
+ mounted = true;
+});
+
+afterEach(async () => {
+ if (mounted) await act(async () => root.unmount());
+ vi.unstubAllGlobals();
+});
+
+describe("project action editor save lifecycle", () => {
+ it("blocks repeated submits and edits until the current save completes", async () => {
+ const save = deferredSave();
+ onSubmit.mockReturnValue(save.promise);
+ await open(request("build"));
+
+ await act(async () => {
+ submit();
+ submit();
+ });
+
+ expect(onSubmit).toHaveBeenCalledTimes(1);
+ expect(saveButton().disabled).toBe(true);
+ expect(saveButton().textContent).toBe("Saving…");
+ expect(fieldset().disabled).toBe(true);
+ expect(button("Cancel").disabled).toBe(false);
+
+ await act(async () => save.resolve(AsyncResult.success(undefined)));
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not close a replacement request or release its in-flight save", async () => {
+ const first = deferredSave();
+ const second = deferredSave();
+ onSubmit.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
+ await open(request("build"));
+ await act(async () => submit());
+
+ await open(request("test"));
+ expect(saveButton().disabled).toBe(false);
+ expect(document.querySelector<HTMLInputElement>("#script-name")!.value).toBe("test");
+ await act(async () => submit());
+
+ await act(async () => first.resolve(AsyncResult.success(undefined)));
+ expect(onClose).not.toHaveBeenCalled();
+ expect(saveButton().disabled).toBe(true);
+
+ await act(async () => second.resolve(AsyncResult.success(undefined)));
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(onSubmit.mock.calls.map(([scriptId]) => scriptId)).toEqual(["build", "test"]);
+ });
+
+ it.each(["failure", "rejection"] as const)(
+ "ignores a stale %s after the request changes",
+ async (outcome) => {
+ const save = deferredSave();
+ onSubmit.mockReturnValue(save.promise);
+ await open(request("build"));
+ await act(async () => submit());
+
+ await open(request("test", "New request error"));
+ await act(async () => {
+ if (outcome === "failure")
+ save.resolve(AsyncResult.failure(Cause.fail(new Error("Old save error"))));
+ else save.reject(new Error("Old save error"));
+ });
+
+ expect(messages()).toContain("New request error");
+ expect(messages()).not.toContain("Old save error");
+ expect(saveButton().disabled).toBe(false);
+ expect(onClose).not.toHaveBeenCalled();
+ },
+ );
+
+ it("shows a current save error and allows retry", async () => {
+ onSubmit.mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Save failed"))));
+ onSubmit.mockResolvedValueOnce(AsyncResult.success(undefined));
+ await open(request("build"));
+
+ await act(async () => saveButton().click());
+ expect(messages()).toContain("Save failed");
+ expect(saveButton().disabled).toBe(false);
+ expect(fieldset().disabled).toBe(false);
+ expect(onClose).not.toHaveBeenCalled();
+
+ await act(async () => saveButton().click());
+ expect(onSubmit).toHaveBeenCalledTimes(2);
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(["cancel", "unmount"] as const)("ignores save completion after %s", async (exit) => {
+ const save = deferredSave();
+ onSubmit.mockReturnValue(save.promise);
+ await open(request("build"));
+ await act(async () => submit());
+
+ await act(async () => {
+ if (exit === "cancel") button("Cancel").click();
+ else {
+ root.unmount();
+ mounted = false;
+ }
+ });
+ onClose.mockClear();
+ await act(async () => save.resolve(AsyncResult.success(undefined)));
+ expect(onClose).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/components/projectScriptEditor.permissions.test.tsx b/apps/web/src/components/projectScriptEditor.permissions.browser.test.tsx
similarity index 64%
rename from apps/web/src/components/projectScriptEditor.permissions.test.tsx
rename to apps/web/src/components/projectScriptEditor.permissions.browser.test.tsx
index ff28a3cf57e..eb49960876e 100644
--- a/apps/web/src/components/projectScriptEditor.permissions.test.tsx
+++ b/apps/web/src/components/projectScriptEditor.permissions.browser.test.tsx
@@ -6,50 +6,39 @@ import {
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
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, describe, expect, it, vi } from "vite-plus/test";
+import { userEvent } from "vite-plus/test/browser";
-const permissions = vi.hoisted(() => ({ canWriteSettings: false, canEditProject: true }));
+const permissions = vi.hoisted(() => ({
+ canWriteSettings: false,
+ canEditProject: true,
+ listeners: new Set<() => void>(),
+}));
-vi.mock("~/state/session", () => ({
- readEnvironmentScope: (_id: EnvironmentId, scope: AuthEnvironmentScope) =>
- scope === AuthOrchestrationOperateScope
- ? permissions.canEditProject
- : permissions.canWriteSettings,
- useEnvironmentScope: (_id: EnvironmentId, scope: AuthEnvironmentScope) =>
+vi.mock(import("~/state/session"), async (original) => {
+ const { useSyncExternalStore } = await import("react");
+ const read = (scope: AuthEnvironmentScope) =>
scope === AuthOrchestrationOperateScope
? permissions.canEditProject
- : permissions.canWriteSettings,
-}));
-vi.mock("./ui/dialog", () => ({
- Dialog: "div",
- DialogDescription: "div",
- DialogFooter: "div",
- DialogHeader: "div",
- DialogPanel: "div",
- DialogPopup: "div",
- DialogTitle: "div",
-}));
-vi.mock("./ui/alert-dialog", () => ({
- AlertDialog: "div",
- AlertDialogClose: "button",
- AlertDialogDescription: "div",
- AlertDialogFooter: "div",
- AlertDialogHeader: "div",
- AlertDialogPopup: "div",
- AlertDialogTitle: "div",
-}));
-vi.mock("./ui/popover", () => ({
- Popover: "div",
- PopoverPopup: "div",
- PopoverTrigger: "button",
-}));
-vi.mock("./ui/button", () => ({ Button: "button" }));
-vi.mock("./ui/input", () => ({ Input: "input" }));
-vi.mock("./ui/label", () => ({ Label: "label" }));
-vi.mock("./ui/switch", () => ({ Switch: "input" }));
-vi.mock("./ui/textarea", () => ({ Textarea: "textarea" }));
+ : permissions.canWriteSettings;
+ return {
+ ...(await original()),
+ readEnvironmentScope: (_id: EnvironmentId, scope: AuthEnvironmentScope) => read(scope),
+ useEnvironmentScope: (_id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
+ useSyncExternalStore(
+ (listener) => {
+ permissions.listeners.add(listener);
+ return () => permissions.listeners.delete(listener);
+ },
+ () => read(scope),
+ ),
+ };
+});
+/** A grant change that React has already rendered, unlike a bare assignment. */
+const publish = () => act(async () => permissions.listeners.forEach((listener) => listener()));
import {
ProjectScriptEditorDialog,
type NewProjectScriptInput,
@@ -72,16 +61,18 @@ const request: ProjectScriptEditorRequest = {
};
describe("ProjectScriptEditorDialog", () => {
- let renderer: ReactTestRenderer | undefined;
+ let root: Root;
beforeEach(() => {
+ root = createRoot(document.createElement("div"));
permissions.canWriteSettings = false;
permissions.canEditProject = true;
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
});
afterEach(async () => {
- await act(() => renderer?.unmount());
+ await act(async () => root.unmount());
+ vi.restoreAllMocks();
vi.unstubAllGlobals();
});
@@ -93,8 +84,8 @@ describe("ProjectScriptEditorDialog", () => {
| typeof AuthOrchestrationOperateScope
| typeof AuthSettingsWriteScope = AuthOrchestrationOperateScope,
) {
- await act(() => {
- renderer = create(
+ await act(async () =>
+ root.render(
<ProjectScriptEditorDialog
environmentId={EnvironmentId.make("script-editor-test")}
editScope={editScope}
@@ -104,9 +95,25 @@ describe("ProjectScriptEditorDialog", () => {
onDelete={actions.onDelete}
onClose={actions.onClose}
/>,
+ ),
+ );
+ }
+
+ const submit = () => act(async () => document.querySelector("form")!.requestSubmit());
+ async function click(label: string) {
+ const button = await vi.waitFor(() => {
+ const match = [...document.querySelectorAll("button")].find(
+ (element) => element.textContent === label,
);
+ expect(match, label).toBeDefined();
+ return match!;
});
- return renderer!.root;
+ await act(async () => button.click());
+ }
+ const confirmation = () => document.querySelector('[role="alertdialog"]');
+ async function pressInShortcutField(keys: string) {
+ document.querySelector<HTMLInputElement>("#script-keybinding")!.focus();
+ await userEvent.keyboard(keys);
}
it.each([null, "test"])(
@@ -115,22 +122,12 @@ describe("ProjectScriptEditorDialog", () => {
permissions.canEditProject = false;
permissions.canWriteSettings = true;
const onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
- const root = await openEditor(
- onSubmit,
- { ...request, scriptId },
- undefined,
- AuthSettingsWriteScope,
- );
- const submit = root.findByType("form").props.onSubmit;
+ await openEditor(onSubmit, { ...request, scriptId }, undefined, AuthSettingsWriteScope);
permissions.canWriteSettings = false;
- await act(async () => {
- await submit({ preventDefault() {} });
- });
+ await submit();
expect(onSubmit).not.toHaveBeenCalled();
permissions.canWriteSettings = true;
- await act(async () => {
- await submit({ preventDefault() {} });
- });
+ await submit();
expect(onSubmit).toHaveBeenCalledExactlyOnceWith(
scriptId,
expect.objectContaining({ command: "vp test" }),
@@ -142,16 +139,16 @@ describe("ProjectScriptEditorDialog", () => {
permissions.canEditProject = false;
permissions.canWriteSettings = true;
const actions = { onDelete: vi.fn(), onClose: vi.fn() };
- const root = await openEditor(undefined, request, actions, AuthSettingsWriteScope);
- await act(() => {
- root.findByProps({ variant: "destructive-outline" }).props.onClick();
- });
- const confirmDelete = root.findByProps({ variant: "destructive" }).props.onClick;
+ await openEditor(undefined, request, actions, AuthSettingsWriteScope);
+ await click("Delete");
permissions.canWriteSettings = false;
- await act(() => confirmDelete());
+ await click("Delete action");
expect(actions.onDelete).not.toHaveBeenCalled();
+ await vi.waitFor(() => expect(confirmation()).toBeNull());
permissions.canWriteSettings = true;
- await act(() => confirmDelete());
+ await publish();
+ await click("Delete");
+ await click("Delete action");
expect(actions.onDelete).toHaveBeenCalledExactlyOnceWith(request.scriptId);
});
@@ -162,14 +159,12 @@ describe("ProjectScriptEditorDialog", () => {
if (input.keybinding !== undefined) persistedKeybinding = input.keybinding;
return AsyncResult.success(undefined);
});
- const root = await openEditor(onSubmit, {
+ await openEditor(onSubmit, {
scriptId: null,
initial: { ...request.initial, keybinding: null },
});
- await act(async () => {
- await root.findByType("form").props.onSubmit({ preventDefault() {} });
- });
+ await submit();
expect(persistedKeybinding).toBeNull();
expect(onSubmit).toHaveBeenCalledWith(null, expect.objectContaining({ keybinding: null }));
@@ -190,15 +185,13 @@ describe("ProjectScriptEditorDialog", () => {
if (input.keybinding !== undefined) persisted.keybinding = input.keybinding;
return AsyncResult.success(undefined);
});
- const root = await openEditor(onSubmit, {
+ await openEditor(onSubmit, {
scriptId: null,
initial: { ...request.initial, keybinding: null },
});
permissions.canWriteSettings = false;
- await act(async () => {
- await root.findByType("form").props.onSubmit({ preventDefault() {} });
- });
+ await submit();
expect(persisted).toEqual({ name: "Test", keybinding: "mod+k" });
expect(onSubmit).toHaveBeenCalledOnce();
@@ -209,31 +202,20 @@ describe("ProjectScriptEditorDialog", () => {
"requires settings access to override a retained shortcut when re-adding an action (revoked: %s)",
async (revokeBeforeSubmit) => {
permissions.canWriteSettings = true;
- vi.stubGlobal("navigator", { platform: "Linux" });
+ vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
const persisted = { name: null as string | null, keybinding: "mod+k" as string | null };
const onSubmit = vi.fn(async (_id: string | null, input: NewProjectScriptInput) => {
persisted.name = input.name;
if (input.keybinding !== undefined) persisted.keybinding = input.keybinding;
return AsyncResult.success(undefined);
});
- const root = await openEditor(onSubmit, {
+ await openEditor(onSubmit, {
scriptId: null,
initial: { ...request.initial, keybinding: null },
});
- await act(() => {
- root.findByProps({ id: "script-keybinding" }).props.onKeyDown({
- key: "j",
- ctrlKey: true,
- metaKey: false,
- altKey: false,
- shiftKey: false,
- preventDefault() {},
- });
- });
+ await pressInShortcutField("{Control>}j{/Control}");
if (revokeBeforeSubmit) permissions.canWriteSettings = false;
- await act(async () => {
- await root.findByType("form").props.onSubmit({ preventDefault() {} });
- });
+ await submit();
expect(persisted).toEqual(
revokeBeforeSubmit
@@ -253,15 +235,13 @@ describe("ProjectScriptEditorDialog", () => {
if (input.keybinding !== undefined) persisted.keybinding = input.keybinding;
return AsyncResult.success(undefined);
});
- const root = await openEditor(onSubmit);
+ await openEditor(onSubmit);
persisted.keybinding = "mod+j";
- await act(() => {
- root.findByProps({ id: "script-name" }).props.onChange({ target: { value: "Renamed" } });
- });
- await act(async () => {
- await root.findByType("form").props.onSubmit({ preventDefault() {} });
- });
+ const name = document.querySelector<HTMLInputElement>("#script-name")!;
+ await userEvent.clear(name);
+ await userEvent.type(name, "Renamed");
+ await submit();
expect(persisted).toEqual({ name: "Renamed", keybinding: "mod+j" });
expect(onSubmit).toHaveBeenCalledOnce();
@@ -273,17 +253,10 @@ describe("ProjectScriptEditorDialog", () => {
async (revokeBeforeSubmit) => {
permissions.canWriteSettings = true;
const onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
- const root = await openEditor(onSubmit);
- await act(() => {
- root.findByProps({ id: "script-keybinding" }).props.onKeyDown({
- key: "Backspace",
- preventDefault() {},
- });
- });
+ await openEditor(onSubmit);
+ await pressInShortcutField("{Backspace}");
if (revokeBeforeSubmit) permissions.canWriteSettings = false;
- await act(async () => {
- await root.findByType("form").props.onSubmit({ preventDefault() {} });
- });
+ await submit();
if (revokeBeforeSubmit) {
expect(onSubmit).not.toHaveBeenCalled();
@@ -302,38 +275,33 @@ describe("ProjectScriptEditorDialog", () => {
permissions.canEditProject = revokeBeforeSubmit;
permissions.canWriteSettings = true;
const onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
- const root = await openEditor(onSubmit);
- const submit = root.findByType("form").props.onSubmit;
+ await openEditor(onSubmit);
permissions.canEditProject = false;
- await act(async () => {
- await submit({ preventDefault() {} });
- });
+ await submit();
expect(onSubmit).not.toHaveBeenCalled();
permissions.canEditProject = true;
- await act(async () => {
- await submit({ preventDefault() {} });
- });
+ await submit();
expect(onSubmit).toHaveBeenCalledOnce();
},
);
it("rechecks project access before deleting from an already open confirmation", async () => {
const actions = { onDelete: vi.fn(), onClose: vi.fn() };
- const root = await openEditor(undefined, request, actions);
- await act(() => {
- root.findByProps({ variant: "destructive-outline" }).props.onClick();
- });
- const confirmDelete = root.findByProps({ variant: "destructive" }).props.onClick;
+ await openEditor(undefined, request, actions);
+ await click("Delete");
permissions.canEditProject = false;
- await act(() => confirmDelete());
+ await click("Delete action");
expect(actions.onDelete).not.toHaveBeenCalled();
expect(actions.onClose).not.toHaveBeenCalled();
+ await vi.waitFor(() => expect(confirmation()).toBeNull());
permissions.canEditProject = true;
- await act(() => confirmDelete());
+ await publish();
+ await click("Delete");
+ await click("Delete action");
expect(actions.onDelete).toHaveBeenCalledExactlyOnceWith(request.scriptId);
expect(actions.onClose).toHaveBeenCalledOnce();
});
diff --git a/apps/web/src/components/projectScriptEditor.test.tsx b/apps/web/src/components/projectScriptEditor.test.tsx
deleted file mode 100644
index 71a3f7c7980..00000000000
--- a/apps/web/src/components/projectScriptEditor.test.tsx
+++ /dev/null
@@ -1,251 +0,0 @@
-import { EnvironmentId } from "@t3tools/contracts";
-import * as Cause from "effect/Cause";
-import { AsyncResult } from "effect/reactivity";
-import { act, StrictMode, type ReactNode } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
-
-vi.mock("~/state/session", () => ({
- readEnvironmentScope: () => true,
- useEnvironmentScope: () => true,
-}));
-vi.mock("./ui/dialog", () => ({
- Dialog: ({ open, children }: { open: boolean; children: ReactNode }) => (open ? children : null),
- DialogDescription: "p",
- DialogFooter: "footer",
- DialogHeader: "header",
- DialogPanel: "section",
- DialogPopup: "section",
- DialogTitle: "h2",
-}));
-vi.mock("./ui/alert-dialog", () => ({
- AlertDialog: ({ open, children }: { open: boolean; children: ReactNode }) =>
- open ? children : null,
- AlertDialogClose: "button",
- AlertDialogDescription: "p",
- AlertDialogFooter: "footer",
- AlertDialogHeader: "header",
- AlertDialogPopup: "section",
- AlertDialogTitle: "h2",
-}));
-vi.mock("./ui/button", () => ({ Button: "button" }));
-vi.mock("./ui/input", () => ({ Input: "input" }));
-vi.mock("./ui/label", () => ({ Label: "label" }));
-vi.mock("./ui/popover", () => ({
- Popover: ({ children }: { children: ReactNode }) => children,
- PopoverPopup: () => null,
- PopoverTrigger: "button",
-}));
-vi.mock("./ui/switch", () => ({ Switch: "input" }));
-vi.mock("./ui/textarea", () => ({ Textarea: "textarea" }));
-
-import {
- EMPTY_PROJECT_SCRIPT_INPUT,
- ProjectScriptEditorDialog,
- type ProjectScriptActionResult,
- type ProjectScriptEditorRequest,
-} from "./projectScriptEditor";
-
-const onSubmit = vi.fn<Parameters<typeof ProjectScriptEditorDialog>[0]["onSubmit"]>();
-const onClose = vi.fn();
-const onDelete = vi.fn();
-let renderer: ReactTestRenderer | null;
-
-function request(name: string, error?: string): ProjectScriptEditorRequest {
- return {
- scriptId: name,
- initial: { ...EMPTY_PROJECT_SCRIPT_INPUT, name, command: `run-${name}` },
- ...(error === undefined ? {} : { error }),
- };
-}
-
-function editor(nextRequest: ProjectScriptEditorRequest) {
- return (
- <StrictMode>
- <ProjectScriptEditorDialog
- environmentId={EnvironmentId.make("test")}
- request={nextRequest}
- scripts={[]}
- onSubmit={onSubmit}
- onClose={onClose}
- onDelete={onDelete}
- />
- </StrictMode>
- );
-}
-
-function open(nextRequest: ProjectScriptEditorRequest) {
- act(() => {
- if (renderer) renderer.update(editor(nextRequest));
- else renderer = create(editor(nextRequest));
- });
-}
-
-function submit(): Promise<void> {
- return renderer!.root.findByType("form").props.onSubmit({ preventDefault() {} });
-}
-
-function saveButton() {
- return renderer!.root.findAllByType("button").find((button) => button.props.type === "submit")!;
-}
-
-function deferredSave() {
- let resolve!: (result: ProjectScriptActionResult) => void;
- let reject!: (error: Error) => void;
- const promise = new Promise<ProjectScriptActionResult>((resolveResult, rejectResult) => {
- resolve = resolveResult;
- reject = rejectResult;
- });
- return { promise, resolve, reject };
-}
-
-beforeEach(() => {
- renderer = null;
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- onSubmit.mockReset();
- onClose.mockReset();
- onDelete.mockReset();
-});
-
-afterEach(async () => {
- await act(async () => renderer?.unmount());
- vi.unstubAllGlobals();
-});
-
-describe("project action editor save lifecycle", () => {
- it("blocks repeated submits and edits until the current save completes", async () => {
- const save = deferredSave();
- onSubmit.mockReturnValue(save.promise);
- open(request("build"));
-
- let completion!: Promise<void>;
- act(() => {
- completion = submit();
- void submit();
- });
-
- expect(onSubmit).toHaveBeenCalledTimes(1);
- expect(saveButton().props.disabled).toBe(true);
- expect(renderer!.root.findByType("fieldset").props.disabled).toBe(true);
- const cancel = renderer!.root
- .findAllByType("button")
- .find((button) => button.children.includes("Cancel"))!;
- expect(cancel.props.disabled).not.toBe(true);
-
- await act(async () => {
- save.resolve(AsyncResult.success(undefined));
- await completion;
- });
- expect(onClose).toHaveBeenCalledTimes(1);
- });
-
- it("does not close a replacement request or release its in-flight save", async () => {
- const first = deferredSave();
- const second = deferredSave();
- onSubmit.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
- open(request("build"));
- let firstCompletion!: Promise<void>;
- act(() => {
- firstCompletion = submit();
- });
-
- open(request("test"));
- expect(saveButton().props.disabled).toBe(false);
- expect(renderer!.root.findByProps({ id: "script-name" }).props.value).toBe("test");
- let secondCompletion!: Promise<void>;
- act(() => {
- secondCompletion = submit();
- });
-
- await act(async () => {
- first.resolve(AsyncResult.success(undefined));
- await firstCompletion;
- });
- expect(onClose).not.toHaveBeenCalled();
- expect(saveButton().props.disabled).toBe(true);
-
- await act(async () => {
- second.resolve(AsyncResult.success(undefined));
- await secondCompletion;
- });
- expect(onClose).toHaveBeenCalledTimes(1);
- expect(onSubmit.mock.calls.map(([scriptId]) => scriptId)).toEqual(["build", "test"]);
- });
-
- it.each(["failure", "rejection"] as const)(
- "ignores a stale %s after the request changes",
- async (outcome) => {
- const save = deferredSave();
- onSubmit.mockReturnValue(save.promise);
- open(request("build"));
- let completion!: Promise<void>;
- act(() => {
- completion = submit();
- });
-
- open(request("test", "New request error"));
- await act(async () => {
- if (outcome === "failure")
- save.resolve(AsyncResult.failure(Cause.fail(new Error("Old save error"))));
- else save.reject(new Error("Old save error"));
- await completion;
- });
-
- const messages = renderer!.root.findAllByType("p").flatMap((paragraph) => paragraph.children);
- expect(messages).toContain("New request error");
- expect(messages).not.toContain("Old save error");
- expect(saveButton().props.disabled).toBe(false);
- expect(onClose).not.toHaveBeenCalled();
- },
- );
-
- it("shows a current save error and allows retry", async () => {
- onSubmit.mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Save failed"))));
- onSubmit.mockResolvedValueOnce(AsyncResult.success(undefined));
- open(request("build"));
-
- await act(async () => {
- await submit();
- });
- expect(renderer!.root.findAllByType("p").flatMap((paragraph) => paragraph.children)).toContain(
- "Save failed",
- );
- expect(saveButton().props.disabled).toBe(false);
- expect(renderer!.root.findByType("fieldset").props.disabled).toBe(false);
- expect(onClose).not.toHaveBeenCalled();
-
- await act(async () => {
- await submit();
- });
- expect(onSubmit).toHaveBeenCalledTimes(2);
- expect(onClose).toHaveBeenCalledTimes(1);
- });
-
- it.each(["cancel", "unmount"] as const)("ignores save completion after %s", async (exit) => {
- const save = deferredSave();
- onSubmit.mockReturnValue(save.promise);
- open(request("build"));
- let completion!: Promise<void>;
- act(() => {
- completion = submit();
- });
-
- act(() => {
- if (exit === "cancel") {
- renderer!.root
- .findAllByType("button")
- .find((button) => button.children.includes("Cancel"))!
- .props.onClick();
- } else {
- renderer!.unmount();
- renderer = null;
- }
- });
- onClose.mockClear();
- await act(async () => {
- save.resolve(AsyncResult.success(undefined));
- await completion;
- });
- expect(onClose).not.toHaveBeenCalled();
- });
-});
diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.test.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx
similarity index 61%
rename from apps/web/src/components/pullRequest/PullRequestMarkdownEditor.test.tsx
rename to apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx
index 593ea123464..6f6569a0b53 100644
--- a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.test.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx
@@ -1,20 +1,22 @@
import { AuthSourceControlWriteScope, 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, expect, it, vi } from "vite-plus/test";
+import { userEvent } from "vite-plus/test/browser";
const permissions = vi.hoisted(() => ({
allowed: new Set<string>(),
listeners: new Set<() => void>(),
}));
-vi.mock("~/state/session", async () => {
+vi.mock(import("~/state/session"), async (original) => {
const { useSyncExternalStore } = await import("react");
- const canWrite = (environmentId: string, scope: string) =>
- scope === AuthSourceControlWriteScope && permissions.allowed.has(environmentId);
+ const canWrite = (environmentId: string | null, scope: string) =>
+ scope === AuthSourceControlWriteScope && permissions.allowed.has(environmentId ?? "");
return {
+ ...(await original()),
readEnvironmentScope: canWrite,
- useEnvironmentScope: (environmentId: string, scope: string) =>
+ useEnvironmentScope: (environmentId, scope) =>
useSyncExternalStore(
(listener) => {
permissions.listeners.add(listener);
@@ -24,37 +26,36 @@ vi.mock("~/state/session", async () => {
),
};
});
-vi.mock("~/lib/utils", () => ({ cn: () => "" }));
-vi.mock("../ui/button", () => ({ Button: "button" }));
-vi.mock("../ui/textarea", () => ({ Textarea: "textarea" }));
-vi.mock("../ui/toggle-group", () => ({ Toggle: "button", ToggleGroup: "div" }));
-vi.mock("./PullRequestMarkdown", () => ({ PullRequestMarkdown: "article" }));
import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
const primary = EnvironmentId.make("primary");
const secondary = EnvironmentId.make("secondary");
-let renderer: ReactTestRenderer | undefined;
const onSave = vi.fn<(next: string) => void>();
const onCancel = vi.fn<() => void>();
+let root: Root;
+let container: HTMLDivElement;
beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
permissions.allowed.clear();
permissions.listeners.clear();
- renderer = undefined;
onSave.mockReset();
onCancel.mockReset();
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
});
afterEach(async () => {
- await act(() => renderer?.unmount());
+ await act(async () => root.unmount());
+ container.remove();
vi.unstubAllGlobals();
});
async function openEditor(options?: { value?: string; allowEmpty?: boolean }) {
- await act(() => {
- renderer = create(
+ await act(async () =>
+ root.render(
<PullRequestMarkdownEditor
value={options?.value ?? "Original description"}
cwd="/repo"
@@ -65,16 +66,22 @@ async function openEditor(options?: { value?: string; allowEmpty?: boolean }) {
onSave={onSave}
onCancel={onCancel}
/>,
- );
- });
+ ),
+ );
}
-function saveHandler(): () => void {
- return renderer!.root.findByProps({ children: "Save" }).props.onClick;
+function button(label: string) {
+ const match = [...container.querySelectorAll("button")].find(
+ (element) => element.textContent === label,
+ );
+ expect(match, `button ${label}`).toBeDefined();
+ return match!;
}
+const clickSave = () => act(async () => button("Save").click());
+
async function grant(allowed: boolean) {
- await act(() => {
+ await act(async () => {
if (allowed) permissions.allowed.add(secondary);
else permissions.allowed.delete(secondary);
permissions.listeners.forEach((listener) => listener());
@@ -85,18 +92,19 @@ it("does not save a secondary environment's description using the primary grant"
permissions.allowed.add(primary);
await openEditor();
- await act(() => saveHandler()());
+ expect(button("Save").disabled).toBe(true);
+ await clickSave();
expect(onSave).not.toHaveBeenCalled();
});
-it("rejects a retained Save callback when the grant changes before React updates", async () => {
+it("rejects a Save click when the grant changes before React updates", async () => {
permissions.allowed.add(secondary);
await openEditor();
- const save = saveHandler();
permissions.allowed.delete(secondary);
- await act(() => save());
+ expect(button("Save").disabled).toBe(false);
+ await clickSave();
expect(onSave).not.toHaveBeenCalled();
});
@@ -104,45 +112,48 @@ it("rejects a retained Save callback when the grant changes before React updates
it("keeps an edited draft through revocation and saves it after access returns without remounting", async () => {
permissions.allowed.add(secondary);
await openEditor();
- await act(() => {
- renderer!.root.findByType("textarea").props.onChange({
- target: { value: "Keep these unsaved edits" },
- });
- });
+ const textarea = container.querySelector("textarea")!;
+ await userEvent.clear(textarea);
+ await userEvent.type(textarea, "Keep these unsaved edits");
await grant(false);
- await act(() => saveHandler()());
- expect(onSave).not.toHaveBeenCalled();
+ expect(button("Save").disabled).toBe(true);
+ expect(container.querySelector("textarea")).toBe(textarea);
await grant(true);
- await act(() => saveHandler()());
+ await clickSave();
expect(onSave).toHaveBeenCalledExactlyOnceWith("Keep these unsaved edits");
});
-it("saves with source-control permission alone", async () => {
+it("saves with source-control permission alone, from the button or Cmd/Ctrl+Enter", async () => {
permissions.allowed.add(secondary);
await openEditor();
- await act(() => saveHandler()());
-
+ await clickSave();
expect(onSave).toHaveBeenCalledExactlyOnceWith("Original description");
+
+ container.querySelector("textarea")!.focus();
+ await userEvent.keyboard("{Control>}{Enter}{/Control}");
+ expect(onSave).toHaveBeenCalledTimes(2);
});
it("allows clearing a description only after a pending grant becomes available", async () => {
await openEditor({ value: "", allowEmpty: true });
- await act(() => saveHandler()());
+ await clickSave();
expect(onSave).not.toHaveBeenCalled();
await grant(true);
- await act(() => saveHandler()());
+ await clickSave();
expect(onSave).toHaveBeenCalledExactlyOnceWith("");
});
it("keeps cancelling a local edit available without a write grant", async () => {
await openEditor();
- await act(() => renderer!.root.findByProps({ children: "Cancel" }).props.onClick());
+ await act(async () => button("Cancel").click());
+ container.querySelector("textarea")!.focus();
+ await userEvent.keyboard("{Escape}");
- expect(onCancel).toHaveBeenCalledOnce();
+ expect(onCancel).toHaveBeenCalledTimes(2);
expect(onSave).not.toHaveBeenCalled();
});
diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx
new file mode 100644
index 00000000000..b7062a14613
--- /dev/null
+++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx
@@ -0,0 +1,221 @@
+import { SourceControlProviderKind } from "@t3tools/contracts";
+import { EnvironmentId, ProjectId, type PullRequestDetailView } 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 { userEvent } from "vite-plus/test/browser";
+
+vi.mock(import("~/state/use-atom-command"), async (original) => ({
+ ...(await original()),
+ useAtomCommand: (() => vi.fn()) as never,
+}));
+
+import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
+
+const detail: PullRequestDetailView = {
+ provider: SourceControlProviderKind.make("github"),
+ projectId: ProjectId.make("project"),
+ projectTitle: "Project",
+ workspaceRoot: "/workspace",
+ repository: "owner/repo",
+ number: 1,
+ title: "Test pull request",
+ body: "Original description",
+ url: "https://github.com/owner/repo/pull/1",
+ author: { login: "author", name: null, avatarUrl: null },
+ viewer: "author",
+ state: "open",
+ isDraft: false,
+ mergeability: "mergeable",
+ additions: 1,
+ deletions: 0,
+ changedFiles: 1,
+ headBranch: "feature",
+ baseBranch: "main",
+ createdAt: "2026-09-01T00:00:00Z",
+ updatedAt: "2026-09-01T00:00:00Z",
+ mergedAt: null,
+ closedAt: null,
+ reviewers: [],
+ labels: [],
+ checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
+ comments: [],
+ commentCount: 0,
+ commentsTruncated: false,
+ reviewThreads: [],
+ commits: [],
+ mergeCapabilities: { merge: false, squash: false, rebase: false },
+ capabilities: {
+ diff: true,
+ comment: true,
+ search: true,
+ actions: [],
+ mergeMethods: [],
+ review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
+ reviewers: { request: false, listCandidates: false },
+ edit: { changeRequest: true, comment: true },
+ },
+ viewerPermissions: {
+ actions: [],
+ comment: true,
+ resolve: false,
+ verdicts: [],
+ requestReviewers: false,
+ },
+};
+
+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(async () => root.unmount());
+ container.remove();
+ localStorage.clear();
+ vi.unstubAllGlobals();
+});
+
+const render = (value = detail) =>
+ act(async () =>
+ root.render(
+ <PullRequestSummaryTab
+ scrollerRef={() => {}}
+ environmentId={EnvironmentId.make("environment")}
+ threadRef={null}
+ reference={value}
+ detail={value}
+ activityPending={false}
+ activityError={null}
+ onRefresh={() => {}}
+ />,
+ ),
+ );
+
+function heading(title: string) {
+ const section = container.querySelector(`section[aria-label="${title}"]`);
+ expect(section, `section ${title}`).not.toBeNull();
+ return [...section!.querySelectorAll("button")].find(
+ (button) => button.querySelector("span")?.textContent === title,
+ )!;
+}
+
+const click = (title: string) => act(async () => heading(title).click());
+const expanded = (title: string) => heading(title).getAttribute("aria-expanded");
+const visibleText = () => container.innerText;
+
+it("toggles checks from their heading and resets sections for another pull request", async () => {
+ await render();
+ expect(visibleText()).not.toContain("Unit tests");
+ await click("Checks");
+ expect(visibleText()).toContain("Unit tests");
+ await click("Checks");
+ expect(expanded("Checks")).toBe("false");
+ await click("Checks");
+ await click("Description");
+ await render({ ...detail, url: "https://github.com/owner/repo/pull/2", number: 2 });
+ expect(expanded("Checks")).toBe("false");
+ expect(expanded("Description")).toBe("true");
+});
+
+it("keeps an unsaved description when collapsed and reopened", async () => {
+ await render();
+ await act(async () =>
+ container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),
+ );
+ const textarea = container.querySelector("textarea")!;
+ await userEvent.clear(textarea);
+ await userEvent.type(textarea, "Unsaved description");
+ await click("Description");
+ expect(expanded("Description")).toBe("false");
+ await click("Description");
+ expect(container.querySelector("textarea")!.value).toBe("Unsaved description");
+});
+
+function commentTexts() {
+ const section = [...container.querySelectorAll("section")].find((element) =>
+ element.getAttribute("aria-label")?.startsWith("Comments"),
+ )!;
+ return [...section.querySelectorAll("p")]
+ .filter((p) => p.checkVisibility())
+ .map((p) => p.textContent ?? "");
+}
+
+const filterButton = () =>
+ container.querySelector<HTMLButtonElement>('[aria-label="Filter comments"]')!;
+
+function filterItem(label: string) {
+ const item = [...document.querySelectorAll('[role="menuitemcheckbox"]')].find((element) =>
+ element.textContent?.includes(label),
+ ) as HTMLElement | undefined;
+ expect(item, `filter ${label}`).toBeDefined();
+ return item!;
+}
+
+async function toggleFilter(label: string) {
+ if (!document.querySelector('[role="menuitemcheckbox"]')) await userEvent.click(filterButton());
+ await userEvent.click(filterItem(label));
+}
+
+it("hides bot and resolved comments until the filter shows them, and remembers the choice", async () => {
+ const comment = (index: number, login: string, body: string, isBot = false) => ({
+ id: `comment-${index}`,
+ kind: "issue-comment" as const,
+ author: { login, name: null, avatarUrl: null, isBot },
+ body,
+ createdAt: `2026-09-01T00:00:${String(index).padStart(2, "0")}Z`,
+ url: null,
+ path: null,
+ reviewState: null,
+ });
+ const resolved = {
+ ...comment(13, "reviewer", "Resolved remark"),
+ kind: "review-comment" as const,
+ };
+ const value: PullRequestDetailView = {
+ ...detail,
+ commentCount: 14,
+ comments: [
+ ...Array.from({ length: 12 }, (_, index) =>
+ comment(index, "review-app", `Bot report ${index}`, true),
+ ),
+ comment(12, "human", "Human comment"),
+ resolved,
+ ],
+ reviewThreads: [
+ {
+ id: "thread",
+ path: "src/index.ts",
+ line: 1,
+ side: "right",
+ isResolved: true,
+ isOutdated: false,
+ comments: [resolved],
+ },
+ ],
+ };
+ await render(value);
+ expect(commentTexts()).toEqual(["Human comment"]);
+ expect(filterButton().textContent).toContain("13 hidden");
+
+ await toggleFilter("Bot comments");
+ expect(commentTexts().filter((text) => text.startsWith("Bot report"))).toHaveLength(9);
+ expect(commentTexts()).toContain("Human comment");
+ expect(commentTexts()).not.toContain("Bot report 0");
+
+ await toggleFilter("Resolved or dismissed");
+ await userEvent.keyboard("{Escape}");
+ expect(
+ [...container.querySelectorAll("button")].some((button) => button.textContent === "Resolved"),
+ ).toBe(true);
+
+ await act(async () => root.unmount());
+ root = createRoot(container);
+ await render({ ...value, url: `${value.url}0`, number: 10 });
+ expect(commentTexts()).toContain("Bot report 11");
+ await userEvent.click(filterButton());
+ expect(filterItem("Bot comments").getAttribute("aria-checked")).toBe("true");
+});
diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.test.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.test.tsx
deleted file mode 100644
index ce8a3bd429f..00000000000
--- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.test.tsx
+++ /dev/null
@@ -1,245 +0,0 @@
-import { SourceControlProviderKind } from "@t3tools/contracts";
-import { EnvironmentId, ProjectId, type PullRequestDetailView } from "@t3tools/contracts";
-import { act, type ReactNode } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
-import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
-
-vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
-vi.mock("~/state/pullRequests", () => ({ pullRequestEnvironment: {} }));
-vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => vi.fn() }));
-vi.mock("./PullRequestMarkdown", () => ({
- PullRequestMarkdown: ({ text }: { text: string }) => <p>{text}</p>,
-}));
-vi.mock("../ui/menu", () => ({
- Menu: "div",
- MenuCheckboxItem: "div",
- MenuGroup: "div",
- MenuGroupLabel: "div",
- MenuPopup: "div",
- MenuTrigger: "div",
-}));
-vi.mock("../ui/tooltip", () => ({
- Tooltip: ({ children }: { children: ReactNode }) => children,
- TooltipTrigger: ({ children }: { children: ReactNode }) => children,
- TooltipPopup: () => null,
-}));
-
-import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
-
-const detail: PullRequestDetailView = {
- provider: SourceControlProviderKind.make("github"),
- projectId: ProjectId.make("project"),
- projectTitle: "Project",
- workspaceRoot: "/workspace",
- repository: "owner/repo",
- number: 1,
- title: "Test pull request",
- body: "Original description",
- url: "https://github.com/owner/repo/pull/1",
- author: { login: "author", name: null, avatarUrl: null },
- viewer: "author",
- state: "open",
- isDraft: false,
- mergeability: "mergeable",
- additions: 1,
- deletions: 0,
- changedFiles: 1,
- headBranch: "feature",
- baseBranch: "main",
- createdAt: "2026-09-01T00:00:00Z",
- updatedAt: "2026-09-01T00:00:00Z",
- mergedAt: null,
- closedAt: null,
- reviewers: [],
- labels: [],
- checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
- comments: [],
- commentCount: 0,
- commentsTruncated: false,
- reviewThreads: [],
- commits: [],
- mergeCapabilities: { merge: false, squash: false, rebase: false },
- capabilities: {
- diff: true,
- comment: true,
- search: true,
- actions: [],
- mergeMethods: [],
- review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
- reviewers: { request: false, listCandidates: false },
- edit: { changeRequest: true, comment: true },
- },
- viewerPermissions: {
- actions: [],
- comment: true,
- resolve: false,
- verdicts: [],
- requestReviewers: false,
- },
-};
-
-let renderer: ReactTestRenderer;
-beforeEach(() => {
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- const store = new Map<string, string>();
- vi.stubGlobal(
- "window",
- Object.assign(new EventTarget(), {
- localStorage: {
- getItem: (key: string) => store.get(key) ?? null,
- setItem: (key: string, value: string) => store.set(key, value),
- removeItem: (key: string) => store.delete(key),
- },
- }),
- );
-});
-afterEach(() => {
- act(() => renderer?.unmount());
- vi.unstubAllGlobals();
-});
-
-function render(value = detail) {
- return (
- <PullRequestSummaryTab
- scrollerRef={() => {}}
- environmentId={EnvironmentId.make("environment")}
- threadRef={null}
- reference={value}
- detail={value}
- activityPending={false}
- activityError={null}
- onRefresh={() => {}}
- />
- );
-}
-
-function heading(title: string) {
- const section = renderer.root
- .findAllByType("section")
- .find((section) => section.props["aria-label"] === title)!;
- return section
- .findAllByType("button")
- .find((button) => button.findAllByType("span").some((span) => span.children.includes(title)))!;
-}
-
-function click(title: string) {
- act(() =>
- heading(title).props.onClick({ nativeEvent: {}, preventDefault() {}, stopPropagation() {} }),
- );
-}
-
-it("toggles checks from their heading and resets sections for another pull request", () => {
- act(() => {
- renderer = create(render());
- });
- expect(
- renderer.root.findAllByType("span").some((span) => span.children.includes("Unit tests")),
- ).toBe(false);
- click("Checks");
- expect(
- renderer.root.findAllByType("span").some((span) => span.children.includes("Unit tests")),
- ).toBe(true);
- click("Checks");
- expect(heading("Checks").props["aria-expanded"]).toBe(false);
- click("Checks");
- click("Description");
- act(() =>
- renderer.update(render({ ...detail, url: "https://github.com/owner/repo/pull/2", number: 2 })),
- );
- expect(heading("Checks").props["aria-expanded"]).toBe(false);
- expect(heading("Description").props["aria-expanded"]).toBe(true);
-});
-
-it("keeps an unsaved description when collapsed and reopened", () => {
- act(() => {
- renderer = create(render());
- });
- act(() => renderer.root.findByProps({ "aria-label": "Edit description" }).props.onClick());
- act(() =>
- renderer.root.findByType("textarea").props.onChange({
- target: { value: "Unsaved description" },
- currentTarget: { value: "Unsaved description" },
- nativeEvent: {},
- }),
- );
- click("Description");
- expect(heading("Description").props["aria-expanded"]).toBe(false);
- click("Description");
- expect(renderer.root.findByType("textarea").props.value).toBe("Unsaved description");
-});
-
-function texts() {
- return renderer.root
- .findAllByType("p")
- .map((p) => p.children.join(""))
- .filter((text) => text !== detail.body);
-}
-
-function filterItem(label: string) {
- return renderer.root.find(
- (node) => typeof node.props.onCheckedChange === "function" && node.children.includes(label),
- );
-}
-
-it("hides bot and resolved comments until the filter shows them, and remembers the choice", () => {
- const comment = (index: number, login: string, body: string, isBot = false) => ({
- id: `comment-${index}`,
- kind: "issue-comment" as const,
- author: { login, name: null, avatarUrl: null, isBot },
- body,
- createdAt: `2026-09-01T00:00:${String(index).padStart(2, "0")}Z`,
- url: null,
- path: null,
- reviewState: null,
- });
- const resolved = {
- ...comment(13, "reviewer", "Resolved remark"),
- kind: "review-comment" as const,
- };
- const value: PullRequestDetailView = {
- ...detail,
- commentCount: 14,
- comments: [
- ...Array.from({ length: 12 }, (_, index) =>
- comment(index, "review-app", `Bot report ${index}`, true),
- ),
- comment(12, "human", "Human comment"),
- resolved,
- ],
- reviewThreads: [
- {
- id: "thread",
- path: "src/index.ts",
- line: 1,
- side: "right",
- isResolved: true,
- isOutdated: false,
- comments: [resolved],
- },
- ],
- };
- act(() => {
- renderer = create(render(value));
- });
- expect(texts()).toEqual(["Human comment"]);
- expect(
- renderer.root.findByProps({ "aria-label": "Filter comments" }).children.join(""),
- ).toContain("13 hidden");
-
- act(() => filterItem("Bot comments").props.onCheckedChange(true));
- expect(texts().filter((text) => text.startsWith("Bot report"))).toHaveLength(9);
- expect(texts()).toContain("Human comment");
- expect(texts()).not.toContain("Bot report 0");
-
- act(() => filterItem("Resolved or dismissed").props.onCheckedChange(true));
- expect(
- renderer.root.findAllByType("button").some((button) => button.children.includes("Resolved")),
- ).toBe(true);
-
- act(() => renderer.unmount());
- act(() => {
- renderer = create(render({ ...value, url: `${value.url}0`, number: 10 }));
- });
- expect(filterItem("Bot comments").props.checked).toBe(true);
- expect(texts()).toContain("Bot report 11");
-});
diff --git a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsx b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.browser.test.tsx
similarity index 79%
rename from apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsx
rename to apps/web/src/components/pullRequest/usePullRequestFilesViewed.browser.test.tsx
index d1a29ec19ee..36ed0b7ecf7 100644
--- a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsx
+++ b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.browser.test.tsx
@@ -5,8 +5,8 @@ import {
type PullRequestRef,
} from "@t3tools/contracts";
import { AsyncResult } from "effect/reactivity";
-import { act, StrictMode } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
+import { act, StrictMode, useEffect } from "react";
+import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
const { host, setFilesViewed, toastAdd } = vi.hoisted(() => ({
@@ -15,20 +15,24 @@ const { host, setFilesViewed, toastAdd } = vi.hoisted(() => ({
toastAdd: vi.fn(),
}));
-vi.mock("~/state/pullRequests", () => ({
- pullRequestEnvironment: { filesViewed: () => null, setFilesViewed: {} },
-}));
-vi.mock("~/state/query", () => ({
- useEnvironmentQuery: () => ({
+vi.mock(import("~/state/query"), async (original) => ({
+ ...(await original()),
+ useEnvironmentQuery: (() => ({
data: host.data,
error: null,
isPending: false,
isSuccess: true,
refresh: host.refresh,
- }),
+ })) as never,
+}));
+vi.mock(import("~/state/use-atom-command"), async (original) => ({
+ ...(await original()),
+ useAtomCommand: (() => setFilesViewed) as never,
}));
-vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => setFilesViewed }));
-vi.mock("../ui/toast", () => ({ toastManager: { add: toastAdd } }));
+vi.mock(import("../ui/toast"), async (original) => {
+ const actual = await original();
+ return { ...actual, toastManager: { ...actual.toastManager, add: toastAdd } as never };
+});
import {
usePullRequestFilesViewed,
@@ -46,30 +50,30 @@ function answer(state: "unviewed" | "viewed" | "dismissed"): PullRequestFilesVie
return { files: [{ path: "a.ts", state }], truncated: false };
}
-let renderer: ReactTestRenderer | null = null;
-
-function Probe(_props: { readonly view: PullRequestFilesViewedView }) {
- return null;
-}
+let root: Root;
+let current: PullRequestFilesViewedView;
function Surface() {
const view = usePullRequestFilesViewed({ environmentId, reference, enabled: true });
- return <Probe view={view} />;
-}
-
-function view(): PullRequestFilesViewedView {
- return renderer!.root.findByType(Probe).props.view;
+ useEffect(() => {
+ current = view;
+ });
+ return null;
}
-async function reads(state: "unviewed" | "viewed" | "dismissed") {
- host.data = answer(state);
- await act(async () =>
- renderer!.update(
+const view = () => current;
+const render = () =>
+ act(async () =>
+ root.render(
<StrictMode>
<Surface />
</StrictMode>,
),
);
+
+async function reads(state: "unviewed" | "viewed" | "dismissed") {
+ host.data = answer(state);
+ await render();
}
beforeEach(async () => {
@@ -79,18 +83,12 @@ beforeEach(async () => {
host.refresh.mockReset();
toastAdd.mockReset();
setFilesViewed.mockReset().mockResolvedValue(AsyncResult.success(undefined));
- act(() => {
- renderer = create(
- <StrictMode>
- <Surface />
- </StrictMode>,
- );
- });
+ root = createRoot(document.createElement("div"));
+ await render();
});
afterEach(async () => {
- await act(async () => renderer?.unmount());
- renderer = null;
+ await act(async () => root.unmount());
vi.useRealTimers();
vi.unstubAllGlobals();
});