Skip to content
TypeScript

test(web): onboarding and usage tests run in a real browser (#20902)

Julius Marminge07680cf7ceaf
diff --git a/apps/web/src/components/onboarding/WelcomeWizard.import.test.tsx b/apps/web/src/components/onboarding/WelcomeWizard.import.browser.test.tsx
similarity index 60%
rename from apps/web/src/components/onboarding/WelcomeWizard.import.test.tsx
rename to apps/web/src/components/onboarding/WelcomeWizard.import.browser.test.tsx
index 7c4497e63ee..c89050d2fc6 100644
--- a/apps/web/src/components/onboarding/WelcomeWizard.import.test.tsx
+++ b/apps/web/src/components/onboarding/WelcomeWizard.import.browser.test.tsx
@@ -8,10 +8,13 @@ import {
type AuthEnvironmentScope,
type AuthSessionState,
} from "@t3tools/contracts";
-import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
-import { act, create, type ReactTestInstance, type ReactTestRenderer } from "react-test-renderer";
+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";
+import "~/index.css";
+
type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
type Project = { id: ProjectId; environmentId: EnvironmentId; workspaceRoot: string };
type CreateProjectInput = {
@@ -20,11 +23,10 @@ type CreateProjectInput = {
};
const state = vi.hoisted(() => ({
selectedEnvironment: "primary",
- registry: null as AtomRegistry.AtomRegistry | null,
- sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),
- projects: null as Atom.Writable<ReadonlyArray<Project>> | null,
- providers: null as Atom.Atom<ReadonlyArray<never>> | null,
- config: null as Atom.Atom<null> | null,
+ sessions: new Map<string, unknown>(),
+ projects: null as unknown,
+ providers: null as unknown,
+ config: null as unknown,
candidates: [] as AgentSessionProjectCandidate[],
createProject: vi.fn(),
importThreads: vi.fn(),
@@ -36,30 +38,28 @@ const state = vi.hoisted(() => ({
refreshScan: 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("@clerk/react", () => ({ useAuth: () => ({ isLoaded: true, isSignedIn: false }) }));
-vi.mock("../../hooks/useTheme", () => ({ mountOnboardingTheme: () => () => {} }));
-vi.mock("../../hooks/useLocalStorage", () => ({ useLocalStorage: () => [false, () => {}] }));
-vi.mock("../../hooks/useCopyToClipboard", () => ({
- useCopyToClipboard: () => ({ copyToClipboard: vi.fn(), copied: false }),
+// Session grants come from per-test atoms so a test can revoke or regrant mid-flow; the
+// real scope checks in ~/state/session read them through the app registry, which the
+// wizard is also rendered with.
+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("../../cloud/publicConfig"), async (original) => ({
+ ...(await original()),
+ hasCloudPublicConfig: () => false,
}));
-vi.mock("../../cloud/publicConfig", () => ({ hasCloudPublicConfig: () => false }));
-vi.mock("../clerk/useT3ConnectAuthPrompt", () => ({ useT3ConnectAuthPrompt: vi.fn() }));
-vi.mock("../../onboarding/firstRun", () => ({
+vi.mock(import("../../onboarding/firstRun"), async (original) => ({
+ ...(await original()),
useCompleteOnboarding: () => state.completeOnboarding,
}));
-vi.mock("../../env", () => ({ isElectron: false }));
-vi.mock("../../state/environments", () => {
+vi.mock(import("../../state/environments"), async (original) => {
const environment = (environmentId: string) => ({
environmentId,
label: environmentId,
@@ -68,92 +68,75 @@ vi.mock("../../state/environments", () => {
});
const primary = environment("primary");
return {
- usePrimaryEnvironment: () => primary,
- useEnvironments: () => ({ environments: [environment(state.selectedEnvironment)] }),
+ ...(await original()),
+ usePrimaryEnvironment: (() => primary) as never,
+ useEnvironments: (() => ({ environments: [environment(state.selectedEnvironment)] })) as never,
};
});
-vi.mock("../../state/server", () => ({
- serverEnvironment: {
- providersValueAtom: () => state.providers,
- configValueAtom: () => state.config,
- refreshProviders: "refreshProviders",
- },
-}));
-vi.mock("../../state/entities", async () => {
+vi.mock(import("../../state/server"), async (original) => {
+ const actual = await original();
+ return {
+ ...actual,
+ serverEnvironment: {
+ ...actual.serverEnvironment,
+ providersValueAtom: (() => state.providers) as never,
+ configValueAtom: (() => state.config) as never,
+ refreshProviders: "refreshProviders" as never,
+ },
+ };
+});
+vi.mock(import("../../state/entities"), async (original) => {
const { useAtomValue } = await import("@effect/atom-react");
return {
- useProjects: () => useAtomValue(state.projects!),
- readProjects: () => state.registry!.get(state.projects!),
+ ...(await original()),
+ useProjects: (() => useAtomValue(state.projects as Atom.Atom<Project[]>)) as never,
+ readProjects: (() => appAtomRegistry.get(state.projects as Atom.Atom<Project[]>)) as never,
};
});
-vi.mock("../../state/projects", () => ({ projectEnvironment: { create: "createProject" } }));
-vi.mock("../../state/agentSessions", () => ({
- agentSessionScan: (query: { environmentId: EnvironmentId }) => query,
- agentSessionImport: "importThreads",
+vi.mock(import("../../state/projects"), async (original) => ({
+ ...(await original()),
+ projectEnvironment: { create: "createProject" } as never,
+}));
+vi.mock(import("../../state/agentSessions"), async (original) => ({
+ ...(await original()),
+ agentSessionImport: "importThreads" as never,
}));
-vi.mock("../../onboarding/useProjectScans", () => ({
- useProjectScans: (ids: EnvironmentId[]) =>
+vi.mock(import("../../onboarding/useProjectScans"), async (original) => ({
+ ...(await original()),
+ useProjectScans: (ids: readonly EnvironmentId[]) =>
ids.map((environmentId) => {
state.scan({ environmentId });
return {
environmentId,
- data: { candidates: state.candidates, truncated: false },
+ data: { candidates: state.candidates, truncated: false } as never,
isPending: false,
error: null,
refresh: state.refreshScan,
};
}),
}));
-vi.mock("../ui/dialog", () => ({
- Dialog: "div",
- DialogPopup: "div",
- DialogTitle: "div",
- DialogHeader: "div",
+vi.mock(import("../../connection/onboarding"), async (original) => ({
+ ...(await original()),
+ connectPairing: "connectPairing" as never,
}));
-vi.mock("../ui/wizard", () => ({
- WizardPanel: "div",
- WizardSteps: "div",
- WizardPopup: "div",
- WizardHeader: "div",
-}));
-vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));
-vi.mock("../ui/tooltip", () => ({ Tooltip: "div", TooltipTrigger: "span", TooltipPopup: "span" }));
-vi.mock("../../connection/onboarding", () => ({ connectPairing: "connectPairing" }));
-vi.mock("../../state/use-atom-command", () => ({
- useAtomCommand: (
+vi.mock(import("../../state/use-atom-command"), async (original) => ({
+ ...(await original()),
+ useAtomCommand: ((
command: "createProject" | "importThreads" | "refreshProviders" | "connectPairing",
- ) => state[command],
-}));
-vi.mock("../../state/terminal", () => ({ terminalEnvironment: {} }));
-vi.mock("../ThreadTerminalDrawer", () => ({ TerminalViewport: "div" }));
-vi.mock("../cloud/CloudEnvironmentConnectList", () => ({ CloudEnvironmentConnectRows: "div" }));
-vi.mock("../settings/ChatGptWelcomeCoordinator", () => ({ ChatGptWelcomeCoordinator: () => null }));
-vi.mock("../settings/CodexSetupSection", () => ({
- CodexSetupSection: () => null,
- AddManagedCodexAccountDialog: () => null,
+ ) => state[command]) as never,
}));
-vi.mock("../settings/providerDriverMeta", () => ({
- providerClients: { get: () => ({ label: "Agent" }) },
+vi.mock(import("../settings/ChatGptWelcomeCoordinator"), async (original) => ({
+ ...(await original()),
+ ChatGptWelcomeCoordinator: () => <></>,
}));
-vi.mock("../settings/providerStatus", () => ({
- getProviderSummary: () => ({ headline: "Checking", detail: null }),
-}));
-vi.mock("../ui/button", () => ({ Button: "button" }));
-vi.mock("../ui/input", () => ({ Input: "input" }));
-vi.mock("../ui/checkbox", () => ({ Checkbox: "input" }));
-vi.mock("../ui/collapsible", () => ({
- Collapsible: "div",
- CollapsiblePanel: "div",
- CollapsibleTrigger: "button",
-}));
-vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn(), close: vi.fn(), update: vi.fn() } }));
+import { appAtomRegistry } from "../../rpc/atomRegistry";
import { WelcomeWizard } from "./WelcomeWizard";
const primaryId = EnvironmentId.make("primary");
const remoteId = EnvironmentId.make("remote");
const permissionMessage = "This connection cannot import projects or thread history.";
-let renderer: ReactTestRenderer | undefined;
+const roots: Root[] = [];
function session(scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState {
return {
@@ -168,9 +151,17 @@ function session(scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState
};
}
+function sessionAtom(environmentId: EnvironmentId) {
+ return state.sessions.get(environmentId) as Atom.Writable<SessionResult>;
+}
+
+function projectsAtom() {
+ return state.projects as Atom.Writable<ReadonlyArray<Project>>;
+}
+
function setGrant(environmentId: EnvironmentId, allowed: boolean) {
- state.registry!.set(
- state.sessions.get(environmentId)!,
+ appAtomRegistry.set(
+ sessionAtom(environmentId),
AsyncResult.success(session(allowed ? [AuthOrchestrationOperateScope] : [])),
);
}
@@ -187,8 +178,8 @@ function candidate(path: string): AgentSessionProjectCandidate {
}
function recordProject({ environmentId, input }: CreateProjectInput) {
- state.registry!.set(state.projects!, [
- ...state.registry!.get(state.projects!),
+ appAtomRegistry.set(projectsAtom(), [
+ ...appAtomRegistry.get(projectsAtom()),
{ id: input.projectId, environmentId, workspaceRoot: input.workspaceRoot },
]);
return AsyncResult.success(undefined);
@@ -202,40 +193,47 @@ function deferred<T>() {
return { promise, resolve };
}
-function text(node: ReactTestInstance | string): string {
- return typeof node === "string" ? node : node.children.map(text).join("");
+function pageText() {
+ return document.body.textContent ?? "";
}
function button(label: string) {
- const found = renderer!.root.findAllByType("button").find((node) => text(node) === label);
+ const found = [...document.querySelectorAll("button")].find(
+ (element) => element.textContent?.trim() === label,
+ );
if (!found) throw new Error(`Missing button: ${label}`);
return found;
}
async function click(label: string) {
const target = button(label);
- expect(target.props.disabled).not.toBe(true);
- await act(async () => target.props.onClick());
+ expect(target.disabled).toBe(false);
+ await act(async () => target.click());
+}
+
+function projectCheckboxes() {
+ return [...document.querySelectorAll<HTMLElement>('[role="checkbox"]')];
}
async function mountImport(remote = false) {
state.selectedEnvironment = remote ? "remote" : "primary";
- await act(async () => {
- renderer = create(
- <RegistryContext.Provider value={state.registry!}>
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ roots.push(root);
+ await act(async () =>
+ root.render(
+ <RegistryContext.Provider value={appAtomRegistry}>
<WelcomeWizard localAvailable={!remote} onDone={state.onDone} />
</RegistryContext.Provider>,
- );
- });
+ ),
+ );
await click("Continue");
await click("Continue");
- expect(text(renderer!.root)).toContain("Import your projects");
+ expect(pageText()).toContain("Import your projects");
}
beforeEach(() => {
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- vi.stubGlobal("document", { activeElement: null, body: {}, getElementById: () => null });
- state.registry = AtomRegistry.make();
for (const id of [primaryId, remoteId]) {
state.sessions.set(
id,
@@ -263,20 +261,18 @@ beforeEach(() => {
});
afterEach(async () => {
- await act(async () => renderer?.unmount());
- renderer = undefined;
- state.registry?.dispose();
+ for (const root of roots.splice(0)) await act(async () => root.unmount());
+ document.body.replaceChildren();
state.sessions.clear();
- vi.unstubAllGlobals();
});
it("keeps scanning, choosing and skipping available to a paired read-only environment", async () => {
setGrant(remoteId, false);
await mountImport(true);
expect(state.scan).toHaveBeenCalledWith(expect.objectContaining({ environmentId: remoteId }));
- expect(text(renderer!.root)).toContain("/projects/first");
- expect(button("Import 2 projects").props.disabled).toBe(true);
- expect(text(renderer!.root)).toContain(permissionMessage);
+ expect(pageText()).toContain("/projects/first");
+ expect(button("Import 2 projects").disabled).toBe(true);
+ expect(pageText()).toContain(permissionMessage);
await click("Do not import projects");
expect(state.createProject).not.toHaveBeenCalled();
expect(state.importThreads).not.toHaveBeenCalled();
@@ -285,9 +281,9 @@ it("keeps scanning, choosing and skipping available to a paired read-only enviro
});
it("waits for the selected grant and enables import when it arrives", async () => {
- state.registry!.set(state.sessions.get(primaryId)!, AsyncResult.initial());
+ appAtomRegistry.set(sessionAtom(primaryId), AsyncResult.initial());
await mountImport();
- expect(button("Import 2 projects").props.disabled).toBe(true);
+ expect(button("Import 2 projects").disabled).toBe(true);
await act(async () => setGrant(primaryId, true));
await click("Import 2 projects");
expect(state.createProject).toHaveBeenCalledTimes(2);
@@ -295,25 +291,25 @@ it("waits for the selected grant and enables import when it arrives", async () =
expect(state.onDone).toHaveBeenCalledWith(expect.objectContaining({ environmentId: primaryId }));
});
-it("preserves selections and denies a retained action using the paired environment's fresh grant", async () => {
+it("preserves selections and denies a click that lands as the paired environment's grant is revoked", async () => {
await mountImport(true);
- await act(async () => {
- renderer!.root.findAllByType("input")[1]!.props.onCheckedChange(false);
- });
- const retainedImport = button("Import 1 project").props.onClick;
+ await act(async () => projectCheckboxes()[1]!.click());
+ expect(projectCheckboxes()[1]!.getAttribute("aria-checked")).toBe("false");
+ const importButton = button("Import 1 project");
+ // The click reaches the still-enabled button before React re-renders the revocation.
await act(async () => {
setGrant(remoteId, false);
- retainedImport();
+ importButton.click();
});
- expect(button("Import 1 project").props.disabled).toBe(true);
- expect(renderer!.root.findAllByType("input")[1]!.props.checked).toBe(false);
- expect(text(renderer!.root)).toContain(permissionMessage);
+ expect(button("Import 1 project").disabled).toBe(true);
+ expect(projectCheckboxes()[1]!.getAttribute("aria-checked")).toBe("false");
+ expect(pageText()).toContain(permissionMessage);
expect(state.createProject).not.toHaveBeenCalled();
expect(state.importThreads).not.toHaveBeenCalled();
expect(state.onDone).not.toHaveBeenCalled();
await act(async () => setGrant(remoteId, true));
- expect(text(renderer!.root)).not.toContain(permissionMessage);
+ expect(pageText()).not.toContain(permissionMessage);
await click("Import 1 project");
expect(state.createProject).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ environmentId: remoteId }),
@@ -340,7 +336,7 @@ it("rechecks after project creation and can retry its history without recreating
expect(state.importThreads).not.toHaveBeenCalled();
expect(state.createProject).toHaveBeenCalledOnce();
expect(state.onDone).not.toHaveBeenCalled();
- expect(text(renderer!.root)).toContain(permissionMessage);
+ expect(pageText()).toContain(permissionMessage);
await act(async () => setGrant(primaryId, true));
await click("Import 2 projects");
@@ -355,7 +351,7 @@ it.each([false, true])(
if (existing) {
const projectId = ProjectId.make("second-existing");
state.candidates[1] = { ...state.candidates[1]!, projectId };
- state.registry!.set(state.projects!, [
+ appAtomRegistry.set(projectsAtom(), [
{ id: projectId, environmentId: primaryId, workspaceRoot: "/projects/second" },
]);
}
@@ -375,7 +371,7 @@ it.each([false, true])(
expect(state.createProject).toHaveBeenCalledOnce();
expect(state.importThreads).toHaveBeenCalledOnce();
expect(state.onDone).not.toHaveBeenCalled();
- expect(text(renderer!.root)).toContain(permissionMessage);
+ expect(pageText()).toContain(permissionMessage);
await act(async () => setGrant(primaryId, true));
await click("Import 2 projects");
diff --git a/apps/web/src/components/onboarding/WelcomeWizard.terminal.test.tsx b/apps/web/src/components/onboarding/WelcomeWizard.terminal.browser.test.tsx
similarity index 66%
rename from apps/web/src/components/onboarding/WelcomeWizard.terminal.test.tsx
rename to apps/web/src/components/onboarding/WelcomeWizard.terminal.browser.test.tsx
index 56cd702411a..069c582d856 100644
--- a/apps/web/src/components/onboarding/WelcomeWizard.terminal.test.tsx
+++ b/apps/web/src/components/onboarding/WelcomeWizard.terminal.browser.test.tsx
@@ -20,10 +20,13 @@ import {
} from "@t3tools/contracts";
import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
import * as Cause from "effect/Cause";
-import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
-import { act, create, type ReactTestInstance, type ReactTestRenderer } from "react-test-renderer";
+import { AsyncResult, Atom } from "effect/reactivity";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import "~/index.css";
+
type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
type CommandResult = AsyncResult.AsyncResult<void, Error>;
type Request<Input> = { environmentId: EnvironmentId; input: Input };
@@ -34,7 +37,6 @@ type SetupConfig = {
keybindings: ResolvedKeybindingsConfig;
};
const state = vi.hoisted(() => ({
- registry: null as AtomRegistry.AtomRegistry | null,
sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),
providers: new Map<EnvironmentId, Atom.Writable<ReadonlyArray<ServerProvider>>>(),
configs: new Map<EnvironmentId, Atom.Atom<SetupConfig>>(),
@@ -49,99 +51,87 @@ const state = vi.hoisted(() => ({
done: 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/environments", () => ({
- useEnvironments: () => ({ environments: [remoteEnvironment] }),
- usePrimaryEnvironment: () => primaryEnvironment,
-}));
-vi.mock("../../state/server", () => ({
- serverEnvironment: {
- providersValueAtom: (id: EnvironmentId) => state.providers.get(id)!,
- configValueAtom: (id: EnvironmentId) => state.configs.get(id)!,
- refreshProviders: "refresh",
- },
+// Session grants come from per-test atoms so a test can revoke or regrant mid-flow; the
+// real scope checks in ~/state/session read them through the app registry, which the
+// wizard is also rendered with.
+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/environments"), async (original) => ({
+ ...(await original()),
+ useEnvironments: (() => ({ environments: [remoteEnvironment] })) as never,
+ usePrimaryEnvironment: (() => primaryEnvironment) as never,
}));
-vi.mock("../../state/terminal", () => ({
- terminalEnvironment: { open: "open", write: "write", close: "close" },
+vi.mock(import("../../state/server"), async (original) => {
+ const actual = await original();
+ return {
+ ...actual,
+ serverEnvironment: {
+ ...actual.serverEnvironment,
+ providersValueAtom: ((id: EnvironmentId) => state.providers.get(id)!) as never,
+ configValueAtom: ((id: EnvironmentId) => state.configs.get(id)!) as never,
+ refreshProviders: "refresh" as never,
+ },
+ };
+});
+vi.mock(import("../../state/terminal"), async (original) => ({
+ ...(await original()),
+ terminalEnvironment: { open: "open", write: "write", close: "close" } as never,
}));
-vi.mock("../../state/use-atom-command", () => ({
- useAtomCommand: (
+vi.mock(import("../../state/use-atom-command"), async (original) => ({
+ ...(await original()),
+ useAtomCommand: ((
command: "open" | "write" | "close" | "refresh" | "pair" | "createProject" | "importThreads",
- ) => state[command],
+ ) => state[command]) as never,
}));
-vi.mock("../../connection/onboarding", () => ({ connectPairing: "pair" }));
-vi.mock("../../state/agentSessions", () => ({
- agentSessionImport: "importThreads",
- agentSessionScan: vi.fn(),
+vi.mock(import("../../connection/onboarding"), async (original) => ({
+ ...(await original()),
+ connectPairing: "pair" as never,
}));
-vi.mock("../../state/projects", () => ({ projectEnvironment: { create: "createProject" } }));
-vi.mock("../../state/entities", () => ({ readProjects: () => [], useProjects: () => [] }));
-vi.mock("../../onboarding/useProjectScans", () => ({ useProjectScans: () => [] }));
-vi.mock("../ui/dialog", () => ({
- Dialog: "div",
- DialogPopup: "div",
- DialogTitle: "div",
- DialogHeader: "div",
+vi.mock(import("../../state/agentSessions"), async (original) => ({
+ ...(await original()),
+ agentSessionImport: "importThreads" as never,
}));
-vi.mock("../ui/wizard", () => ({
- WizardPanel: "div",
- WizardPopup: "div",
- WizardHeader: "div",
- WizardSteps: ({ onStepChange }: { onStepChange: (step: number) => void }) => (
- <button onClick={() => onStepChange(0)}>Back</button>
- ),
+vi.mock(import("../../state/projects"), async (original) => ({
+ ...(await original()),
+ projectEnvironment: { create: "createProject" } as never,
}));
-vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));
-vi.mock("../../onboarding/firstRun", () => ({ useCompleteOnboarding: () => state.complete }));
-vi.mock("../../hooks/useTheme", () => ({ mountOnboardingTheme: () => undefined }));
-vi.mock("../../hooks/useLocalStorage", () => ({ useLocalStorage: () => [false, vi.fn()] }));
-vi.mock("../../hooks/useCopyToClipboard", () => ({
- useCopyToClipboard: () => ({ copyToClipboard: vi.fn(), isCopied: false }),
+vi.mock(import("../../state/entities"), async (original) => ({
+ ...(await original()),
+ readProjects: () => [],
+ useProjects: () => [],
}));
-vi.mock("../../cloud/publicConfig", () => ({ hasCloudPublicConfig: () => false }));
-vi.mock("../clerk/useT3ConnectAuthPrompt", () => ({ useT3ConnectAuthPrompt: vi.fn() }));
-vi.mock("@clerk/react", () => ({ useAuth: vi.fn() }));
-vi.mock("../../env", () => ({ isElectron: false }));
-vi.mock("../../providerInstances", () => ({ resolveDefaultProviderModelSelection: vi.fn() }));
-vi.mock("../settings/ChatGptWelcomeCoordinator", () => ({ ChatGptWelcomeCoordinator: () => null }));
-vi.mock("../settings/CodexSetupSection", () => ({
- CodexSetupSection: () => null,
- AddManagedCodexAccountDialog: () => null,
+vi.mock(import("../../onboarding/useProjectScans"), async (original) => ({
+ ...(await original()),
+ useProjectScans: () => [],
}));
-vi.mock("../settings/providerDriverMeta", () => ({
- providerClients: { get: (driver: string) => ({ label: driver }) },
+vi.mock(import("../../onboarding/firstRun"), async (original) => ({
+ ...(await original()),
+ useCompleteOnboarding: () => state.complete,
}));
-vi.mock("../settings/providerStatus", () => ({
- getProviderSummary: () => ({ headline: "Setup required" }),
+vi.mock(import("../../cloud/publicConfig"), async (original) => ({
+ ...(await original()),
+ hasCloudPublicConfig: () => false,
}));
-vi.mock("../cloud/CloudEnvironmentConnectList", () => ({
- CloudEnvironmentConnectRows: () => null,
+vi.mock(import("../settings/ChatGptWelcomeCoordinator"), async (original) => ({
+ ...(await original()),
+ ChatGptWelcomeCoordinator: () => <></>,
}));
-vi.mock("../ThreadTerminalDrawer", () => ({
+// The real viewport mounts a Ghostty terminal against the PTY; these tests only need to
+// see whether the wizard shows it.
+vi.mock(import("../ThreadTerminalDrawer"), async (original) => ({
+ ...(await original()),
TerminalViewport: () => <div data-terminal-viewport />,
}));
-vi.mock("../ui/button", () => ({ Button: "button" }));
-vi.mock("../ui/input", () => ({ Input: "input" }));
-vi.mock("../ui/checkbox", () => ({ Checkbox: "input" }));
-vi.mock("../ui/collapsible", () => ({
- Collapsible: "div",
- CollapsiblePanel: "div",
- CollapsibleTrigger: "button",
-}));
-vi.mock("../ui/toast", () => ({
- toastManager: { add: vi.fn(), update: vi.fn(), close: vi.fn() },
-}));
+import { appAtomRegistry } from "../../rpc/atomRegistry";
import { WelcomeWizard } from "./WelcomeWizard";
const primaryId = EnvironmentId.make("primary");
@@ -204,7 +194,7 @@ const session = (scopes: readonly AuthEnvironmentScope[]): AuthSessionState => (
},
});
function setAccess(environmentId: EnvironmentId, allowed: boolean) {
- state.registry!.set(
+ appAtomRegistry.set(
state.sessions.get(environmentId)!,
AsyncResult.success(session(allowed ? [AuthTerminalOperateScope] : [])),
);
@@ -216,38 +206,42 @@ function deferred<T>() {
});
return { promise, resolve };
}
-function text(node: ReactTestInstance | string): string {
- return typeof node === "string" ? node : node.children.map(text).join("");
+const roots: Root[] = [];
+function pageText() {
+ return document.body.textContent ?? "";
}
-let renderer: ReactTestRenderer | undefined;
function button(label: string) {
- return renderer!.root.findAllByType("button").find((node) => text(node) === label)!;
+ const found = [...document.querySelectorAll("button")].find(
+ (element) => element.textContent?.trim() === label || element.ariaLabel === label,
+ );
+ if (!found) throw new Error(`Missing button: ${label}`);
+ return found;
}
async function click(label: string) {
const node = button(label);
- expect(node).toBeDefined();
- expect(node.props.disabled).not.toBe(true);
- await act(async () => node.props.onClick());
+ expect(node.disabled).toBe(false);
+ await act(async () => node.click());
}
function hasViewport() {
- return renderer!.root.findAllByProps({ "data-terminal-viewport": true }).length > 0;
+ return document.querySelector("[data-terminal-viewport]") !== null;
}
async function enterRemoteAgents() {
- await act(async () => {
- renderer = create(
- <RegistryContext.Provider value={state.registry!}>
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ roots.push(root);
+ await act(async () =>
+ root.render(
+ <RegistryContext.Provider value={appAtomRegistry}>
<WelcomeWizard localAvailable onDone={state.done} />
</RegistryContext.Provider>,
- );
- });
+ ),
+ );
await click("Continue");
- expect(text(renderer!.root)).toContain("Paired computer");
+ expect(pageText()).toContain("Paired computer");
}
beforeEach(() => {
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- vi.stubGlobal("document", { activeElement: null, body: {}, getElementById: () => null });
- state.registry = AtomRegistry.make();
for (const id of [primaryId, remoteId]) {
state.sessions.set(
id,
@@ -289,25 +283,23 @@ beforeEach(() => {
});
afterEach(async () => {
- await act(async () => renderer?.unmount());
- renderer = undefined;
- state.registry?.dispose();
+ for (const root of roots.splice(0)) await act(async () => root.unmount());
+ document.body.replaceChildren();
state.sessions.clear();
state.providers.clear();
state.configs.clear();
- vi.unstubAllGlobals();
});
describe("welcome agent terminal setup", () => {
it("disables both setup actions for the paired read-only connection and preserves local completion", async () => {
setAccess(remoteId, false);
await enterRemoteAgents();
- expect(button("Install").props.disabled).toBe(true);
- expect(button("Sign in").props.disabled).toBe(true);
- expect(text(renderer!.root)).toContain("This connection cannot control terminals.");
+ expect(button("Install").disabled).toBe(true);
+ expect(button("Sign in").disabled).toBe(true);
+ expect(pageText()).toContain("This connection cannot control terminals.");
await act(async () => {
- button("Install").props.onClick();
- button("Sign in").props.onClick();
+ button("Install").click();
+ button("Sign in").click();
});
expect(state.open).not.toHaveBeenCalled();
expect(state.write).not.toHaveBeenCalled();
@@ -321,16 +313,17 @@ describe("welcome agent terminal setup", () => {
it("rejects a retained install action after revocation and allows a terminal-only regrant", async () => {
setAccess(primaryId, false);
await enterRemoteAgents();
- const install = button("Install").props.onClick;
+ const install = button("Install");
+ // The click reaches the still-enabled button before React re-renders the revocation.
await act(async () => {
setAccess(remoteId, false);
- install();
+ install.click();
});
expect(state.open).not.toHaveBeenCalled();
- expect(button("Install").props.disabled).toBe(true);
+ expect(button("Install").disabled).toBe(true);
await act(async () => setAccess(remoteId, true));
- expect(button("Install").props.disabled).toBe(false);
- await act(async () => install());
+ expect(button("Install").disabled).toBe(false);
+ await click("Install");
expect(state.open).toHaveBeenCalledExactlyOnceWith({
environmentId: remoteId,
input: {
@@ -381,7 +374,7 @@ describe("welcome agent terminal setup", () => {
data: "/opt/codex-work login",
},
});
- expect(text(renderer!.root)).toContain("Review the command, then press Enter to run it.");
+ expect(pageText()).toContain("Review the command, then press Enter to run it.");
});
it("checks access when a queued retry starts and recovers after regrant", async () => {
@@ -398,7 +391,7 @@ describe("welcome agent terminal setup", () => {
closing.resolve(AsyncResult.success(undefined));
});
expect(state.open).toHaveBeenCalledOnce();
- expect(button("Retry").props.disabled).toBe(true);
+ expect(button("Retry").disabled).toBe(true);
expect(state.write).not.toHaveBeenCalled();
await act(async () => setAccess(remoteId, true));
await click("Retry");
@@ -419,19 +412,17 @@ describe("welcome agent terminal setup", () => {
expect(state.write).not.toHaveBeenCalled();
expect(state.close).not.toHaveBeenCalled();
expect(hasViewport()).toBe(true);
- expect(text(renderer!.root)).toContain("This connection cannot control terminals.");
+ expect(pageText()).toContain("This connection cannot control terminals.");
await act(async () => setAccess(remoteId, true));
expect(state.open).toHaveBeenCalledOnce();
expect(state.write).not.toHaveBeenCalled();
- expect(text(renderer!.root)).toContain(
- "Run curl -fsSL https://claude.ai/install.sh | bash in this",
- );
+ expect(pageText()).toContain("Run curl -fsSL https://claude.ai/install.sh | bash in this");
await act(async () => setAccess(remoteId, false));
await click("Close");
expect(hasViewport()).toBe(false);
expect(state.close).not.toHaveBeenCalled();
await click("Continue");
- expect(text(renderer!.root)).toContain("Import your projects");
+ expect(pageText()).toContain("Import your projects");
});
it("settles accepted pretyping locally after revocation without closing the PTY", async () => {
@@ -447,7 +438,7 @@ describe("welcome agent terminal setup", () => {
expect(state.write).toHaveBeenCalledOnce();
expect(hasViewport()).toBe(true);
await act(async () => setAccess(remoteId, true));
- expect(text(renderer!.root)).toContain("Review the command, then press Enter to run it.");
+ expect(pageText()).toContain("Review the command, then press Enter to run it.");
expect(state.open).toHaveBeenCalledOnce();
expect(state.write).toHaveBeenCalledOnce();
await act(async () => setAccess(remoteId, false));
@@ -460,13 +451,13 @@ describe("welcome agent terminal setup", () => {
state.write.mockReturnValueOnce(writing.promise);
await enterRemoteAgents();
await click("Install");
- await click("Back");
+ await click("Connect, step 1");
expect(state.close).not.toHaveBeenCalled();
await act(async () => {
setAccess(remoteId, false);
writing.resolve(AsyncResult.success(undefined));
});
expect(state.close).not.toHaveBeenCalled();
- expect(text(renderer!.root)).toContain("Connect your computers");
+ expect(pageText()).toContain("Connect your computers");
});
});
diff --git a/apps/web/src/components/preview/PreviewView.browser.test.tsx b/apps/web/src/components/preview/PreviewView.browser.test.tsx
new file mode 100644
index 00000000000..0147addd091
--- /dev/null
+++ b/apps/web/src/components/preview/PreviewView.browser.test.tsx
@@ -0,0 +1,452 @@
+import {
+ BUILT_IN_BROWSER_PROFILES,
+ DEFAULT_BROWSER_PROFILE_ID,
+ DEFAULT_PREVIEW_APPEARANCE,
+ DEFAULT_PREVIEW_ZOOM_FACTOR,
+ EnvironmentId,
+ FILL_PREVIEW_VIEWPORT,
+ ThreadId,
+} from "@t3tools/contracts";
+import { act, Profiler, type ComponentProps, type ReactNode } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import { page, userEvent } from "vite-plus/test/browser";
+
+import "~/index.css";
+
+import type { PreviewableServer } from "./useDiscoveredLocalServers";
+
+const mocks = vi.hoisted(() => ({
+ navigate: vi.fn(async (_tabId: string, _url: string): Promise<void> => undefined),
+ rememberPreviewUrl: vi.fn(),
+ readPreparedConnection: vi.fn(() => ({ httpBaseUrl: "http://172.25.85.75:3773" })),
+ readEnvironmentScope: vi.fn((_environmentId?: unknown, _scope?: unknown) => true),
+ setAnnotationSendEnabled: vi.fn(async (_tabId: string, _enabled: boolean): Promise<void> => {}),
+ cancelPickElement: vi.fn(async (_tabId: string) => undefined),
+ openPictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
+ closePictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
+ pickElement: vi.fn(),
+ addPreviewAnnotation: vi.fn(),
+ addImage: vi.fn(),
+ toast: vi.fn(),
+ pictureInPicture: false,
+ showEmptyState: false,
+ loading: false,
+ serverEpoch: null as string | null,
+ servers: [] as PreviewableServer[],
+ recordingTabIds: new Set<string>(),
+ recordingRuntimeTabId: null as string | null,
+ recordVisitForThread: vi.fn(),
+}));
+
+const STUB_BROWSER_DEFAULTS = {
+ viewport: FILL_PREVIEW_VIEWPORT,
+ zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
+ appearance: DEFAULT_PREVIEW_APPEARANCE,
+ autoShowFloatingPreview: true,
+ profiles: BUILT_IN_BROWSER_PROFILES,
+ profileId: DEFAULT_BROWSER_PROFILE_ID,
+};
+
+// The desktop bridge only exists inside Electron; the view reads it once at import.
+vi.mock(import("./previewBridge"), async (original) => ({
+ ...(await original()),
+ previewBridge: {
+ navigate: mocks.navigate,
+ pickElement: mocks.pickElement,
+ setAnnotationSendEnabled: mocks.setAnnotationSendEnabled,
+ cancelPickElement: mocks.cancelPickElement,
+ refresh: vi.fn(async () => undefined),
+ goBack: vi.fn(async () => undefined),
+ goForward: vi.fn(async () => undefined),
+ hardReload: vi.fn(async () => undefined),
+ openDevTools: vi.fn(async () => undefined),
+ setColorScheme: vi.fn(async () => undefined),
+ zoomIn: vi.fn(async () => undefined),
+ zoomOut: vi.fn(async () => undefined),
+ resetZoom: vi.fn(async () => undefined),
+ clearCookies: vi.fn(async () => undefined),
+ clearCache: vi.fn(async () => undefined),
+ pictureInPicture: {
+ open: mocks.openPictureInPicture,
+ close: mocks.closePictureInPicture,
+ },
+ } as never,
+}));
+vi.mock(import("~/browserHistoryStore"), async (original) => ({
+ ...(await original()),
+ recordVisitForThread: mocks.recordVisitForThread,
+}));
+vi.mock(import("~/state/session"), async (original) => ({
+ ...(await original()),
+ readPreparedConnection: mocks.readPreparedConnection as never,
+ readEnvironmentScope: mocks.readEnvironmentScope,
+ useEnvironmentScope: mocks.readEnvironmentScope,
+}));
+vi.mock(import("~/browser/browserDefaults"), async (original) => ({
+ ...(await original()),
+ useBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
+ getBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
+}));
+vi.mock(import("~/previewStateStore"), async (original) => ({
+ ...(await original()),
+ rememberPreviewUrl: mocks.rememberPreviewUrl,
+ useThreadPreviewState: (() => ({
+ activeTabId: "tab-1",
+ serverEpoch: mocks.serverEpoch,
+ desktopByTabId: {
+ "tab-1": {
+ hasWebContents: true,
+ canGoBack: false,
+ canGoForward: false,
+ loading: mocks.loading,
+ zoomFactor: 1,
+ pictureInPicture: mocks.pictureInPicture,
+ colorScheme: "system",
+ audioMuted: false,
+ audible: false,
+ controller: "none",
+ },
+ },
+ recentlySeenUrls: [],
+ sessions: mocks.showEmptyState
+ ? {}
+ : {
+ "tab-1": {
+ threadId: "thread-1",
+ tabId: "tab-1",
+ navStatus: { _tag: "Success", url: "http://example.com/", title: "Example" },
+ canGoBack: false,
+ canGoForward: false,
+ updatedAt: "2026-07-13T00:00:00.000Z",
+ },
+ },
+ })) as never,
+}));
+vi.mock(import("~/state/environments"), async (original) => ({
+ ...(await original()),
+ useEnvironment: (() => ({ label: "WSL" })) as never,
+ useEnvironmentHttpBaseUrl: () => "http://172.25.85.75:3773",
+ usePrimaryEnvironmentId: () => null,
+}));
+vi.mock(import("~/browser/browserRecording"), async (original) => ({
+ ...(await original()),
+ findActiveBrowserRecordingRuntimeTabId: () => mocks.recordingRuntimeTabId,
+ useActiveBrowserRecordingTabIds: () => mocks.recordingTabIds,
+}));
+vi.mock(import("~/components/ui/toast"), async (original) => {
+ const actual = await original();
+ return { ...actual, toastManager: { ...actual.toastManager, add: mocks.toast } };
+});
+vi.mock(import("./useDiscoveredLocalServers"), async (original) => ({
+ ...(await original()),
+ useDiscoveredLocalServers: () => mocks.servers,
+}));
+vi.mock(import("./usePreviewSession"), async (original) => ({
+ ...(await original()),
+ usePreviewSession: () => {},
+}));
+
+import { useComposerDraftStore } from "~/composerDraftStore";
+import { useBrowserPointerStore } from "~/browser/browserPointerStore";
+import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
+import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
+import { PreviewView } from "./PreviewView";
+
+const TEST_THREAD_REF = {
+ environmentId: EnvironmentId.make("environment-1"),
+ threadId: ThreadId.make("thread-1"),
+} as const;
+const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
+
+const roots: Root[] = [];
+let root: Root;
+
+async function render(node: ReactNode) {
+ await act(async () => root.render(node));
+}
+
+function view(onSendAnnotation?: ComponentProps<typeof PreviewView>["onSendAnnotation"]) {
+ return (
+ <PreviewView
+ threadRef={TEST_THREAD_REF}
+ tabId="tab-1"
+ visible
+ {...(onSendAnnotation ? { onSendAnnotation } : {})}
+ />
+ );
+}
+
+function annotation(id: string, screenshot: unknown = null) {
+ return {
+ id,
+ pageUrl: "https://example.com/dashboard",
+ pageTitle: "Dashboard",
+ comment: "Tighten this spacing",
+ elements: [],
+ regions: [],
+ strokes: [],
+ styleChanges: [],
+ screenshot,
+ createdAt: "2026-07-27T00:00:00.000Z",
+ };
+}
+
+async function submitAddress(text: string) {
+ const input = page.getByPlaceholder("Search or enter URL");
+ await userEvent.click(input);
+ await userEvent.fill(input, text);
+ await userEvent.keyboard("{Enter}");
+}
+
+function hasCursor() {
+ return document.querySelector("svg.lucide-mouse-pointer2") !== null;
+}
+
+describe("PreviewView", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
+ mocks.setAnnotationSendEnabled.mockReset().mockResolvedValue(undefined);
+ mocks.pickElement.mockReset();
+ mocks.pictureInPicture = false;
+ mocks.showEmptyState = false;
+ mocks.loading = false;
+ mocks.serverEpoch = null;
+ mocks.servers = [];
+ mocks.recordingTabIds = new Set();
+ mocks.recordingRuntimeTabId = null;
+ useComposerDraftStore.setState({
+ addPreviewAnnotation: mocks.addPreviewAnnotation,
+ addImage: mocks.addImage,
+ });
+ usePreviewMiniPlayerStore.setState({ byThreadKey: {} });
+ useBrowserPointerStore.setState({ byTabId: {} });
+ const container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ roots.push(root);
+ });
+
+ afterEach(async () => {
+ for (const each of roots.splice(0)) await act(async () => each.unmount());
+ document.body.replaceChildren();
+ vi.useRealTimers();
+ });
+
+ it("shows the cursor in a replacement browser while the old instance still records", async () => {
+ mocks.recordingTabIds.add(TEST_RUNTIME_TAB_ID);
+ mocks.recordingRuntimeTabId = TEST_RUNTIME_TAB_ID;
+ const replacementTabId = previewRuntimeTabId(TEST_THREAD_REF, "replacement-server", "tab-1");
+ useBrowserPointerStore.setState({
+ byTabId: Object.fromEntries(
+ [TEST_RUNTIME_TAB_ID, replacementTabId].map((tabId) => [
+ tabId,
+ { tabId, phase: "move", x: 10, y: 10, sequence: 1, createdAt: "2026-07-27T00:00:00Z" },
+ ]),
+ ),
+ });
+ await render(view());
+ expect(hasCursor()).toBe(false);
+ mocks.serverEpoch = "replacement-server";
+ await render(view());
+ expect(hasCursor()).toBe(true);
+ expect(mocks.recordingTabIds.has(TEST_RUNTIME_TAB_ID)).toBe(true);
+ });
+
+ it("does not rerender while loading time passes", async () => {
+ vi.useFakeTimers();
+ mocks.loading = true;
+ const onRender = vi.fn();
+ await render(
+ <Profiler id="preview" onRender={onRender}>
+ {view()}
+ </Profiler>,
+ );
+ const initialRenderCount = onRender.mock.calls.length;
+ await act(() => vi.advanceTimersByTimeAsync(1_000));
+ expect(onRender).toHaveBeenCalledTimes(initialRenderCount);
+ });
+
+ it.each([
+ [
+ "https://localhost:8000/dashboard?mode=test#top",
+ "https://localhost:8000/dashboard?mode=test#top",
+ ],
+ ["localhost:5173/app", "http://localhost:5173/app"],
+ ])(
+ "preserves a direct localhost URL %s in a WSL environment and records it",
+ async (submitted, expected) => {
+ await render(view());
+ await submitAddress(submitted);
+ await vi.waitFor(() =>
+ expect(mocks.navigate).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID, expected),
+ );
+ expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(TEST_THREAD_REF, expected);
+ expect(mocks.recordVisitForThread).toHaveBeenCalledWith(TEST_THREAD_REF, expected);
+ },
+ );
+
+ it("maps an empty-state localhost server onto the WSL host", async () => {
+ mocks.showEmptyState = true;
+ mocks.servers = [
+ {
+ host: "localhost",
+ port: 5173,
+ url: "http://localhost:5173/app?mode=test#top",
+ requestedUrl: "http://localhost:5173/app?mode=test#top",
+ processName: "vite",
+ pid: 1,
+ terminal: null,
+ source: "scanner",
+ } as unknown as PreviewableServer,
+ ];
+ await render(view());
+ await userEvent.click(page.getByRole("button", { name: /vite/ }));
+
+ await vi.waitFor(() =>
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ TEST_RUNTIME_TAB_ID,
+ "http://172.25.85.75:5173/app?mode=test#top",
+ ),
+ );
+ expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
+ TEST_THREAD_REF,
+ "http://172.25.85.75:5173/app?mode=test#top",
+ );
+ // History keys off the requested loopback URL, which stays stable across hosts.
+ await vi.waitFor(() =>
+ expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
+ TEST_THREAD_REF,
+ "http://localhost:5173/app?mode=test#top",
+ ),
+ );
+ });
+
+ it("opens and closes a thread-scoped floating preview for the active tab", async () => {
+ await render(view());
+ await userEvent.click(page.getByRole("button", { name: "Float preview over chat" }));
+ expect(usePreviewMiniPlayerStore.getState().byThreadKey).toMatchObject({
+ "environment-1:thread-1": { source: { kind: "browser", tabId: "tab-1" } },
+ });
+ const closeButton = page.getByRole("button", { name: "Close floating preview" });
+ await expect.element(closeButton).toHaveAttribute("aria-pressed", "true");
+ await userEvent.click(closeButton);
+ expect(usePreviewMiniPlayerStore.getState().byThreadKey).toEqual({});
+ });
+
+ it("keeps the native preview window as a secondary menu action", async () => {
+ await render(view());
+ await userEvent.click(page.getByRole("button", { name: "Preview menu" }));
+ await userEvent.click(page.getByRole("menuitem", { name: "Open separate preview window" }));
+ await vi.waitFor(() =>
+ expect(mocks.openPictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
+ );
+ await vi.waitFor(() => expect(document.querySelector('[role="menu"]')).toBeNull());
+
+ mocks.pictureInPicture = true;
+ await render(view());
+ await userEvent.click(page.getByRole("button", { name: "Preview menu" }));
+ await userEvent.click(page.getByRole("menuitem", { name: "Close separate preview window" }));
+ await vi.waitFor(() =>
+ expect(mocks.closePictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
+ );
+ });
+
+ it("forwards Cmd/Ctrl+Enter annotations to the composer send path", async () => {
+ const picked = annotation("annotation-1");
+ const onSendAnnotation = vi.fn();
+ mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
+ await render(view(onSendAnnotation));
+ await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
+
+ await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
+ expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, picked);
+ });
+
+ it("retains the annotation locally when its own environment loses access during capture", async () => {
+ const picked = annotation("annotation-revoked");
+ const onSendAnnotation = vi.fn();
+ let submitPick: (() => void) | undefined;
+ mocks.pickElement.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ submitPick = () => resolve({ annotation: picked, submission: "send" });
+ }),
+ );
+ await render(view(onSendAnnotation));
+ await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
+ await vi.waitFor(() => expect(submitPick).toBeDefined());
+ expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
+
+ mocks.readEnvironmentScope.mockImplementation(
+ (environmentId?: unknown) => environmentId !== TEST_THREAD_REF.environmentId,
+ );
+ await render(view(onSendAnnotation));
+ expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, false);
+ await act(async () => submitPick!());
+ await vi.waitFor(() =>
+ expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, picked),
+ );
+ expect(onSendAnnotation).not.toHaveBeenCalled();
+
+ mocks.readEnvironmentScope.mockReturnValue(true);
+ mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
+ await render(view(onSendAnnotation));
+ await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
+ await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
+ expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
+ });
+
+ it("does not reopen a cancelled picker after the permission update finishes", async () => {
+ let finishUpdate: (() => void) | undefined;
+ mocks.setAnnotationSendEnabled.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finishUpdate = resolve;
+ }),
+ );
+ await render(view());
+ await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
+ await vi.waitFor(() => expect(finishUpdate).toBeDefined());
+ expect(mocks.pickElement).not.toHaveBeenCalled();
+ await userEvent.click(page.getByRole("button", { name: "Cancel annotation" }));
+ expect(mocks.cancelPickElement).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID);
+ await act(async () => finishUpdate!());
+ expect(mocks.pickElement).not.toHaveBeenCalled();
+ expect(mocks.addPreviewAnnotation).not.toHaveBeenCalled();
+ });
+
+ it("warns when main dropped the crop before handing over the pick", async () => {
+ const picked = annotation("annotation-3");
+ const onSendAnnotation = vi.fn();
+ mocks.pickElement.mockResolvedValue({
+ annotation: picked,
+ submission: "send",
+ screenshotFailed: true,
+ });
+ await render(view(onSendAnnotation));
+ await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
+
+ await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
+ expect(mocks.toast).toHaveBeenCalledOnce();
+ });
+
+ it("still sends annotation text when the picked element's crop is malformed", async () => {
+ const picked = annotation("annotation-2", {
+ dataUrl: "data:image/png;base64,%%%",
+ width: 10,
+ height: 10,
+ cropRect: { x: 0, y: 0, width: 10, height: 10 },
+ });
+ const onSendAnnotation = vi.fn();
+ mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
+ await render(view(onSendAnnotation));
+ await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
+
+ const sent = { ...picked, screenshot: null };
+ await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(sent, null));
+ expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, sent);
+ expect(mocks.addImage).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/components/preview/PreviewView.test.tsx b/apps/web/src/components/preview/PreviewView.test.tsx
deleted file mode 100644
index 684c95307a5..00000000000
--- a/apps/web/src/components/preview/PreviewView.test.tsx
+++ /dev/null
@@ -1,751 +0,0 @@
-import {
- BUILT_IN_BROWSER_PROFILES,
- DEFAULT_BROWSER_PROFILE_ID,
- DEFAULT_PREVIEW_APPEARANCE,
- DEFAULT_PREVIEW_ZOOM_FACTOR,
- EnvironmentId,
- FILL_PREVIEW_VIEWPORT,
- ThreadId,
-} from "@t3tools/contracts";
-import { act, createElement, Profiler } from "react";
-import { renderToStaticMarkup } from "react-dom/server";
-import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
-
-const mocks = vi.hoisted(() => ({
- navigate: vi.fn(async (_tabId: string, _url: string): Promise<void> => undefined),
- rememberPreviewUrl: vi.fn(),
- readPreparedConnection: vi.fn(() => ({ httpBaseUrl: "http://172.25.85.75:3773" })),
- readEnvironmentScope: vi.fn(() => true),
- setAnnotationSendEnabled: vi.fn(async (): Promise<void> => undefined),
- cancelPickElement: vi.fn(async () => undefined),
- submittedUrl: null as ((url: string) => void) | null,
- emptyStateUrl: null as ((url: string) => void) | null,
- togglePictureInPicture: null as (() => void) | null,
- toggleNativePictureInPicture: null as (() => void) | null,
- pictureInPicturePressed: false,
- miniPlayerTabId: null as string | null,
- openMiniPlayer: vi.fn(),
- closeMiniPlayer: vi.fn(),
- closeRightPanel: vi.fn(),
- openPictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
- closePictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
- pickElement: vi.fn(),
- addPreviewAnnotation: vi.fn(),
- addImage: vi.fn(),
- toggleAnnotation: null as (() => void) | null,
- pictureInPicture: false,
- showEmptyState: false,
- loading: false,
- serverEpoch: null as string | null,
- recordingTabIds: new Set<string>(),
- recordingRuntimeTabId: null as string | null,
- recordVisitForThread: vi.fn(),
-}));
-
-const EMPTY_HISTORY: never[] = [];
-
-const STUB_BROWSER_DEFAULTS = {
- viewport: FILL_PREVIEW_VIEWPORT,
- zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
- appearance: DEFAULT_PREVIEW_APPEARANCE,
- autoShowFloatingPreview: true,
- profiles: BUILT_IN_BROWSER_PROFILES,
- profileId: DEFAULT_BROWSER_PROFILE_ID,
-};
-
-vi.mock("~/browserHistoryStore", () => ({
- recordVisitForThread: mocks.recordVisitForThread,
- setTitleForThreadUrl: vi.fn(),
- removeUrlForThread: vi.fn(),
- BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT: 50,
- useThreadRecentHistory: () => EMPTY_HISTORY,
-}));
-
-vi.mock("~/state/session", async (importOriginal) => ({
- ...(await importOriginal<typeof import("~/state/session")>()),
- readPreparedConnection: mocks.readPreparedConnection,
- readEnvironmentScope: mocks.readEnvironmentScope,
- useEnvironmentScope: mocks.readEnvironmentScope,
-}));
-
-vi.mock("~/assets/assetUrls", async () => {
- const { resolveAssetUrl } = await import("@t3tools/client-runtime/state/assets");
- return { resolveAssetUrl };
-});
-
-vi.mock("~/browser/browserDefaults", () => ({
- useBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
- getBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
- browserDefaultOpenViewport: () => FILL_PREVIEW_VIEWPORT,
- browserDefaultOpenProfileId: () => DEFAULT_BROWSER_PROFILE_ID,
- browserDefaultTabState: () => ({
- zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
- colorScheme: DEFAULT_PREVIEW_APPEARANCE,
- }),
- browserResponsiveViewportForToggle: () => ({
- _tag: "freeform" as const,
- width: 1024,
- height: 768,
- }),
-}));
-
-vi.mock("~/composerDraftStore", () => ({
- useComposerDraftStore: (
- select: (store: { addPreviewAnnotation: () => void; addImage: () => void }) => unknown,
- ) =>
- select({
- addPreviewAnnotation: mocks.addPreviewAnnotation,
- addImage: mocks.addImage,
- }),
-}));
-
-vi.mock("~/localApi", () => ({
- ensureLocalApi: vi.fn(),
-}));
-
-vi.mock("~/previewStateStore", () => ({
- rememberPreviewUrl: mocks.rememberPreviewUrl,
- updatePreviewServerSnapshot: vi.fn(),
- useThreadPreviewState: () => ({
- activeTabId: "tab-1",
- serverEpoch: mocks.serverEpoch,
- desktopByTabId: {
- "tab-1": {
- hasWebContents: true,
- canGoBack: false,
- canGoForward: false,
- loading: mocks.loading,
- zoomFactor: 1,
- pictureInPicture: mocks.pictureInPicture,
- colorScheme: "system",
- audioMuted: false,
- audible: false,
- controller: "none",
- },
- },
- recentlySeenUrls: [],
- sessions: mocks.showEmptyState
- ? {}
- : {
- "tab-1": {
- threadId: "thread-1",
- tabId: "tab-1",
- navStatus: {
- _tag: "Success",
- url: "http://example.com/",
- title: "Example",
- },
- canGoBack: false,
- canGoForward: false,
- updatedAt: "2026-07-13T00:00:00.000Z",
- },
- },
- }),
-}));
-
-vi.mock("~/state/environments", () => ({
- useEnvironment: () => ({ label: "WSL" }),
- useEnvironmentHttpBaseUrl: () => "http://172.25.85.75:3773",
- usePrimaryEnvironmentId: () => null,
-}));
-
-vi.mock("~/state/preview", () => ({
- previewEnvironment: { open: {}, close: {}, resize: {} },
-}));
-
-vi.mock("~/state/use-atom-command", () => ({
- useAtomCommand: () => vi.fn(),
-}));
-
-vi.mock("~/browser/browserRecording", () => ({
- findActiveBrowserRecordingRuntimeTabId: () => mocks.recordingRuntimeTabId,
- isBrowserRecordingStartCancelledError: vi.fn(() => false),
- startBrowserRecording: vi.fn(),
- stopBrowserRecording: vi.fn(),
- useActiveBrowserRecordingTabIds: () => mocks.recordingTabIds,
-}));
-
-vi.mock("~/browser/browserSurfaceStore", () => ({
- useBrowserSurfaceStore: (
- select: (state: { byTabId: Record<string, { rect?: unknown }> }) => unknown,
- ) => select({ byTabId: {} }),
-}));
-
-vi.mock("~/previewMiniPlayerStore", () => {
- const usePreviewMiniPlayerStore = Object.assign(
- (select: (state: unknown) => unknown) =>
- select({
- byThreadKey: mocks.miniPlayerTabId
- ? {
- "environment-1:thread-1": {
- source: { kind: "browser", tabId: mocks.miniPlayerTabId },
- position: null,
- },
- }
- : {},
- }),
- {
- getState: () => ({
- open: mocks.openMiniPlayer,
- close: mocks.closeMiniPlayer,
- }),
- },
- );
- return {
- browserMiniPlayerSource: (tabId: string) => ({ kind: "browser", tabId }),
- selectThreadPreviewMiniPlayerTabId: (
- byThreadKey: Record<string, { source: { tabId: string }; position: null }>,
- ) => byThreadKey["environment-1:thread-1"]?.source.tabId ?? null,
- usePreviewMiniPlayerStore,
- };
-});
-
-vi.mock("~/rightPanelStore", () => ({
- useRightPanelStore: {
- getState: () => ({ close: mocks.closeRightPanel }),
- },
-}));
-
-vi.mock("~/components/ui/toast", () => ({
- stackedThreadToast: vi.fn(),
- toastManager: { add: vi.fn() },
-}));
-
-vi.mock("./previewBridge", () => ({
- previewBridge: {
- navigate: mocks.navigate,
- pickElement: mocks.pickElement,
- setAnnotationSendEnabled: mocks.setAnnotationSendEnabled,
- cancelPickElement: mocks.cancelPickElement,
- pictureInPicture: {
- open: mocks.openPictureInPicture,
- close: mocks.closePictureInPicture,
- },
- },
-}));
-
-vi.mock("./PreviewChromeRow", () => ({
- PreviewChromeRow: (props: {
- onSubmit: (url: string) => void;
- onPickElement?: () => void;
- onPictureInPicture?: () => void;
- pictureInPicture?: boolean;
- trailingActions?: {
- props: { actions?: { toggleNativePictureInPicture?: () => void } };
- };
- }) => {
- mocks.submittedUrl = props.onSubmit;
- mocks.toggleAnnotation = props.onPickElement ?? null;
- mocks.togglePictureInPicture = props.onPictureInPicture ?? null;
- mocks.toggleNativePictureInPicture =
- props.trailingActions?.props.actions?.toggleNativePictureInPicture ?? null;
- mocks.pictureInPicturePressed = props.pictureInPicture ?? false;
- return null;
- },
-}));
-
-vi.mock("./PreviewEmptyState", () => ({
- PreviewEmptyState: (props: { onOpenUrl: (url: string) => void }) => {
- mocks.emptyStateUrl = props.onOpenUrl;
- return null;
- },
-}));
-vi.mock("./PreviewMoreMenu", () => ({
- PreviewMoreMenu: (props: { actions: { toggleNativePictureInPicture?: () => void } }) => {
- mocks.toggleNativePictureInPicture = props.actions.toggleNativePictureInPicture ?? null;
- return null;
- },
-}));
-vi.mock("./PreviewUnreachable", () => ({ PreviewUnreachable: () => null }));
-vi.mock("./ZoomIndicator", () => ({ ZoomIndicator: () => null }));
-vi.mock("./AgentBrowserCursor", () => ({
- AgentBrowserCursor: () => createElement("agent-cursor"),
-}));
-vi.mock("~/browser/BrowserSurfaceSlot", () => ({ BrowserSurfaceSlot: () => null }));
-vi.mock("./usePreviewSession", () => ({ usePreviewSession: vi.fn() }));
-
-import { PreviewView } from "./PreviewView";
-import { toastManager } from "~/components/ui/toast";
-import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
-
-const TEST_THREAD_REF = {
- environmentId: EnvironmentId.make("environment-1"),
- threadId: ThreadId.make("thread-1"),
-} as const;
-const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
-
-// ReactDOM needs a host, but this unit suite intentionally has no DOM dependency.
-class TestNode {
- parentNode: TestNode | null = null;
- childNodes: TestNode[] = [];
- readonly nodeName: string;
- readonly tagName: string;
- readonly namespaceURI = "http://www.w3.org/1999/xhtml";
- readonly style = {};
-
- constructor(
- name: string,
- readonly ownerDocument: TestNode | null = null,
- readonly nodeType = 1,
- ) {
- this.nodeName = name.toUpperCase();
- this.tagName = this.nodeName;
- }
-
- set textContent(_value: string) {
- this.childNodes = [];
- }
-
- appendChild(child: TestNode) {
- child.parentNode = this;
- this.childNodes.push(child);
- return child;
- }
-
- removeChild(child: TestNode) {
- this.childNodes.splice(this.childNodes.indexOf(child), 1);
- child.parentNode = null;
- return child;
- }
-
- createElement(name: string) {
- return new TestNode(name, this);
- }
-
- addEventListener() {}
- removeEventListener() {}
- setAttribute() {}
-}
-
-function installTestDom() {
- const document = new TestNode("#document", null, 9);
- const window = {
- document,
- HTMLIFrameElement: TestNode,
- setInterval: globalThis.setInterval,
- clearInterval: globalThis.clearInterval,
- setTimeout: globalThis.setTimeout,
- clearTimeout: globalThis.clearTimeout,
- addEventListener() {},
- removeEventListener() {},
- };
- vi.stubGlobal("document", document);
- vi.stubGlobal("window", window);
- vi.stubGlobal("HTMLIFrameElement", window.HTMLIFrameElement);
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- return document;
-}
-
-describe("PreviewView navigation", () => {
- beforeEach(() => {
- mocks.navigate.mockClear();
- mocks.rememberPreviewUrl.mockClear();
- mocks.readPreparedConnection.mockClear();
- mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
- mocks.setAnnotationSendEnabled.mockClear();
- mocks.cancelPickElement.mockClear();
- mocks.submittedUrl = null;
- mocks.emptyStateUrl = null;
- mocks.togglePictureInPicture = null;
- mocks.toggleNativePictureInPicture = null;
- mocks.pictureInPicturePressed = false;
- mocks.miniPlayerTabId = null;
- mocks.openMiniPlayer.mockClear();
- mocks.closeMiniPlayer.mockClear();
- mocks.closeRightPanel.mockClear();
- mocks.openPictureInPicture.mockClear();
- mocks.closePictureInPicture.mockClear();
- mocks.pickElement.mockReset();
- mocks.addPreviewAnnotation.mockClear();
- vi.mocked(toastManager.add).mockClear();
- mocks.addImage.mockClear();
- mocks.toggleAnnotation = null;
- mocks.pictureInPicture = false;
- mocks.showEmptyState = false;
- mocks.loading = false;
- mocks.serverEpoch = null;
- mocks.recordingTabIds = new Set();
- mocks.recordingRuntimeTabId = null;
- mocks.recordVisitForThread.mockClear();
- });
-
- it("shows the cursor in a replacement browser while the old instance still records", async () => {
- const document = installTestDom();
- const { createRoot } = await import("react-dom/client");
- const container = document.createElement("div");
- const root = createRoot(container as unknown as Element);
- const hasCursor = (node: TestNode): boolean =>
- node.nodeName === "AGENT-CURSOR" || node.childNodes.some(hasCursor);
- mocks.recordingTabIds.add(TEST_RUNTIME_TAB_ID);
- mocks.recordingRuntimeTabId = TEST_RUNTIME_TAB_ID;
- try {
- await act(() => {
- root.render(<PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />);
- });
- expect(hasCursor(container)).toBe(false);
- mocks.serverEpoch = "replacement-server";
- await act(() => {
- root.render(<PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />);
- });
- expect(hasCursor(container)).toBe(true);
- expect(mocks.recordingTabIds.has(TEST_RUNTIME_TAB_ID)).toBe(true);
- } finally {
- await act(() => root.unmount());
- vi.unstubAllGlobals();
- }
- });
-
- it("does not rerender while loading time passes", async () => {
- vi.useFakeTimers();
- mocks.loading = true;
- const document = installTestDom();
- const { createRoot } = await import("react-dom/client");
- const root = createRoot(document.createElement("div") as unknown as Element);
- const onRender = vi.fn();
-
- try {
- await act(() => {
- root.render(
- <Profiler id="preview" onRender={onRender}>
- <PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />
- </Profiler>,
- );
- });
- const initialRenderCount = onRender.mock.calls.length;
-
- await act(() => vi.advanceTimersByTimeAsync(1_000));
-
- expect(onRender).toHaveBeenCalledTimes(initialRenderCount);
- } finally {
- await act(() => root.unmount());
- vi.useRealTimers();
- vi.unstubAllGlobals();
- }
- });
-
- it.each([
- [
- "https://localhost:8000/dashboard?mode=test#top",
- "https://localhost:8000/dashboard?mode=test#top",
- ],
- ["localhost:5173/app", "http://localhost:5173/app"],
- ])("preserves a direct localhost URL in a WSL environment", async (submitted, expected) => {
- renderToStaticMarkup(
- <PreviewView
- threadRef={{
- environmentId: EnvironmentId.make("environment-1"),
- threadId: ThreadId.make("thread-1"),
- }}
- tabId="tab-1"
- visible
- />,
- );
-
- expect(mocks.submittedUrl).not.toBeNull();
- mocks.submittedUrl?.(submitted);
-
- await vi.waitFor(() =>
- expect(mocks.navigate).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID, expected),
- );
- expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
- {
- environmentId: "environment-1",
- threadId: "thread-1",
- },
- expected,
- );
- });
-
- it("records a history visit with the normalized requested url on submit", async () => {
- renderToStaticMarkup(
- <PreviewView
- threadRef={{
- environmentId: EnvironmentId.make("environment-1"),
- threadId: ThreadId.make("thread-1"),
- }}
- tabId="tab-1"
- visible
- />,
- );
-
- mocks.submittedUrl?.("localhost:3000/admin");
- await vi.waitFor(() => {
- expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
- expect.objectContaining({ threadId: expect.anything() }),
- "http://localhost:3000/admin",
- );
- });
- });
-
- it("maps an empty-state localhost server onto the WSL host", async () => {
- mocks.showEmptyState = true;
- renderToStaticMarkup(
- <PreviewView
- threadRef={{
- environmentId: EnvironmentId.make("environment-1"),
- threadId: ThreadId.make("thread-1"),
- }}
- tabId="tab-1"
- visible
- />,
- );
-
- expect(mocks.emptyStateUrl).not.toBeNull();
- mocks.emptyStateUrl?.("http://localhost:5173/app?mode=test#top");
-
- await vi.waitFor(() =>
- expect(mocks.navigate).toHaveBeenCalledWith(
- TEST_RUNTIME_TAB_ID,
- "http://172.25.85.75:5173/app?mode=test#top",
- ),
- );
- expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
- {
- environmentId: "environment-1",
- threadId: "thread-1",
- },
- "http://172.25.85.75:5173/app?mode=test#top",
- );
- await vi.waitFor(() =>
- expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
- expect.objectContaining({ threadId: expect.anything() }),
- "http://localhost:5173/app?mode=test#top",
- ),
- );
- });
-
- it("opens and closes a thread-scoped floating preview for the active tab", async () => {
- const props = {
- threadRef: {
- environmentId: EnvironmentId.make("environment-1"),
- threadId: ThreadId.make("thread-1"),
- },
- tabId: "tab-1",
- visible: true,
- } as const;
-
- renderToStaticMarkup(<PreviewView {...props} />);
- expect(mocks.pictureInPicturePressed).toBe(false);
- mocks.togglePictureInPicture?.();
- expect(mocks.openMiniPlayer).toHaveBeenCalledWith(props.threadRef, {
- kind: "browser",
- tabId: "tab-1",
- });
- expect(mocks.closeRightPanel).toHaveBeenCalledWith(props.threadRef);
-
- mocks.miniPlayerTabId = "tab-1";
- renderToStaticMarkup(<PreviewView {...props} />);
- expect(mocks.pictureInPicturePressed).toBe(true);
- mocks.togglePictureInPicture?.();
- expect(mocks.closeMiniPlayer).toHaveBeenCalledWith(props.threadRef);
- });
-
- it("keeps the native preview window as a secondary action", async () => {
- const props = {
- threadRef: {
- environmentId: EnvironmentId.make("environment-1"),
- threadId: ThreadId.make("thread-1"),
- },
- tabId: "tab-1",
- visible: true,
- } as const;
-
- renderToStaticMarkup(<PreviewView {...props} />);
- mocks.toggleNativePictureInPicture?.();
- await vi.waitFor(() =>
- expect(mocks.openPictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
- );
-
- mocks.pictureInPicture = true;
- renderToStaticMarkup(<PreviewView {...props} />);
- mocks.toggleNativePictureInPicture?.();
- await vi.waitFor(() =>
- expect(mocks.closePictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
- );
- });
-
- it("forwards Cmd/Ctrl+Enter annotations to the composer send path", async () => {
- const annotation = {
- id: "annotation-1",
- pageUrl: "https://example.com/dashboard",
- pageTitle: "Dashboard",
- comment: "Tighten this spacing",
- elements: [],
- regions: [],
- strokes: [],
- styleChanges: [],
- screenshot: null,
- createdAt: "2026-07-27T00:00:00.000Z",
- };
- const onSendAnnotation = vi.fn();
- mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
-
- renderToStaticMarkup(
- <PreviewView
- threadRef={TEST_THREAD_REF}
- tabId="tab-1"
- visible
- onSendAnnotation={onSendAnnotation}
- />,
- );
- mocks.toggleAnnotation?.();
-
- await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
- expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, annotation);
- });
-
- it("retains the annotation locally when its own environment loses access during capture", async () => {
- const annotation = {
- id: "annotation-revoked",
- pageUrl: "https://example.com/dashboard",
- pageTitle: "Dashboard",
- comment: "Tighten this spacing",
- elements: [],
- regions: [],
- strokes: [],
- styleChanges: [],
- screenshot: null,
- createdAt: "2026-09-05T00:00:00.000Z",
- };
- const onSendAnnotation = vi.fn();
- let submitPick: (() => void) | undefined;
- mocks.pickElement.mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- submitPick = () => resolve({ annotation, submission: "send" });
- }),
- );
- const document = installTestDom();
- const { createRoot } = await import("react-dom/client");
- const root = createRoot(document.createElement("div") as unknown as Element);
- const view = () => (
- <PreviewView
- threadRef={TEST_THREAD_REF}
- tabId="tab-1"
- visible
- onSendAnnotation={onSendAnnotation}
- />
- );
- try {
- await act(async () => root.render(view()));
- await act(async () => mocks.toggleAnnotation?.());
- expect(submitPick).toBeDefined();
- expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
-
- mocks.readEnvironmentScope.mockImplementation(
- (environmentId?: unknown) => environmentId !== TEST_THREAD_REF.environmentId,
- );
- await act(async () => root.render(view()));
- expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, false);
- await act(async () => submitPick!());
- expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, annotation);
- expect(onSendAnnotation).not.toHaveBeenCalled();
-
- mocks.readEnvironmentScope.mockReturnValue(true);
- mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
- await act(async () => root.render(view()));
- await act(async () => mocks.toggleAnnotation?.());
- expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
- expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null);
- } finally {
- await act(async () => root.unmount());
- vi.unstubAllGlobals();
- }
- });
-
- it("does not reopen a cancelled picker after the permission update finishes", async () => {
- let finishUpdate: (() => void) | undefined;
- mocks.setAnnotationSendEnabled.mockImplementationOnce(
- () =>
- new Promise<void>((resolve) => {
- finishUpdate = resolve;
- }),
- );
- const document = installTestDom();
- const { createRoot } = await import("react-dom/client");
- const root = createRoot(document.createElement("div") as unknown as Element);
- try {
- await act(async () =>
- root.render(<PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />),
- );
- await act(async () => mocks.toggleAnnotation?.());
- expect(finishUpdate).toBeDefined();
- expect(mocks.pickElement).not.toHaveBeenCalled();
- await act(async () => mocks.toggleAnnotation?.());
- expect(mocks.cancelPickElement).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID);
- await act(async () => finishUpdate!());
- expect(mocks.pickElement).not.toHaveBeenCalled();
- expect(mocks.addPreviewAnnotation).not.toHaveBeenCalled();
- } finally {
- await act(async () => root.unmount());
- vi.unstubAllGlobals();
- }
- });
-
- it("warns when main dropped the crop before handing over the pick", async () => {
- const annotation = {
- id: "annotation-3",
- pageUrl: "https://example.com/dashboard",
- pageTitle: "Dashboard",
- comment: "Tighten this spacing",
- elements: [],
- regions: [],
- strokes: [],
- styleChanges: [],
- screenshot: null,
- createdAt: "2026-07-27T00:00:00.000Z",
- };
- const onSendAnnotation = vi.fn();
- mocks.pickElement.mockResolvedValue({ annotation, submission: "send", screenshotFailed: true });
-
- renderToStaticMarkup(
- <PreviewView
- threadRef={TEST_THREAD_REF}
- tabId="tab-1"
- visible
- onSendAnnotation={onSendAnnotation}
- />,
- );
- mocks.toggleAnnotation?.();
-
- await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
- expect(toastManager.add).toHaveBeenCalledTimes(1);
- });
-
- it("still sends annotation text when the picked element's crop is malformed", async () => {
- const annotation = {
- id: "annotation-2",
- pageUrl: "https://example.com/dashboard",
- pageTitle: "Dashboard",
- comment: "Tighten this spacing",
- elements: [],
- regions: [],
- strokes: [],
- styleChanges: [],
- screenshot: {
- dataUrl: "data:image/png;base64,%%%",
- width: 10,
- height: 10,
- cropRect: { x: 0, y: 0, width: 10, height: 10 },
- },
- createdAt: "2026-07-27T00:00:00.000Z",
- };
- const onSendAnnotation = vi.fn();
- mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
-
- renderToStaticMarkup(
- <PreviewView
- threadRef={TEST_THREAD_REF}
- tabId="tab-1"
- visible
- onSendAnnotation={onSendAnnotation}
- />,
- );
- mocks.toggleAnnotation?.();
-
- const sent = { ...annotation, screenshot: null };
- await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(sent, null));
- expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, sent);
- expect(mocks.addImage).not.toHaveBeenCalled();
- });
-});
diff --git a/apps/web/src/components/usage/UsagePage.test.tsx b/apps/web/src/components/usage/UsagePage.browser.test.tsx
similarity index 62%
rename from apps/web/src/components/usage/UsagePage.test.tsx
rename to apps/web/src/components/usage/UsagePage.browser.test.tsx
index cf821e7dfc5..16ce09b401a 100644
--- a/apps/web/src/components/usage/UsagePage.test.tsx
+++ b/apps/web/src/components/usage/UsagePage.browser.test.tsx
@@ -3,6 +3,9 @@ import { mergeUsage } from "@t3tools/shared/usageMerge";
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import { page, userEvent } from "vite-plus/test/browser";
+
+import "~/index.css";
const testState = vi.hoisted(() => ({
useUsage: vi.fn(),
@@ -10,43 +13,15 @@ const testState = vi.hoisted(() => ({
canGoBack: true,
}));
-vi.mock("../../env", () => ({ isElectron: false }));
-vi.mock("@tanstack/react-router", () => ({
- useNavigate: () => testState.navigate,
+vi.mock(import("@tanstack/react-router"), async (original) => ({
+ ...(await original()),
+ useNavigate: (() => testState.navigate) as never,
useCanGoBack: () => testState.canGoBack,
}));
-vi.mock("../../state/usage", () => ({ useUsage: testState.useUsage }));
-vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));
-vi.mock("../ui/select", () => ({
- Select: "div",
- SelectItem: "div",
- SelectPopup: "div",
- SelectTrigger: "div",
- SelectValue: "div",
-}));
-vi.mock("../ui/sidebar", () => ({ SidebarInset: "div" }));
-vi.mock("../ui/toggle-group", () => ({ Toggle: "button", ToggleGroup: "div" }));
-vi.mock("../WorkspaceBreadcrumb", () => ({
- WorkspaceBreadcrumb: "div",
- WorkspaceBreadcrumbItem: "div",
- WorkspaceBreadcrumbSeparator: "span",
- WorkspaceBreadcrumbText: "span",
+vi.mock(import("../../state/usage"), async (original) => ({
+ ...(await original()),
+ useUsage: testState.useUsage,
}));
-vi.mock("../WorkspacePageContainer", () => ({ WorkspacePageContainer: "main" }));
-vi.mock("../WorkspacePageHeader", () => ({ WorkspacePageHeader: "header" }));
-vi.mock("./UsageProviderChart", () => ({ UsageProviderChart: "div" }));
-vi.mock("./UsagePriceOverrides", () => ({ UsagePriceOverrides: () => null }));
-vi.mock("./usageProviders", async (importOriginal) => {
- const actual = await importOriginal<typeof import("./usageProviders")>();
- return {
- ...actual,
- PROVIDER_ORDER: ["codex", "claude"],
- PROVIDER_PRESENTATION: {
- codex: { color: "white", label: "Codex", mark: "span" },
- claude: { color: "orange", label: "Claude Code", mark: "span" },
- },
- };
-});
import { UsagePage } from "./UsagePage";
const environments = [
@@ -91,7 +66,6 @@ describe("UsagePage Escape navigation", () => {
back = vi.spyOn(window.history, "back").mockImplementation(() => {});
testState.navigate.mockClear();
testState.canGoBack = true;
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
container = document.createElement("div");
document.body.append(container);
renderer = createRoot(container);
@@ -104,9 +78,9 @@ describe("UsagePage Escape navigation", () => {
await act(() => renderer.unmount());
container.remove();
back.mockRestore();
- vi.unstubAllGlobals();
});
+ // Playwright cannot press a repeating or composing key, so those cases dispatch the event.
function escape(properties: { repeat?: boolean; isComposing?: boolean } = {}) {
return new KeyboardEvent("keydown", {
bubbles: true,
@@ -116,8 +90,8 @@ describe("UsagePage Escape navigation", () => {
});
}
- it("returns to the previous page on Escape", () => {
- document.body.dispatchEvent(escape());
+ it("returns to the previous page on Escape", async () => {
+ await userEvent.keyboard("{Escape}");
expect(back).toHaveBeenCalledOnce();
expect(testState.navigate).not.toHaveBeenCalled();
});
@@ -126,23 +100,22 @@ describe("UsagePage Escape navigation", () => {
testState.canGoBack = false;
await act(() => renderer.render(<UsagePage />));
- document.body.dispatchEvent(escape());
+ await userEvent.keyboard("{Escape}");
expect(testState.navigate).toHaveBeenCalledWith({ to: "/" });
expect(back).not.toHaveBeenCalled();
});
it("closes the environment menu before Escape navigates back", async () => {
const trigger = container.querySelector<HTMLButtonElement>('[data-slot="menu-trigger"]')!;
- await act(() => trigger.click());
- expect(document.querySelector('[role="menu"]')).not.toBeNull();
+ await userEvent.click(trigger);
+ await expect.element(page.getByRole("menu")).toBeVisible();
- await act(() => {
- document.activeElement!.dispatchEvent(escape());
- });
+ await userEvent.keyboard("{Escape}");
+ await vi.waitFor(() => expect(document.querySelector('[role="menu"]')).toBeNull());
expect(trigger.getAttribute("aria-expanded")).toBe("false");
expect(back).not.toHaveBeenCalled();
- document.body.dispatchEvent(escape());
+ await userEvent.keyboard("{Escape}");
expect(back).toHaveBeenCalledOnce();
});
@@ -152,5 +125,3 @@ describe("UsagePage Escape navigation", () => {
expect(testState.navigate).not.toHaveBeenCalled();
});
});
-
-// @vitest-environment jsdom