@devries-cameron20 / t3code Mirror · read-only / commits / 07680cf7ce
Fork 0

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

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

Synced Nov 23, 05:30 UTC

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

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

Julius Marminge committed Oct 17, 2026 at 05:51 UTC 07680cf7ceaf0920a23217104196f6c982fb37c4
5 files changed +707 -1048
apps/web/src/components/onboarding/WelcomeWizard.import.browser.test.tsx renamed
+123 -127
@@ -8,10 +8,13 @@ import {
8 type AuthEnvironmentScope,
9 type AuthSessionState,
10 } from "@t3tools/contracts";
11 -import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
12 -import { act, create, type ReactTestInstance, type ReactTestRenderer } from "react-test-renderer";
11 +import { AsyncResult, Atom } from "effect/reactivity";
12 +import { act } from "react";
13 +import { createRoot, type Root } from "react-dom/client";
14 import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
15
16 +import "~/index.css";
17 +
18 type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
19 type Project = { id: ProjectId; environmentId: EnvironmentId; workspaceRoot: string };
20 type CreateProjectInput = {
@@ -20,11 +23,10 @@ type CreateProjectInput = {
23 };
24 const state = vi.hoisted(() => ({
25 selectedEnvironment: "primary",
23 - registry: null as AtomRegistry.AtomRegistry | null,
24 - sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),
25 - projects: null as Atom.Writable<ReadonlyArray<Project>> | null,
26 - providers: null as Atom.Atom<ReadonlyArray<never>> | null,
27 - config: null as Atom.Atom<null> | null,
26 + sessions: new Map<string, unknown>(),
27 + projects: null as unknown,
28 + providers: null as unknown,
29 + config: null as unknown,
30 candidates: [] as AgentSessionProjectCandidate[],
31 createProject: vi.fn(),
32 importThreads: vi.fn(),
@@ -36,30 +38,28 @@ const state = vi.hoisted(() => ({
38 refreshScan: vi.fn(),
39 }));
40
39 -vi.mock("../../connection/runtime", () => ({ connectionAtomRuntime: undefined }));
40 -vi.mock("@t3tools/client-runtime/state/session", () => ({
41 - createEnvironmentSessionAtoms: () => ({
42 - sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,
43 - }),
44 -}));
45 -vi.mock("../../rpc/atomRegistry", () => ({
46 - get appAtomRegistry() {
47 - return state.registry;
48 - },
49 -}));
50 -vi.mock("@clerk/react", () => ({ useAuth: () => ({ isLoaded: true, isSignedIn: false }) }));
51 -vi.mock("../../hooks/useTheme", () => ({ mountOnboardingTheme: () => () => {} }));
52 -vi.mock("../../hooks/useLocalStorage", () => ({ useLocalStorage: () => [false, () => {}] }));
53 -vi.mock("../../hooks/useCopyToClipboard", () => ({
54 - useCopyToClipboard: () => ({ copyToClipboard: vi.fn(), copied: false }),
41 +// Session grants come from per-test atoms so a test can revoke or regrant mid-flow; the
42 +// real scope checks in ~/state/session read them through the app registry, which the
43 +// wizard is also rendered with.
44 +vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => {
45 + const actual = await original();
46 + return {
47 + ...actual,
48 + createEnvironmentSessionAtoms: ((runtime: never) => ({
49 + ...actual.createEnvironmentSessionAtoms(runtime),
50 + sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id),
51 + })) as never,
52 + };
53 +});
54 +vi.mock(import("../../cloud/publicConfig"), async (original) => ({
55 + ...(await original()),
56 + hasCloudPublicConfig: () => false,
57 }));
56 -vi.mock("../../cloud/publicConfig", () => ({ hasCloudPublicConfig: () => false }));
57 -vi.mock("../clerk/useT3ConnectAuthPrompt", () => ({ useT3ConnectAuthPrompt: vi.fn() }));
58 -vi.mock("../../onboarding/firstRun", () => ({
58 +vi.mock(import("../../onboarding/firstRun"), async (original) => ({
59 + ...(await original()),
60 useCompleteOnboarding: () => state.completeOnboarding,
61 }));
61 -vi.mock("../../env", () => ({ isElectron: false }));
62 -vi.mock("../../state/environments", () => {
62 +vi.mock(import("../../state/environments"), async (original) => {
63 const environment = (environmentId: string) => ({
64 environmentId,
65 label: environmentId,
@@ -68,92 +68,75 @@ vi.mock("../../state/environments", () => {
68 });
69 const primary = environment("primary");
70 return {
71 - usePrimaryEnvironment: () => primary,
72 - useEnvironments: () => ({ environments: [environment(state.selectedEnvironment)] }),
71 + ...(await original()),
72 + usePrimaryEnvironment: (() => primary) as never,
73 + useEnvironments: (() => ({ environments: [environment(state.selectedEnvironment)] })) as never,
74 };
75 });
75 -vi.mock("../../state/server", () => ({
76 - serverEnvironment: {
77 - providersValueAtom: () => state.providers,
78 - configValueAtom: () => state.config,
79 - refreshProviders: "refreshProviders",
80 - },
81 -}));
82 -vi.mock("../../state/entities", async () => {
76 +vi.mock(import("../../state/server"), async (original) => {
77 + const actual = await original();
78 + return {
79 + ...actual,
80 + serverEnvironment: {
81 + ...actual.serverEnvironment,
82 + providersValueAtom: (() => state.providers) as never,
83 + configValueAtom: (() => state.config) as never,
84 + refreshProviders: "refreshProviders" as never,
85 + },
86 + };
87 +});
88 +vi.mock(import("../../state/entities"), async (original) => {
89 const { useAtomValue } = await import("@effect/atom-react");
90 return {
85 - useProjects: () => useAtomValue(state.projects!),
86 - readProjects: () => state.registry!.get(state.projects!),
91 + ...(await original()),
92 + useProjects: (() => useAtomValue(state.projects as Atom.Atom<Project[]>)) as never,
93 + readProjects: (() => appAtomRegistry.get(state.projects as Atom.Atom<Project[]>)) as never,
94 };
95 });
89 -vi.mock("../../state/projects", () => ({ projectEnvironment: { create: "createProject" } }));
90 -vi.mock("../../state/agentSessions", () => ({
91 - agentSessionScan: (query: { environmentId: EnvironmentId }) => query,
92 - agentSessionImport: "importThreads",
96 +vi.mock(import("../../state/projects"), async (original) => ({
97 + ...(await original()),
98 + projectEnvironment: { create: "createProject" } as never,
99 +}));
100 +vi.mock(import("../../state/agentSessions"), async (original) => ({
101 + ...(await original()),
102 + agentSessionImport: "importThreads" as never,
103 }));
94 -vi.mock("../../onboarding/useProjectScans", () => ({
95 - useProjectScans: (ids: EnvironmentId[]) =>
104 +vi.mock(import("../../onboarding/useProjectScans"), async (original) => ({
105 + ...(await original()),
106 + useProjectScans: (ids: readonly EnvironmentId[]) =>
107 ids.map((environmentId) => {
108 state.scan({ environmentId });
109 return {
110 environmentId,
100 - data: { candidates: state.candidates, truncated: false },
111 + data: { candidates: state.candidates, truncated: false } as never,
112 isPending: false,
113 error: null,
114 refresh: state.refreshScan,
115 };
116 }),
117 }));
107 -vi.mock("../ui/dialog", () => ({
108 - Dialog: "div",
109 - DialogPopup: "div",
110 - DialogTitle: "div",
111 - DialogHeader: "div",
118 +vi.mock(import("../../connection/onboarding"), async (original) => ({
119 + ...(await original()),
120 + connectPairing: "connectPairing" as never,
121 }));
113 -vi.mock("../ui/wizard", () => ({
114 - WizardPanel: "div",
115 - WizardSteps: "div",
116 - WizardPopup: "div",
117 - WizardHeader: "div",
118 -}));
119 -vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));
120 -vi.mock("../ui/tooltip", () => ({ Tooltip: "div", TooltipTrigger: "span", TooltipPopup: "span" }));
121 -vi.mock("../../connection/onboarding", () => ({ connectPairing: "connectPairing" }));
122 -vi.mock("../../state/use-atom-command", () => ({
123 - useAtomCommand: (
122 +vi.mock(import("../../state/use-atom-command"), async (original) => ({
123 + ...(await original()),
124 + useAtomCommand: ((
125 command: "createProject" | "importThreads" | "refreshProviders" | "connectPairing",
125 - ) => state[command],
126 -}));
127 -vi.mock("../../state/terminal", () => ({ terminalEnvironment: {} }));
128 -vi.mock("../ThreadTerminalDrawer", () => ({ TerminalViewport: "div" }));
129 -vi.mock("../cloud/CloudEnvironmentConnectList", () => ({ CloudEnvironmentConnectRows: "div" }));
130 -vi.mock("../settings/ChatGptWelcomeCoordinator", () => ({ ChatGptWelcomeCoordinator: () => null }));
131 -vi.mock("../settings/CodexSetupSection", () => ({
132 - CodexSetupSection: () => null,
133 - AddManagedCodexAccountDialog: () => null,
126 + ) => state[command]) as never,
127 }));
135 -vi.mock("../settings/providerDriverMeta", () => ({
136 - providerClients: { get: () => ({ label: "Agent" }) },
128 +vi.mock(import("../settings/ChatGptWelcomeCoordinator"), async (original) => ({
129 + ...(await original()),
130 + ChatGptWelcomeCoordinator: () => <></>,
131 }));
138 -vi.mock("../settings/providerStatus", () => ({
139 - getProviderSummary: () => ({ headline: "Checking", detail: null }),
140 -}));
141 -vi.mock("../ui/button", () => ({ Button: "button" }));
142 -vi.mock("../ui/input", () => ({ Input: "input" }));
143 -vi.mock("../ui/checkbox", () => ({ Checkbox: "input" }));
144 -vi.mock("../ui/collapsible", () => ({
145 - Collapsible: "div",
146 - CollapsiblePanel: "div",
147 - CollapsibleTrigger: "button",
148 -}));
149 -vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn(), close: vi.fn(), update: vi.fn() } }));
132
133 +import { appAtomRegistry } from "../../rpc/atomRegistry";
134 import { WelcomeWizard } from "./WelcomeWizard";
135
136 const primaryId = EnvironmentId.make("primary");
137 const remoteId = EnvironmentId.make("remote");
138 const permissionMessage = "This connection cannot import projects or thread history.";
156 -let renderer: ReactTestRenderer | undefined;
139 +const roots: Root[] = [];
140
141 function session(scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState {
142 return {
@@ -168,9 +151,17 @@ function session(scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState
151 };
152 }
153
154 +function sessionAtom(environmentId: EnvironmentId) {
155 + return state.sessions.get(environmentId) as Atom.Writable<SessionResult>;
156 +}
157 +
158 +function projectsAtom() {
159 + return state.projects as Atom.Writable<ReadonlyArray<Project>>;
160 +}
161 +
162 function setGrant(environmentId: EnvironmentId, allowed: boolean) {
172 - state.registry!.set(
173 - state.sessions.get(environmentId)!,
163 + appAtomRegistry.set(
164 + sessionAtom(environmentId),
165 AsyncResult.success(session(allowed ? [AuthOrchestrationOperateScope] : [])),
166 );
167 }
@@ -187,8 +178,8 @@ function candidate(path: string): AgentSessionProjectCandidate {
178 }
179
180 function recordProject({ environmentId, input }: CreateProjectInput) {
190 - state.registry!.set(state.projects!, [
191 - ...state.registry!.get(state.projects!),
181 + appAtomRegistry.set(projectsAtom(), [
182 + ...appAtomRegistry.get(projectsAtom()),
183 { id: input.projectId, environmentId, workspaceRoot: input.workspaceRoot },
184 ]);
185 return AsyncResult.success(undefined);
@@ -202,40 +193,47 @@ function deferred<T>() {
193 return { promise, resolve };
194 }
195
205 -function text(node: ReactTestInstance | string): string {
206 - return typeof node === "string" ? node : node.children.map(text).join("");
196 +function pageText() {
197 + return document.body.textContent ?? "";
198 }
199
200 function button(label: string) {
210 - const found = renderer!.root.findAllByType("button").find((node) => text(node) === label);
201 + const found = [...document.querySelectorAll("button")].find(
202 + (element) => element.textContent?.trim() === label,
203 + );
204 if (!found) throw new Error(`Missing button: ${label}`);
205 return found;
206 }
207
208 async function click(label: string) {
209 const target = button(label);
217 - expect(target.props.disabled).not.toBe(true);
218 - await act(async () => target.props.onClick());
210 + expect(target.disabled).toBe(false);
211 + await act(async () => target.click());
212 +}
213 +
214 +function projectCheckboxes() {
215 + return [...document.querySelectorAll<HTMLElement>('[role="checkbox"]')];
216 }
217
218 async function mountImport(remote = false) {
219 state.selectedEnvironment = remote ? "remote" : "primary";
223 - await act(async () => {
224 - renderer = create(
225 - <RegistryContext.Provider value={state.registry!}>
220 + const container = document.createElement("div");
221 + document.body.append(container);
222 + const root = createRoot(container);
223 + roots.push(root);
224 + await act(async () =>
225 + root.render(
226 + <RegistryContext.Provider value={appAtomRegistry}>
227 <WelcomeWizard localAvailable={!remote} onDone={state.onDone} />
228 </RegistryContext.Provider>,
228 - );
229 - });
229 + ),
230 + );
231 await click("Continue");
232 await click("Continue");
232 - expect(text(renderer!.root)).toContain("Import your projects");
233 + expect(pageText()).toContain("Import your projects");
234 }
235
236 beforeEach(() => {
236 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
237 - vi.stubGlobal("document", { activeElement: null, body: {}, getElementById: () => null });
238 - state.registry = AtomRegistry.make();
237 for (const id of [primaryId, remoteId]) {
238 state.sessions.set(
239 id,
@@ -263,20 +261,18 @@ beforeEach(() => {
261 });
262
263 afterEach(async () => {
266 - await act(async () => renderer?.unmount());
267 - renderer = undefined;
268 - state.registry?.dispose();
264 + for (const root of roots.splice(0)) await act(async () => root.unmount());
265 + document.body.replaceChildren();
266 state.sessions.clear();
270 - vi.unstubAllGlobals();
267 });
268
269 it("keeps scanning, choosing and skipping available to a paired read-only environment", async () => {
270 setGrant(remoteId, false);
271 await mountImport(true);
272 expect(state.scan).toHaveBeenCalledWith(expect.objectContaining({ environmentId: remoteId }));
277 - expect(text(renderer!.root)).toContain("/projects/first");
278 - expect(button("Import 2 projects").props.disabled).toBe(true);
279 - expect(text(renderer!.root)).toContain(permissionMessage);
273 + expect(pageText()).toContain("/projects/first");
274 + expect(button("Import 2 projects").disabled).toBe(true);
275 + expect(pageText()).toContain(permissionMessage);
276 await click("Do not import projects");
277 expect(state.createProject).not.toHaveBeenCalled();
278 expect(state.importThreads).not.toHaveBeenCalled();
@@ -285,9 +281,9 @@ it("keeps scanning, choosing and skipping available to a paired read-only enviro
281 });
282
283 it("waits for the selected grant and enables import when it arrives", async () => {
288 - state.registry!.set(state.sessions.get(primaryId)!, AsyncResult.initial());
284 + appAtomRegistry.set(sessionAtom(primaryId), AsyncResult.initial());
285 await mountImport();
290 - expect(button("Import 2 projects").props.disabled).toBe(true);
286 + expect(button("Import 2 projects").disabled).toBe(true);
287 await act(async () => setGrant(primaryId, true));
288 await click("Import 2 projects");
289 expect(state.createProject).toHaveBeenCalledTimes(2);
@@ -295,25 +291,25 @@ it("waits for the selected grant and enables import when it arrives", async () =
291 expect(state.onDone).toHaveBeenCalledWith(expect.objectContaining({ environmentId: primaryId }));
292 });
293
298 -it("preserves selections and denies a retained action using the paired environment's fresh grant", async () => {
294 +it("preserves selections and denies a click that lands as the paired environment's grant is revoked", async () => {
295 await mountImport(true);
300 - await act(async () => {
301 - renderer!.root.findAllByType("input")[1]!.props.onCheckedChange(false);
302 - });
303 - const retainedImport = button("Import 1 project").props.onClick;
296 + await act(async () => projectCheckboxes()[1]!.click());
297 + expect(projectCheckboxes()[1]!.getAttribute("aria-checked")).toBe("false");
298 + const importButton = button("Import 1 project");
299 + // The click reaches the still-enabled button before React re-renders the revocation.
300 await act(async () => {
301 setGrant(remoteId, false);
306 - retainedImport();
302 + importButton.click();
303 });
308 - expect(button("Import 1 project").props.disabled).toBe(true);
309 - expect(renderer!.root.findAllByType("input")[1]!.props.checked).toBe(false);
310 - expect(text(renderer!.root)).toContain(permissionMessage);
304 + expect(button("Import 1 project").disabled).toBe(true);
305 + expect(projectCheckboxes()[1]!.getAttribute("aria-checked")).toBe("false");
306 + expect(pageText()).toContain(permissionMessage);
307 expect(state.createProject).not.toHaveBeenCalled();
308 expect(state.importThreads).not.toHaveBeenCalled();
309 expect(state.onDone).not.toHaveBeenCalled();
310
311 await act(async () => setGrant(remoteId, true));
316 - expect(text(renderer!.root)).not.toContain(permissionMessage);
312 + expect(pageText()).not.toContain(permissionMessage);
313 await click("Import 1 project");
314 expect(state.createProject).toHaveBeenCalledExactlyOnceWith(
315 expect.objectContaining({ environmentId: remoteId }),
@@ -340,7 +336,7 @@ it("rechecks after project creation and can retry its history without recreating
336 expect(state.importThreads).not.toHaveBeenCalled();
337 expect(state.createProject).toHaveBeenCalledOnce();
338 expect(state.onDone).not.toHaveBeenCalled();
343 - expect(text(renderer!.root)).toContain(permissionMessage);
339 + expect(pageText()).toContain(permissionMessage);
340
341 await act(async () => setGrant(primaryId, true));
342 await click("Import 2 projects");
@@ -355,7 +351,7 @@ it.each([false, true])(
351 if (existing) {
352 const projectId = ProjectId.make("second-existing");
353 state.candidates[1] = { ...state.candidates[1]!, projectId };
358 - state.registry!.set(state.projects!, [
354 + appAtomRegistry.set(projectsAtom(), [
355 { id: projectId, environmentId: primaryId, workspaceRoot: "/projects/second" },
356 ]);
357 }
@@ -375,7 +371,7 @@ it.each([false, true])(
371 expect(state.createProject).toHaveBeenCalledOnce();
372 expect(state.importThreads).toHaveBeenCalledOnce();
373 expect(state.onDone).not.toHaveBeenCalled();
378 - expect(text(renderer!.root)).toContain(permissionMessage);
374 + expect(pageText()).toContain(permissionMessage);
375
376 await act(async () => setGrant(primaryId, true));
377 await click("Import 2 projects");
apps/web/src/components/onboarding/WelcomeWizard.terminal.browser.test.tsx renamed
+114 -123
@@ -20,10 +20,13 @@ import {
20 } from "@t3tools/contracts";
21 import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
22 import * as Cause from "effect/Cause";
23 -import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
24 -import { act, create, type ReactTestInstance, type ReactTestRenderer } from "react-test-renderer";
23 +import { AsyncResult, Atom } from "effect/reactivity";
24 +import { act } from "react";
25 +import { createRoot, type Root } from "react-dom/client";
26 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
27
28 +import "~/index.css";
29 +
30 type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
31 type CommandResult = AsyncResult.AsyncResult<void, Error>;
32 type Request<Input> = { environmentId: EnvironmentId; input: Input };
@@ -34,7 +37,6 @@ type SetupConfig = {
37 keybindings: ResolvedKeybindingsConfig;
38 };
39 const state = vi.hoisted(() => ({
37 - registry: null as AtomRegistry.AtomRegistry | null,
40 sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),
41 providers: new Map<EnvironmentId, Atom.Writable<ReadonlyArray<ServerProvider>>>(),
42 configs: new Map<EnvironmentId, Atom.Atom<SetupConfig>>(),
@@ -49,99 +51,87 @@ const state = vi.hoisted(() => ({
51 done: vi.fn(),
52 }));
53
52 -vi.mock("../../connection/runtime", () => ({ connectionAtomRuntime: undefined }));
53 -vi.mock("@t3tools/client-runtime/state/session", () => ({
54 - createEnvironmentSessionAtoms: () => ({
55 - sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,
56 - }),
57 -}));
58 -vi.mock("../../rpc/atomRegistry", () => ({
59 - get appAtomRegistry() {
60 - return state.registry;
61 - },
62 -}));
63 -vi.mock("../../state/environments", () => ({
64 - useEnvironments: () => ({ environments: [remoteEnvironment] }),
65 - usePrimaryEnvironment: () => primaryEnvironment,
66 -}));
67 -vi.mock("../../state/server", () => ({
68 - serverEnvironment: {
69 - providersValueAtom: (id: EnvironmentId) => state.providers.get(id)!,
70 - configValueAtom: (id: EnvironmentId) => state.configs.get(id)!,
71 - refreshProviders: "refresh",
72 - },
54 +// Session grants come from per-test atoms so a test can revoke or regrant mid-flow; the
55 +// real scope checks in ~/state/session read them through the app registry, which the
56 +// wizard is also rendered with.
57 +vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => {
58 + const actual = await original();
59 + return {
60 + ...actual,
61 + createEnvironmentSessionAtoms: ((runtime: never) => ({
62 + ...actual.createEnvironmentSessionAtoms(runtime),
63 + sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,
64 + })) as never,
65 + };
66 +});
67 +vi.mock(import("../../state/environments"), async (original) => ({
68 + ...(await original()),
69 + useEnvironments: (() => ({ environments: [remoteEnvironment] })) as never,
70 + usePrimaryEnvironment: (() => primaryEnvironment) as never,
71 }));
74 -vi.mock("../../state/terminal", () => ({
75 - terminalEnvironment: { open: "open", write: "write", close: "close" },
72 +vi.mock(import("../../state/server"), async (original) => {
73 + const actual = await original();
74 + return {
75 + ...actual,
76 + serverEnvironment: {
77 + ...actual.serverEnvironment,
78 + providersValueAtom: ((id: EnvironmentId) => state.providers.get(id)!) as never,
79 + configValueAtom: ((id: EnvironmentId) => state.configs.get(id)!) as never,
80 + refreshProviders: "refresh" as never,
81 + },
82 + };
83 +});
84 +vi.mock(import("../../state/terminal"), async (original) => ({
85 + ...(await original()),
86 + terminalEnvironment: { open: "open", write: "write", close: "close" } as never,
87 }));
77 -vi.mock("../../state/use-atom-command", () => ({
78 - useAtomCommand: (
88 +vi.mock(import("../../state/use-atom-command"), async (original) => ({
89 + ...(await original()),
90 + useAtomCommand: ((
91 command: "open" | "write" | "close" | "refresh" | "pair" | "createProject" | "importThreads",
80 - ) => state[command],
92 + ) => state[command]) as never,
93 }));
82 -vi.mock("../../connection/onboarding", () => ({ connectPairing: "pair" }));
83 -vi.mock("../../state/agentSessions", () => ({
84 - agentSessionImport: "importThreads",
85 - agentSessionScan: vi.fn(),
94 +vi.mock(import("../../connection/onboarding"), async (original) => ({
95 + ...(await original()),
96 + connectPairing: "pair" as never,
97 }));
87 -vi.mock("../../state/projects", () => ({ projectEnvironment: { create: "createProject" } }));
88 -vi.mock("../../state/entities", () => ({ readProjects: () => [], useProjects: () => [] }));
89 -vi.mock("../../onboarding/useProjectScans", () => ({ useProjectScans: () => [] }));
90 -vi.mock("../ui/dialog", () => ({
91 - Dialog: "div",
92 - DialogPopup: "div",
93 - DialogTitle: "div",
94 - DialogHeader: "div",
98 +vi.mock(import("../../state/agentSessions"), async (original) => ({
99 + ...(await original()),
100 + agentSessionImport: "importThreads" as never,
101 }));
96 -vi.mock("../ui/wizard", () => ({
97 - WizardPanel: "div",
98 - WizardPopup: "div",
99 - WizardHeader: "div",
100 - WizardSteps: ({ onStepChange }: { onStepChange: (step: number) => void }) => (
101 - <button onClick={() => onStepChange(0)}>Back</button>
102 - ),
102 +vi.mock(import("../../state/projects"), async (original) => ({
103 + ...(await original()),
104 + projectEnvironment: { create: "createProject" } as never,
105 }));
104 -vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));
105 -vi.mock("../../onboarding/firstRun", () => ({ useCompleteOnboarding: () => state.complete }));
106 -vi.mock("../../hooks/useTheme", () => ({ mountOnboardingTheme: () => undefined }));
107 -vi.mock("../../hooks/useLocalStorage", () => ({ useLocalStorage: () => [false, vi.fn()] }));
108 -vi.mock("../../hooks/useCopyToClipboard", () => ({
109 - useCopyToClipboard: () => ({ copyToClipboard: vi.fn(), isCopied: false }),
106 +vi.mock(import("../../state/entities"), async (original) => ({
107 + ...(await original()),
108 + readProjects: () => [],
109 + useProjects: () => [],
110 }));
111 -vi.mock("../../cloud/publicConfig", () => ({ hasCloudPublicConfig: () => false }));
112 -vi.mock("../clerk/useT3ConnectAuthPrompt", () => ({ useT3ConnectAuthPrompt: vi.fn() }));
113 -vi.mock("@clerk/react", () => ({ useAuth: vi.fn() }));
114 -vi.mock("../../env", () => ({ isElectron: false }));
115 -vi.mock("../../providerInstances", () => ({ resolveDefaultProviderModelSelection: vi.fn() }));
116 -vi.mock("../settings/ChatGptWelcomeCoordinator", () => ({ ChatGptWelcomeCoordinator: () => null }));
117 -vi.mock("../settings/CodexSetupSection", () => ({
118 - CodexSetupSection: () => null,
119 - AddManagedCodexAccountDialog: () => null,
111 +vi.mock(import("../../onboarding/useProjectScans"), async (original) => ({
112 + ...(await original()),
113 + useProjectScans: () => [],
114 }));
121 -vi.mock("../settings/providerDriverMeta", () => ({
122 - providerClients: { get: (driver: string) => ({ label: driver }) },
115 +vi.mock(import("../../onboarding/firstRun"), async (original) => ({
116 + ...(await original()),
117 + useCompleteOnboarding: () => state.complete,
118 }));
124 -vi.mock("../settings/providerStatus", () => ({
125 - getProviderSummary: () => ({ headline: "Setup required" }),
119 +vi.mock(import("../../cloud/publicConfig"), async (original) => ({
120 + ...(await original()),
121 + hasCloudPublicConfig: () => false,
122 }));
127 -vi.mock("../cloud/CloudEnvironmentConnectList", () => ({
128 - CloudEnvironmentConnectRows: () => null,
123 +vi.mock(import("../settings/ChatGptWelcomeCoordinator"), async (original) => ({
124 + ...(await original()),
125 + ChatGptWelcomeCoordinator: () => <></>,
126 }));
130 -vi.mock("../ThreadTerminalDrawer", () => ({
127 +// The real viewport mounts a Ghostty terminal against the PTY; these tests only need to
128 +// see whether the wizard shows it.
129 +vi.mock(import("../ThreadTerminalDrawer"), async (original) => ({
130 + ...(await original()),
131 TerminalViewport: () => <div data-terminal-viewport />,
132 }));
133 -vi.mock("../ui/button", () => ({ Button: "button" }));
134 -vi.mock("../ui/input", () => ({ Input: "input" }));
135 -vi.mock("../ui/checkbox", () => ({ Checkbox: "input" }));
136 -vi.mock("../ui/collapsible", () => ({
137 - Collapsible: "div",
138 - CollapsiblePanel: "div",
139 - CollapsibleTrigger: "button",
140 -}));
141 -vi.mock("../ui/toast", () => ({
142 - toastManager: { add: vi.fn(), update: vi.fn(), close: vi.fn() },
143 -}));
133
134 +import { appAtomRegistry } from "../../rpc/atomRegistry";
135 import { WelcomeWizard } from "./WelcomeWizard";
136
137 const primaryId = EnvironmentId.make("primary");
@@ -204,7 +194,7 @@ const session = (scopes: readonly AuthEnvironmentScope[]): AuthSessionState => (
194 },
195 });
196 function setAccess(environmentId: EnvironmentId, allowed: boolean) {
207 - state.registry!.set(
197 + appAtomRegistry.set(
198 state.sessions.get(environmentId)!,
199 AsyncResult.success(session(allowed ? [AuthTerminalOperateScope] : [])),
200 );
@@ -216,38 +206,42 @@ function deferred<T>() {
206 });
207 return { promise, resolve };
208 }
219 -function text(node: ReactTestInstance | string): string {
220 - return typeof node === "string" ? node : node.children.map(text).join("");
209 +const roots: Root[] = [];
210 +function pageText() {
211 + return document.body.textContent ?? "";
212 }
222 -let renderer: ReactTestRenderer | undefined;
213 function button(label: string) {
224 - return renderer!.root.findAllByType("button").find((node) => text(node) === label)!;
214 + const found = [...document.querySelectorAll("button")].find(
215 + (element) => element.textContent?.trim() === label || element.ariaLabel === label,
216 + );
217 + if (!found) throw new Error(`Missing button: ${label}`);
218 + return found;
219 }
220 async function click(label: string) {
221 const node = button(label);
228 - expect(node).toBeDefined();
229 - expect(node.props.disabled).not.toBe(true);
230 - await act(async () => node.props.onClick());
222 + expect(node.disabled).toBe(false);
223 + await act(async () => node.click());
224 }
225 function hasViewport() {
233 - return renderer!.root.findAllByProps({ "data-terminal-viewport": true }).length > 0;
226 + return document.querySelector("[data-terminal-viewport]") !== null;
227 }
228 async function enterRemoteAgents() {
236 - await act(async () => {
237 - renderer = create(
238 - <RegistryContext.Provider value={state.registry!}>
229 + const container = document.createElement("div");
230 + document.body.append(container);
231 + const root = createRoot(container);
232 + roots.push(root);
233 + await act(async () =>
234 + root.render(
235 + <RegistryContext.Provider value={appAtomRegistry}>
236 <WelcomeWizard localAvailable onDone={state.done} />
237 </RegistryContext.Provider>,
241 - );
242 - });
238 + ),
239 + );
240 await click("Continue");
244 - expect(text(renderer!.root)).toContain("Paired computer");
241 + expect(pageText()).toContain("Paired computer");
242 }
243
244 beforeEach(() => {
248 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
249 - vi.stubGlobal("document", { activeElement: null, body: {}, getElementById: () => null });
250 - state.registry = AtomRegistry.make();
245 for (const id of [primaryId, remoteId]) {
246 state.sessions.set(
247 id,
@@ -289,25 +283,23 @@ beforeEach(() => {
283 });
284
285 afterEach(async () => {
292 - await act(async () => renderer?.unmount());
293 - renderer = undefined;
294 - state.registry?.dispose();
286 + for (const root of roots.splice(0)) await act(async () => root.unmount());
287 + document.body.replaceChildren();
288 state.sessions.clear();
289 state.providers.clear();
290 state.configs.clear();
298 - vi.unstubAllGlobals();
291 });
292
293 describe("welcome agent terminal setup", () => {
294 it("disables both setup actions for the paired read-only connection and preserves local completion", async () => {
295 setAccess(remoteId, false);
296 await enterRemoteAgents();
305 - expect(button("Install").props.disabled).toBe(true);
306 - expect(button("Sign in").props.disabled).toBe(true);
307 - expect(text(renderer!.root)).toContain("This connection cannot control terminals.");
297 + expect(button("Install").disabled).toBe(true);
298 + expect(button("Sign in").disabled).toBe(true);
299 + expect(pageText()).toContain("This connection cannot control terminals.");
300 await act(async () => {
309 - button("Install").props.onClick();
310 - button("Sign in").props.onClick();
301 + button("Install").click();
302 + button("Sign in").click();
303 });
304 expect(state.open).not.toHaveBeenCalled();
305 expect(state.write).not.toHaveBeenCalled();
@@ -321,16 +313,17 @@ describe("welcome agent terminal setup", () => {
313 it("rejects a retained install action after revocation and allows a terminal-only regrant", async () => {
314 setAccess(primaryId, false);
315 await enterRemoteAgents();
324 - const install = button("Install").props.onClick;
316 + const install = button("Install");
317 + // The click reaches the still-enabled button before React re-renders the revocation.
318 await act(async () => {
319 setAccess(remoteId, false);
327 - install();
320 + install.click();
321 });
322 expect(state.open).not.toHaveBeenCalled();
330 - expect(button("Install").props.disabled).toBe(true);
323 + expect(button("Install").disabled).toBe(true);
324 await act(async () => setAccess(remoteId, true));
332 - expect(button("Install").props.disabled).toBe(false);
333 - await act(async () => install());
325 + expect(button("Install").disabled).toBe(false);
326 + await click("Install");
327 expect(state.open).toHaveBeenCalledExactlyOnceWith({
328 environmentId: remoteId,
329 input: {
@@ -381,7 +374,7 @@ describe("welcome agent terminal setup", () => {
374 data: "/opt/codex-work login",
375 },
376 });
384 - expect(text(renderer!.root)).toContain("Review the command, then press Enter to run it.");
377 + expect(pageText()).toContain("Review the command, then press Enter to run it.");
378 });
379
380 it("checks access when a queued retry starts and recovers after regrant", async () => {
@@ -398,7 +391,7 @@ describe("welcome agent terminal setup", () => {
391 closing.resolve(AsyncResult.success(undefined));
392 });
393 expect(state.open).toHaveBeenCalledOnce();
401 - expect(button("Retry").props.disabled).toBe(true);
394 + expect(button("Retry").disabled).toBe(true);
395 expect(state.write).not.toHaveBeenCalled();
396 await act(async () => setAccess(remoteId, true));
397 await click("Retry");
@@ -419,19 +412,17 @@ describe("welcome agent terminal setup", () => {
412 expect(state.write).not.toHaveBeenCalled();
413 expect(state.close).not.toHaveBeenCalled();
414 expect(hasViewport()).toBe(true);
422 - expect(text(renderer!.root)).toContain("This connection cannot control terminals.");
415 + expect(pageText()).toContain("This connection cannot control terminals.");
416 await act(async () => setAccess(remoteId, true));
417 expect(state.open).toHaveBeenCalledOnce();
418 expect(state.write).not.toHaveBeenCalled();
426 - expect(text(renderer!.root)).toContain(
427 - "Run curl -fsSL https://claude.ai/install.sh | bash in this",
428 - );
419 + expect(pageText()).toContain("Run curl -fsSL https://claude.ai/install.sh | bash in this");
420 await act(async () => setAccess(remoteId, false));
421 await click("Close");
422 expect(hasViewport()).toBe(false);
423 expect(state.close).not.toHaveBeenCalled();
424 await click("Continue");
434 - expect(text(renderer!.root)).toContain("Import your projects");
425 + expect(pageText()).toContain("Import your projects");
426 });
427
428 it("settles accepted pretyping locally after revocation without closing the PTY", async () => {
@@ -447,7 +438,7 @@ describe("welcome agent terminal setup", () => {
438 expect(state.write).toHaveBeenCalledOnce();
439 expect(hasViewport()).toBe(true);
440 await act(async () => setAccess(remoteId, true));
450 - expect(text(renderer!.root)).toContain("Review the command, then press Enter to run it.");
441 + expect(pageText()).toContain("Review the command, then press Enter to run it.");
442 expect(state.open).toHaveBeenCalledOnce();
443 expect(state.write).toHaveBeenCalledOnce();
444 await act(async () => setAccess(remoteId, false));
@@ -460,13 +451,13 @@ describe("welcome agent terminal setup", () => {
451 state.write.mockReturnValueOnce(writing.promise);
452 await enterRemoteAgents();
453 await click("Install");
463 - await click("Back");
454 + await click("Connect, step 1");
455 expect(state.close).not.toHaveBeenCalled();
456 await act(async () => {
457 setAccess(remoteId, false);
458 writing.resolve(AsyncResult.success(undefined));
459 });
460 expect(state.close).not.toHaveBeenCalled();
470 - expect(text(renderer!.root)).toContain("Connect your computers");
461 + expect(pageText()).toContain("Connect your computers");
462 });
463 });
apps/web/src/components/preview/PreviewView.browser.test.tsx new
+452
@@ -0,0 +1,452 @@
1 +import {
2 + BUILT_IN_BROWSER_PROFILES,
3 + DEFAULT_BROWSER_PROFILE_ID,
4 + DEFAULT_PREVIEW_APPEARANCE,
5 + DEFAULT_PREVIEW_ZOOM_FACTOR,
6 + EnvironmentId,
7 + FILL_PREVIEW_VIEWPORT,
8 + ThreadId,
9 +} from "@t3tools/contracts";
10 +import { act, Profiler, type ComponentProps, type ReactNode } from "react";
11 +import { createRoot, type Root } from "react-dom/client";
12 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13 +import { page, userEvent } from "vite-plus/test/browser";
14 +
15 +import "~/index.css";
16 +
17 +import type { PreviewableServer } from "./useDiscoveredLocalServers";
18 +
19 +const mocks = vi.hoisted(() => ({
20 + navigate: vi.fn(async (_tabId: string, _url: string): Promise<void> => undefined),
21 + rememberPreviewUrl: vi.fn(),
22 + readPreparedConnection: vi.fn(() => ({ httpBaseUrl: "http://172.25.85.75:3773" })),
23 + readEnvironmentScope: vi.fn((_environmentId?: unknown, _scope?: unknown) => true),
24 + setAnnotationSendEnabled: vi.fn(async (_tabId: string, _enabled: boolean): Promise<void> => {}),
25 + cancelPickElement: vi.fn(async (_tabId: string) => undefined),
26 + openPictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
27 + closePictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
28 + pickElement: vi.fn(),
29 + addPreviewAnnotation: vi.fn(),
30 + addImage: vi.fn(),
31 + toast: vi.fn(),
32 + pictureInPicture: false,
33 + showEmptyState: false,
34 + loading: false,
35 + serverEpoch: null as string | null,
36 + servers: [] as PreviewableServer[],
37 + recordingTabIds: new Set<string>(),
38 + recordingRuntimeTabId: null as string | null,
39 + recordVisitForThread: vi.fn(),
40 +}));
41 +
42 +const STUB_BROWSER_DEFAULTS = {
43 + viewport: FILL_PREVIEW_VIEWPORT,
44 + zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
45 + appearance: DEFAULT_PREVIEW_APPEARANCE,
46 + autoShowFloatingPreview: true,
47 + profiles: BUILT_IN_BROWSER_PROFILES,
48 + profileId: DEFAULT_BROWSER_PROFILE_ID,
49 +};
50 +
51 +// The desktop bridge only exists inside Electron; the view reads it once at import.
52 +vi.mock(import("./previewBridge"), async (original) => ({
53 + ...(await original()),
54 + previewBridge: {
55 + navigate: mocks.navigate,
56 + pickElement: mocks.pickElement,
57 + setAnnotationSendEnabled: mocks.setAnnotationSendEnabled,
58 + cancelPickElement: mocks.cancelPickElement,
59 + refresh: vi.fn(async () => undefined),
60 + goBack: vi.fn(async () => undefined),
61 + goForward: vi.fn(async () => undefined),
62 + hardReload: vi.fn(async () => undefined),
63 + openDevTools: vi.fn(async () => undefined),
64 + setColorScheme: vi.fn(async () => undefined),
65 + zoomIn: vi.fn(async () => undefined),
66 + zoomOut: vi.fn(async () => undefined),
67 + resetZoom: vi.fn(async () => undefined),
68 + clearCookies: vi.fn(async () => undefined),
69 + clearCache: vi.fn(async () => undefined),
70 + pictureInPicture: {
71 + open: mocks.openPictureInPicture,
72 + close: mocks.closePictureInPicture,
73 + },
74 + } as never,
75 +}));
76 +vi.mock(import("~/browserHistoryStore"), async (original) => ({
77 + ...(await original()),
78 + recordVisitForThread: mocks.recordVisitForThread,
79 +}));
80 +vi.mock(import("~/state/session"), async (original) => ({
81 + ...(await original()),
82 + readPreparedConnection: mocks.readPreparedConnection as never,
83 + readEnvironmentScope: mocks.readEnvironmentScope,
84 + useEnvironmentScope: mocks.readEnvironmentScope,
85 +}));
86 +vi.mock(import("~/browser/browserDefaults"), async (original) => ({
87 + ...(await original()),
88 + useBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
89 + getBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
90 +}));
91 +vi.mock(import("~/previewStateStore"), async (original) => ({
92 + ...(await original()),
93 + rememberPreviewUrl: mocks.rememberPreviewUrl,
94 + useThreadPreviewState: (() => ({
95 + activeTabId: "tab-1",
96 + serverEpoch: mocks.serverEpoch,
97 + desktopByTabId: {
98 + "tab-1": {
99 + hasWebContents: true,
100 + canGoBack: false,
101 + canGoForward: false,
102 + loading: mocks.loading,
103 + zoomFactor: 1,
104 + pictureInPicture: mocks.pictureInPicture,
105 + colorScheme: "system",
106 + audioMuted: false,
107 + audible: false,
108 + controller: "none",
109 + },
110 + },
111 + recentlySeenUrls: [],
112 + sessions: mocks.showEmptyState
113 + ? {}
114 + : {
115 + "tab-1": {
116 + threadId: "thread-1",
117 + tabId: "tab-1",
118 + navStatus: { _tag: "Success", url: "http://example.com/", title: "Example" },
119 + canGoBack: false,
120 + canGoForward: false,
121 + updatedAt: "2026-07-13T00:00:00.000Z",
122 + },
123 + },
124 + })) as never,
125 +}));
126 +vi.mock(import("~/state/environments"), async (original) => ({
127 + ...(await original()),
128 + useEnvironment: (() => ({ label: "WSL" })) as never,
129 + useEnvironmentHttpBaseUrl: () => "http://172.25.85.75:3773",
130 + usePrimaryEnvironmentId: () => null,
131 +}));
132 +vi.mock(import("~/browser/browserRecording"), async (original) => ({
133 + ...(await original()),
134 + findActiveBrowserRecordingRuntimeTabId: () => mocks.recordingRuntimeTabId,
135 + useActiveBrowserRecordingTabIds: () => mocks.recordingTabIds,
136 +}));
137 +vi.mock(import("~/components/ui/toast"), async (original) => {
138 + const actual = await original();
139 + return { ...actual, toastManager: { ...actual.toastManager, add: mocks.toast } };
140 +});
141 +vi.mock(import("./useDiscoveredLocalServers"), async (original) => ({
142 + ...(await original()),
143 + useDiscoveredLocalServers: () => mocks.servers,
144 +}));
145 +vi.mock(import("./usePreviewSession"), async (original) => ({
146 + ...(await original()),
147 + usePreviewSession: () => {},
148 +}));
149 +
150 +import { useComposerDraftStore } from "~/composerDraftStore";
151 +import { useBrowserPointerStore } from "~/browser/browserPointerStore";
152 +import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
153 +import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
154 +import { PreviewView } from "./PreviewView";
155 +
156 +const TEST_THREAD_REF = {
157 + environmentId: EnvironmentId.make("environment-1"),
158 + threadId: ThreadId.make("thread-1"),
159 +} as const;
160 +const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
161 +
162 +const roots: Root[] = [];
163 +let root: Root;
164 +
165 +async function render(node: ReactNode) {
166 + await act(async () => root.render(node));
167 +}
168 +
169 +function view(onSendAnnotation?: ComponentProps<typeof PreviewView>["onSendAnnotation"]) {
170 + return (
171 + <PreviewView
172 + threadRef={TEST_THREAD_REF}
173 + tabId="tab-1"
174 + visible
175 + {...(onSendAnnotation ? { onSendAnnotation } : {})}
176 + />
177 + );
178 +}
179 +
180 +function annotation(id: string, screenshot: unknown = null) {
181 + return {
182 + id,
183 + pageUrl: "https://example.com/dashboard",
184 + pageTitle: "Dashboard",
185 + comment: "Tighten this spacing",
186 + elements: [],
187 + regions: [],
188 + strokes: [],
189 + styleChanges: [],
190 + screenshot,
191 + createdAt: "2026-07-27T00:00:00.000Z",
192 + };
193 +}
194 +
195 +async function submitAddress(text: string) {
196 + const input = page.getByPlaceholder("Search or enter URL");
197 + await userEvent.click(input);
198 + await userEvent.fill(input, text);
199 + await userEvent.keyboard("{Enter}");
200 +}
201 +
202 +function hasCursor() {
203 + return document.querySelector("svg.lucide-mouse-pointer2") !== null;
204 +}
205 +
206 +describe("PreviewView", () => {
207 + beforeEach(() => {
208 + vi.clearAllMocks();
209 + mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
210 + mocks.setAnnotationSendEnabled.mockReset().mockResolvedValue(undefined);
211 + mocks.pickElement.mockReset();
212 + mocks.pictureInPicture = false;
213 + mocks.showEmptyState = false;
214 + mocks.loading = false;
215 + mocks.serverEpoch = null;
216 + mocks.servers = [];
217 + mocks.recordingTabIds = new Set();
218 + mocks.recordingRuntimeTabId = null;
219 + useComposerDraftStore.setState({
220 + addPreviewAnnotation: mocks.addPreviewAnnotation,
221 + addImage: mocks.addImage,
222 + });
223 + usePreviewMiniPlayerStore.setState({ byThreadKey: {} });
224 + useBrowserPointerStore.setState({ byTabId: {} });
225 + const container = document.createElement("div");
226 + document.body.append(container);
227 + root = createRoot(container);
228 + roots.push(root);
229 + });
230 +
231 + afterEach(async () => {
232 + for (const each of roots.splice(0)) await act(async () => each.unmount());
233 + document.body.replaceChildren();
234 + vi.useRealTimers();
235 + });
236 +
237 + it("shows the cursor in a replacement browser while the old instance still records", async () => {
238 + mocks.recordingTabIds.add(TEST_RUNTIME_TAB_ID);
239 + mocks.recordingRuntimeTabId = TEST_RUNTIME_TAB_ID;
240 + const replacementTabId = previewRuntimeTabId(TEST_THREAD_REF, "replacement-server", "tab-1");
241 + useBrowserPointerStore.setState({
242 + byTabId: Object.fromEntries(
243 + [TEST_RUNTIME_TAB_ID, replacementTabId].map((tabId) => [
244 + tabId,
245 + { tabId, phase: "move", x: 10, y: 10, sequence: 1, createdAt: "2026-07-27T00:00:00Z" },
246 + ]),
247 + ),
248 + });
249 + await render(view());
250 + expect(hasCursor()).toBe(false);
251 + mocks.serverEpoch = "replacement-server";
252 + await render(view());
253 + expect(hasCursor()).toBe(true);
254 + expect(mocks.recordingTabIds.has(TEST_RUNTIME_TAB_ID)).toBe(true);
255 + });
256 +
257 + it("does not rerender while loading time passes", async () => {
258 + vi.useFakeTimers();
259 + mocks.loading = true;
260 + const onRender = vi.fn();
261 + await render(
262 + <Profiler id="preview" onRender={onRender}>
263 + {view()}
264 + </Profiler>,
265 + );
266 + const initialRenderCount = onRender.mock.calls.length;
267 + await act(() => vi.advanceTimersByTimeAsync(1_000));
268 + expect(onRender).toHaveBeenCalledTimes(initialRenderCount);
269 + });
270 +
271 + it.each([
272 + [
273 + "https://localhost:8000/dashboard?mode=test#top",
274 + "https://localhost:8000/dashboard?mode=test#top",
275 + ],
276 + ["localhost:5173/app", "http://localhost:5173/app"],
277 + ])(
278 + "preserves a direct localhost URL %s in a WSL environment and records it",
279 + async (submitted, expected) => {
280 + await render(view());
281 + await submitAddress(submitted);
282 + await vi.waitFor(() =>
283 + expect(mocks.navigate).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID, expected),
284 + );
285 + expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(TEST_THREAD_REF, expected);
286 + expect(mocks.recordVisitForThread).toHaveBeenCalledWith(TEST_THREAD_REF, expected);
287 + },
288 + );
289 +
290 + it("maps an empty-state localhost server onto the WSL host", async () => {
291 + mocks.showEmptyState = true;
292 + mocks.servers = [
293 + {
294 + host: "localhost",
295 + port: 5173,
296 + url: "http://localhost:5173/app?mode=test#top",
297 + requestedUrl: "http://localhost:5173/app?mode=test#top",
298 + processName: "vite",
299 + pid: 1,
300 + terminal: null,
301 + source: "scanner",
302 + } as unknown as PreviewableServer,
303 + ];
304 + await render(view());
305 + await userEvent.click(page.getByRole("button", { name: /vite/ }));
306 +
307 + await vi.waitFor(() =>
308 + expect(mocks.navigate).toHaveBeenCalledWith(
309 + TEST_RUNTIME_TAB_ID,
310 + "http://172.25.85.75:5173/app?mode=test#top",
311 + ),
312 + );
313 + expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
314 + TEST_THREAD_REF,
315 + "http://172.25.85.75:5173/app?mode=test#top",
316 + );
317 + // History keys off the requested loopback URL, which stays stable across hosts.
318 + await vi.waitFor(() =>
319 + expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
320 + TEST_THREAD_REF,
321 + "http://localhost:5173/app?mode=test#top",
322 + ),
323 + );
324 + });
325 +
326 + it("opens and closes a thread-scoped floating preview for the active tab", async () => {
327 + await render(view());
328 + await userEvent.click(page.getByRole("button", { name: "Float preview over chat" }));
329 + expect(usePreviewMiniPlayerStore.getState().byThreadKey).toMatchObject({
330 + "environment-1:thread-1": { source: { kind: "browser", tabId: "tab-1" } },
331 + });
332 + const closeButton = page.getByRole("button", { name: "Close floating preview" });
333 + await expect.element(closeButton).toHaveAttribute("aria-pressed", "true");
334 + await userEvent.click(closeButton);
335 + expect(usePreviewMiniPlayerStore.getState().byThreadKey).toEqual({});
336 + });
337 +
338 + it("keeps the native preview window as a secondary menu action", async () => {
339 + await render(view());
340 + await userEvent.click(page.getByRole("button", { name: "Preview menu" }));
341 + await userEvent.click(page.getByRole("menuitem", { name: "Open separate preview window" }));
342 + await vi.waitFor(() =>
343 + expect(mocks.openPictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
344 + );
345 + await vi.waitFor(() => expect(document.querySelector('[role="menu"]')).toBeNull());
346 +
347 + mocks.pictureInPicture = true;
348 + await render(view());
349 + await userEvent.click(page.getByRole("button", { name: "Preview menu" }));
350 + await userEvent.click(page.getByRole("menuitem", { name: "Close separate preview window" }));
351 + await vi.waitFor(() =>
352 + expect(mocks.closePictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
353 + );
354 + });
355 +
356 + it("forwards Cmd/Ctrl+Enter annotations to the composer send path", async () => {
357 + const picked = annotation("annotation-1");
358 + const onSendAnnotation = vi.fn();
359 + mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
360 + await render(view(onSendAnnotation));
361 + await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
362 +
363 + await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
364 + expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, picked);
365 + });
366 +
367 + it("retains the annotation locally when its own environment loses access during capture", async () => {
368 + const picked = annotation("annotation-revoked");
369 + const onSendAnnotation = vi.fn();
370 + let submitPick: (() => void) | undefined;
371 + mocks.pickElement.mockImplementationOnce(
372 + () =>
373 + new Promise((resolve) => {
374 + submitPick = () => resolve({ annotation: picked, submission: "send" });
375 + }),
376 + );
377 + await render(view(onSendAnnotation));
378 + await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
379 + await vi.waitFor(() => expect(submitPick).toBeDefined());
380 + expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
381 +
382 + mocks.readEnvironmentScope.mockImplementation(
383 + (environmentId?: unknown) => environmentId !== TEST_THREAD_REF.environmentId,
384 + );
385 + await render(view(onSendAnnotation));
386 + expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, false);
387 + await act(async () => submitPick!());
388 + await vi.waitFor(() =>
389 + expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, picked),
390 + );
391 + expect(onSendAnnotation).not.toHaveBeenCalled();
392 +
393 + mocks.readEnvironmentScope.mockReturnValue(true);
394 + mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
395 + await render(view(onSendAnnotation));
396 + await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
397 + await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
398 + expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
399 + });
400 +
401 + it("does not reopen a cancelled picker after the permission update finishes", async () => {
402 + let finishUpdate: (() => void) | undefined;
403 + mocks.setAnnotationSendEnabled.mockImplementationOnce(
404 + () =>
405 + new Promise<void>((resolve) => {
406 + finishUpdate = resolve;
407 + }),
408 + );
409 + await render(view());
410 + await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
411 + await vi.waitFor(() => expect(finishUpdate).toBeDefined());
412 + expect(mocks.pickElement).not.toHaveBeenCalled();
413 + await userEvent.click(page.getByRole("button", { name: "Cancel annotation" }));
414 + expect(mocks.cancelPickElement).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID);
415 + await act(async () => finishUpdate!());
416 + expect(mocks.pickElement).not.toHaveBeenCalled();
417 + expect(mocks.addPreviewAnnotation).not.toHaveBeenCalled();
418 + });
419 +
420 + it("warns when main dropped the crop before handing over the pick", async () => {
421 + const picked = annotation("annotation-3");
422 + const onSendAnnotation = vi.fn();
423 + mocks.pickElement.mockResolvedValue({
424 + annotation: picked,
425 + submission: "send",
426 + screenshotFailed: true,
427 + });
428 + await render(view(onSendAnnotation));
429 + await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
430 +
431 + await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
432 + expect(mocks.toast).toHaveBeenCalledOnce();
433 + });
434 +
435 + it("still sends annotation text when the picked element's crop is malformed", async () => {
436 + const picked = annotation("annotation-2", {
437 + dataUrl: "data:image/png;base64,%%%",
438 + width: 10,
439 + height: 10,
440 + cropRect: { x: 0, y: 0, width: 10, height: 10 },
441 + });
442 + const onSendAnnotation = vi.fn();
443 + mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
444 + await render(view(onSendAnnotation));
445 + await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
446 +
447 + const sent = { ...picked, screenshot: null };
448 + await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(sent, null));
449 + expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, sent);
450 + expect(mocks.addImage).not.toHaveBeenCalled();
451 + });
452 +});
apps/web/src/components/preview/PreviewView.test.tsx deleted
-751
@@ -1,751 +0,0 @@
1 -import {
2 - BUILT_IN_BROWSER_PROFILES,
3 - DEFAULT_BROWSER_PROFILE_ID,
4 - DEFAULT_PREVIEW_APPEARANCE,
5 - DEFAULT_PREVIEW_ZOOM_FACTOR,
6 - EnvironmentId,
7 - FILL_PREVIEW_VIEWPORT,
8 - ThreadId,
9 -} from "@t3tools/contracts";
10 -import { act, createElement, Profiler } from "react";
11 -import { renderToStaticMarkup } from "react-dom/server";
12 -import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
13 -
14 -const mocks = vi.hoisted(() => ({
15 - navigate: vi.fn(async (_tabId: string, _url: string): Promise<void> => undefined),
16 - rememberPreviewUrl: vi.fn(),
17 - readPreparedConnection: vi.fn(() => ({ httpBaseUrl: "http://172.25.85.75:3773" })),
18 - readEnvironmentScope: vi.fn(() => true),
19 - setAnnotationSendEnabled: vi.fn(async (): Promise<void> => undefined),
20 - cancelPickElement: vi.fn(async () => undefined),
21 - submittedUrl: null as ((url: string) => void) | null,
22 - emptyStateUrl: null as ((url: string) => void) | null,
23 - togglePictureInPicture: null as (() => void) | null,
24 - toggleNativePictureInPicture: null as (() => void) | null,
25 - pictureInPicturePressed: false,
26 - miniPlayerTabId: null as string | null,
27 - openMiniPlayer: vi.fn(),
28 - closeMiniPlayer: vi.fn(),
29 - closeRightPanel: vi.fn(),
30 - openPictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
31 - closePictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
32 - pickElement: vi.fn(),
33 - addPreviewAnnotation: vi.fn(),
34 - addImage: vi.fn(),
35 - toggleAnnotation: null as (() => void) | null,
36 - pictureInPicture: false,
37 - showEmptyState: false,
38 - loading: false,
39 - serverEpoch: null as string | null,
40 - recordingTabIds: new Set<string>(),
41 - recordingRuntimeTabId: null as string | null,
42 - recordVisitForThread: vi.fn(),
43 -}));
44 -
45 -const EMPTY_HISTORY: never[] = [];
46 -
47 -const STUB_BROWSER_DEFAULTS = {
48 - viewport: FILL_PREVIEW_VIEWPORT,
49 - zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
50 - appearance: DEFAULT_PREVIEW_APPEARANCE,
51 - autoShowFloatingPreview: true,
52 - profiles: BUILT_IN_BROWSER_PROFILES,
53 - profileId: DEFAULT_BROWSER_PROFILE_ID,
54 -};
55 -
56 -vi.mock("~/browserHistoryStore", () => ({
57 - recordVisitForThread: mocks.recordVisitForThread,
58 - setTitleForThreadUrl: vi.fn(),
59 - removeUrlForThread: vi.fn(),
60 - BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT: 50,
61 - useThreadRecentHistory: () => EMPTY_HISTORY,
62 -}));
63 -
64 -vi.mock("~/state/session", async (importOriginal) => ({
65 - ...(await importOriginal<typeof import("~/state/session")>()),
66 - readPreparedConnection: mocks.readPreparedConnection,
67 - readEnvironmentScope: mocks.readEnvironmentScope,
68 - useEnvironmentScope: mocks.readEnvironmentScope,
69 -}));
70 -
71 -vi.mock("~/assets/assetUrls", async () => {
72 - const { resolveAssetUrl } = await import("@t3tools/client-runtime/state/assets");
73 - return { resolveAssetUrl };
74 -});
75 -
76 -vi.mock("~/browser/browserDefaults", () => ({
77 - useBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
78 - getBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
79 - browserDefaultOpenViewport: () => FILL_PREVIEW_VIEWPORT,
80 - browserDefaultOpenProfileId: () => DEFAULT_BROWSER_PROFILE_ID,
81 - browserDefaultTabState: () => ({
82 - zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
83 - colorScheme: DEFAULT_PREVIEW_APPEARANCE,
84 - }),
85 - browserResponsiveViewportForToggle: () => ({
86 - _tag: "freeform" as const,
87 - width: 1024,
88 - height: 768,
89 - }),
90 -}));
91 -
92 -vi.mock("~/composerDraftStore", () => ({
93 - useComposerDraftStore: (
94 - select: (store: { addPreviewAnnotation: () => void; addImage: () => void }) => unknown,
95 - ) =>
96 - select({
97 - addPreviewAnnotation: mocks.addPreviewAnnotation,
98 - addImage: mocks.addImage,
99 - }),
100 -}));
101 -
102 -vi.mock("~/localApi", () => ({
103 - ensureLocalApi: vi.fn(),
104 -}));
105 -
106 -vi.mock("~/previewStateStore", () => ({
107 - rememberPreviewUrl: mocks.rememberPreviewUrl,
108 - updatePreviewServerSnapshot: vi.fn(),
109 - useThreadPreviewState: () => ({
110 - activeTabId: "tab-1",
111 - serverEpoch: mocks.serverEpoch,
112 - desktopByTabId: {
113 - "tab-1": {
114 - hasWebContents: true,
115 - canGoBack: false,
116 - canGoForward: false,
117 - loading: mocks.loading,
118 - zoomFactor: 1,
119 - pictureInPicture: mocks.pictureInPicture,
120 - colorScheme: "system",
121 - audioMuted: false,
122 - audible: false,
123 - controller: "none",
124 - },
125 - },
126 - recentlySeenUrls: [],
127 - sessions: mocks.showEmptyState
128 - ? {}
129 - : {
130 - "tab-1": {
131 - threadId: "thread-1",
132 - tabId: "tab-1",
133 - navStatus: {
134 - _tag: "Success",
135 - url: "http://example.com/",
136 - title: "Example",
137 - },
138 - canGoBack: false,
139 - canGoForward: false,
140 - updatedAt: "2026-07-13T00:00:00.000Z",
141 - },
142 - },
143 - }),
144 -}));
145 -
146 -vi.mock("~/state/environments", () => ({
147 - useEnvironment: () => ({ label: "WSL" }),
148 - useEnvironmentHttpBaseUrl: () => "http://172.25.85.75:3773",
149 - usePrimaryEnvironmentId: () => null,
150 -}));
151 -
152 -vi.mock("~/state/preview", () => ({
153 - previewEnvironment: { open: {}, close: {}, resize: {} },
154 -}));
155 -
156 -vi.mock("~/state/use-atom-command", () => ({
157 - useAtomCommand: () => vi.fn(),
158 -}));
159 -
160 -vi.mock("~/browser/browserRecording", () => ({
161 - findActiveBrowserRecordingRuntimeTabId: () => mocks.recordingRuntimeTabId,
162 - isBrowserRecordingStartCancelledError: vi.fn(() => false),
163 - startBrowserRecording: vi.fn(),
164 - stopBrowserRecording: vi.fn(),
165 - useActiveBrowserRecordingTabIds: () => mocks.recordingTabIds,
166 -}));
167 -
168 -vi.mock("~/browser/browserSurfaceStore", () => ({
169 - useBrowserSurfaceStore: (
170 - select: (state: { byTabId: Record<string, { rect?: unknown }> }) => unknown,
171 - ) => select({ byTabId: {} }),
172 -}));
173 -
174 -vi.mock("~/previewMiniPlayerStore", () => {
175 - const usePreviewMiniPlayerStore = Object.assign(
176 - (select: (state: unknown) => unknown) =>
177 - select({
178 - byThreadKey: mocks.miniPlayerTabId
179 - ? {
180 - "environment-1:thread-1": {
181 - source: { kind: "browser", tabId: mocks.miniPlayerTabId },
182 - position: null,
183 - },
184 - }
185 - : {},
186 - }),
187 - {
188 - getState: () => ({
189 - open: mocks.openMiniPlayer,
190 - close: mocks.closeMiniPlayer,
191 - }),
192 - },
193 - );
194 - return {
195 - browserMiniPlayerSource: (tabId: string) => ({ kind: "browser", tabId }),
196 - selectThreadPreviewMiniPlayerTabId: (
197 - byThreadKey: Record<string, { source: { tabId: string }; position: null }>,
198 - ) => byThreadKey["environment-1:thread-1"]?.source.tabId ?? null,
199 - usePreviewMiniPlayerStore,
200 - };
201 -});
202 -
203 -vi.mock("~/rightPanelStore", () => ({
204 - useRightPanelStore: {
205 - getState: () => ({ close: mocks.closeRightPanel }),
206 - },
207 -}));
208 -
209 -vi.mock("~/components/ui/toast", () => ({
210 - stackedThreadToast: vi.fn(),
211 - toastManager: { add: vi.fn() },
212 -}));
213 -
214 -vi.mock("./previewBridge", () => ({
215 - previewBridge: {
216 - navigate: mocks.navigate,
217 - pickElement: mocks.pickElement,
218 - setAnnotationSendEnabled: mocks.setAnnotationSendEnabled,
219 - cancelPickElement: mocks.cancelPickElement,
220 - pictureInPicture: {
221 - open: mocks.openPictureInPicture,
222 - close: mocks.closePictureInPicture,
223 - },
224 - },
225 -}));
226 -
227 -vi.mock("./PreviewChromeRow", () => ({
228 - PreviewChromeRow: (props: {
229 - onSubmit: (url: string) => void;
230 - onPickElement?: () => void;
231 - onPictureInPicture?: () => void;
232 - pictureInPicture?: boolean;
233 - trailingActions?: {
234 - props: { actions?: { toggleNativePictureInPicture?: () => void } };
235 - };
236 - }) => {
237 - mocks.submittedUrl = props.onSubmit;
238 - mocks.toggleAnnotation = props.onPickElement ?? null;
239 - mocks.togglePictureInPicture = props.onPictureInPicture ?? null;
240 - mocks.toggleNativePictureInPicture =
241 - props.trailingActions?.props.actions?.toggleNativePictureInPicture ?? null;
242 - mocks.pictureInPicturePressed = props.pictureInPicture ?? false;
243 - return null;
244 - },
245 -}));
246 -
247 -vi.mock("./PreviewEmptyState", () => ({
248 - PreviewEmptyState: (props: { onOpenUrl: (url: string) => void }) => {
249 - mocks.emptyStateUrl = props.onOpenUrl;
250 - return null;
251 - },
252 -}));
253 -vi.mock("./PreviewMoreMenu", () => ({
254 - PreviewMoreMenu: (props: { actions: { toggleNativePictureInPicture?: () => void } }) => {
255 - mocks.toggleNativePictureInPicture = props.actions.toggleNativePictureInPicture ?? null;
256 - return null;
257 - },
258 -}));
259 -vi.mock("./PreviewUnreachable", () => ({ PreviewUnreachable: () => null }));
260 -vi.mock("./ZoomIndicator", () => ({ ZoomIndicator: () => null }));
261 -vi.mock("./AgentBrowserCursor", () => ({
262 - AgentBrowserCursor: () => createElement("agent-cursor"),
263 -}));
264 -vi.mock("~/browser/BrowserSurfaceSlot", () => ({ BrowserSurfaceSlot: () => null }));
265 -vi.mock("./usePreviewSession", () => ({ usePreviewSession: vi.fn() }));
266 -
267 -import { PreviewView } from "./PreviewView";
268 -import { toastManager } from "~/components/ui/toast";
269 -import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
270 -
271 -const TEST_THREAD_REF = {
272 - environmentId: EnvironmentId.make("environment-1"),
273 - threadId: ThreadId.make("thread-1"),
274 -} as const;
275 -const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
276 -
277 -// ReactDOM needs a host, but this unit suite intentionally has no DOM dependency.
278 -class TestNode {
279 - parentNode: TestNode | null = null;
280 - childNodes: TestNode[] = [];
281 - readonly nodeName: string;
282 - readonly tagName: string;
283 - readonly namespaceURI = "http://www.w3.org/1999/xhtml";
284 - readonly style = {};
285 -
286 - constructor(
287 - name: string,
288 - readonly ownerDocument: TestNode | null = null,
289 - readonly nodeType = 1,
290 - ) {
291 - this.nodeName = name.toUpperCase();
292 - this.tagName = this.nodeName;
293 - }
294 -
295 - set textContent(_value: string) {
296 - this.childNodes = [];
297 - }
298 -
299 - appendChild(child: TestNode) {
300 - child.parentNode = this;
301 - this.childNodes.push(child);
302 - return child;
303 - }
304 -
305 - removeChild(child: TestNode) {
306 - this.childNodes.splice(this.childNodes.indexOf(child), 1);
307 - child.parentNode = null;
308 - return child;
309 - }
310 -
311 - createElement(name: string) {
312 - return new TestNode(name, this);
313 - }
314 -
315 - addEventListener() {}
316 - removeEventListener() {}
317 - setAttribute() {}
318 -}
319 -
320 -function installTestDom() {
321 - const document = new TestNode("#document", null, 9);
322 - const window = {
323 - document,
324 - HTMLIFrameElement: TestNode,
325 - setInterval: globalThis.setInterval,
326 - clearInterval: globalThis.clearInterval,
327 - setTimeout: globalThis.setTimeout,
328 - clearTimeout: globalThis.clearTimeout,
329 - addEventListener() {},
330 - removeEventListener() {},
331 - };
332 - vi.stubGlobal("document", document);
333 - vi.stubGlobal("window", window);
334 - vi.stubGlobal("HTMLIFrameElement", window.HTMLIFrameElement);
335 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
336 - return document;
337 -}
338 -
339 -describe("PreviewView navigation", () => {
340 - beforeEach(() => {
341 - mocks.navigate.mockClear();
342 - mocks.rememberPreviewUrl.mockClear();
343 - mocks.readPreparedConnection.mockClear();
344 - mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
345 - mocks.setAnnotationSendEnabled.mockClear();
346 - mocks.cancelPickElement.mockClear();
347 - mocks.submittedUrl = null;
348 - mocks.emptyStateUrl = null;
349 - mocks.togglePictureInPicture = null;
350 - mocks.toggleNativePictureInPicture = null;
351 - mocks.pictureInPicturePressed = false;
352 - mocks.miniPlayerTabId = null;
353 - mocks.openMiniPlayer.mockClear();
354 - mocks.closeMiniPlayer.mockClear();
355 - mocks.closeRightPanel.mockClear();
356 - mocks.openPictureInPicture.mockClear();
357 - mocks.closePictureInPicture.mockClear();
358 - mocks.pickElement.mockReset();
359 - mocks.addPreviewAnnotation.mockClear();
360 - vi.mocked(toastManager.add).mockClear();
361 - mocks.addImage.mockClear();
362 - mocks.toggleAnnotation = null;
363 - mocks.pictureInPicture = false;
364 - mocks.showEmptyState = false;
365 - mocks.loading = false;
366 - mocks.serverEpoch = null;
367 - mocks.recordingTabIds = new Set();
368 - mocks.recordingRuntimeTabId = null;
369 - mocks.recordVisitForThread.mockClear();
370 - });
371 -
372 - it("shows the cursor in a replacement browser while the old instance still records", async () => {
373 - const document = installTestDom();
374 - const { createRoot } = await import("react-dom/client");
375 - const container = document.createElement("div");
376 - const root = createRoot(container as unknown as Element);
377 - const hasCursor = (node: TestNode): boolean =>
378 - node.nodeName === "AGENT-CURSOR" || node.childNodes.some(hasCursor);
379 - mocks.recordingTabIds.add(TEST_RUNTIME_TAB_ID);
380 - mocks.recordingRuntimeTabId = TEST_RUNTIME_TAB_ID;
381 - try {
382 - await act(() => {
383 - root.render(<PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />);
384 - });
385 - expect(hasCursor(container)).toBe(false);
386 - mocks.serverEpoch = "replacement-server";
387 - await act(() => {
388 - root.render(<PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />);
389 - });
390 - expect(hasCursor(container)).toBe(true);
391 - expect(mocks.recordingTabIds.has(TEST_RUNTIME_TAB_ID)).toBe(true);
392 - } finally {
393 - await act(() => root.unmount());
394 - vi.unstubAllGlobals();
395 - }
396 - });
397 -
398 - it("does not rerender while loading time passes", async () => {
399 - vi.useFakeTimers();
400 - mocks.loading = true;
401 - const document = installTestDom();
402 - const { createRoot } = await import("react-dom/client");
403 - const root = createRoot(document.createElement("div") as unknown as Element);
404 - const onRender = vi.fn();
405 -
406 - try {
407 - await act(() => {
408 - root.render(
409 - <Profiler id="preview" onRender={onRender}>
410 - <PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />
411 - </Profiler>,
412 - );
413 - });
414 - const initialRenderCount = onRender.mock.calls.length;
415 -
416 - await act(() => vi.advanceTimersByTimeAsync(1_000));
417 -
418 - expect(onRender).toHaveBeenCalledTimes(initialRenderCount);
419 - } finally {
420 - await act(() => root.unmount());
421 - vi.useRealTimers();
422 - vi.unstubAllGlobals();
423 - }
424 - });
425 -
426 - it.each([
427 - [
428 - "https://localhost:8000/dashboard?mode=test#top",
429 - "https://localhost:8000/dashboard?mode=test#top",
430 - ],
431 - ["localhost:5173/app", "http://localhost:5173/app"],
432 - ])("preserves a direct localhost URL in a WSL environment", async (submitted, expected) => {
433 - renderToStaticMarkup(
434 - <PreviewView
435 - threadRef={{
436 - environmentId: EnvironmentId.make("environment-1"),
437 - threadId: ThreadId.make("thread-1"),
438 - }}
439 - tabId="tab-1"
440 - visible
441 - />,
442 - );
443 -
444 - expect(mocks.submittedUrl).not.toBeNull();
445 - mocks.submittedUrl?.(submitted);
446 -
447 - await vi.waitFor(() =>
448 - expect(mocks.navigate).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID, expected),
449 - );
450 - expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
451 - {
452 - environmentId: "environment-1",
453 - threadId: "thread-1",
454 - },
455 - expected,
456 - );
457 - });
458 -
459 - it("records a history visit with the normalized requested url on submit", async () => {
460 - renderToStaticMarkup(
461 - <PreviewView
462 - threadRef={{
463 - environmentId: EnvironmentId.make("environment-1"),
464 - threadId: ThreadId.make("thread-1"),
465 - }}
466 - tabId="tab-1"
467 - visible
468 - />,
469 - );
470 -
471 - mocks.submittedUrl?.("localhost:3000/admin");
472 - await vi.waitFor(() => {
473 - expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
474 - expect.objectContaining({ threadId: expect.anything() }),
475 - "http://localhost:3000/admin",
476 - );
477 - });
478 - });
479 -
480 - it("maps an empty-state localhost server onto the WSL host", async () => {
481 - mocks.showEmptyState = true;
482 - renderToStaticMarkup(
483 - <PreviewView
484 - threadRef={{
485 - environmentId: EnvironmentId.make("environment-1"),
486 - threadId: ThreadId.make("thread-1"),
487 - }}
488 - tabId="tab-1"
489 - visible
490 - />,
491 - );
492 -
493 - expect(mocks.emptyStateUrl).not.toBeNull();
494 - mocks.emptyStateUrl?.("http://localhost:5173/app?mode=test#top");
495 -
496 - await vi.waitFor(() =>
497 - expect(mocks.navigate).toHaveBeenCalledWith(
498 - TEST_RUNTIME_TAB_ID,
499 - "http://172.25.85.75:5173/app?mode=test#top",
500 - ),
501 - );
502 - expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
503 - {
504 - environmentId: "environment-1",
505 - threadId: "thread-1",
506 - },
507 - "http://172.25.85.75:5173/app?mode=test#top",
508 - );
509 - await vi.waitFor(() =>
510 - expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
511 - expect.objectContaining({ threadId: expect.anything() }),
512 - "http://localhost:5173/app?mode=test#top",
513 - ),
514 - );
515 - });
516 -
517 - it("opens and closes a thread-scoped floating preview for the active tab", async () => {
518 - const props = {
519 - threadRef: {
520 - environmentId: EnvironmentId.make("environment-1"),
521 - threadId: ThreadId.make("thread-1"),
522 - },
523 - tabId: "tab-1",
524 - visible: true,
525 - } as const;
526 -
527 - renderToStaticMarkup(<PreviewView {...props} />);
528 - expect(mocks.pictureInPicturePressed).toBe(false);
529 - mocks.togglePictureInPicture?.();
530 - expect(mocks.openMiniPlayer).toHaveBeenCalledWith(props.threadRef, {
531 - kind: "browser",
532 - tabId: "tab-1",
533 - });
534 - expect(mocks.closeRightPanel).toHaveBeenCalledWith(props.threadRef);
535 -
536 - mocks.miniPlayerTabId = "tab-1";
537 - renderToStaticMarkup(<PreviewView {...props} />);
538 - expect(mocks.pictureInPicturePressed).toBe(true);
539 - mocks.togglePictureInPicture?.();
540 - expect(mocks.closeMiniPlayer).toHaveBeenCalledWith(props.threadRef);
541 - });
542 -
543 - it("keeps the native preview window as a secondary action", async () => {
544 - const props = {
545 - threadRef: {
546 - environmentId: EnvironmentId.make("environment-1"),
547 - threadId: ThreadId.make("thread-1"),
548 - },
549 - tabId: "tab-1",
550 - visible: true,
551 - } as const;
552 -
553 - renderToStaticMarkup(<PreviewView {...props} />);
554 - mocks.toggleNativePictureInPicture?.();
555 - await vi.waitFor(() =>
556 - expect(mocks.openPictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
557 - );
558 -
559 - mocks.pictureInPicture = true;
560 - renderToStaticMarkup(<PreviewView {...props} />);
561 - mocks.toggleNativePictureInPicture?.();
562 - await vi.waitFor(() =>
563 - expect(mocks.closePictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
564 - );
565 - });
566 -
567 - it("forwards Cmd/Ctrl+Enter annotations to the composer send path", async () => {
568 - const annotation = {
569 - id: "annotation-1",
570 - pageUrl: "https://example.com/dashboard",
571 - pageTitle: "Dashboard",
572 - comment: "Tighten this spacing",
573 - elements: [],
574 - regions: [],
575 - strokes: [],
576 - styleChanges: [],
577 - screenshot: null,
578 - createdAt: "2026-07-27T00:00:00.000Z",
579 - };
580 - const onSendAnnotation = vi.fn();
581 - mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
582 -
583 - renderToStaticMarkup(
584 - <PreviewView
585 - threadRef={TEST_THREAD_REF}
586 - tabId="tab-1"
587 - visible
588 - onSendAnnotation={onSendAnnotation}
589 - />,
590 - );
591 - mocks.toggleAnnotation?.();
592 -
593 - await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
594 - expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, annotation);
595 - });
596 -
597 - it("retains the annotation locally when its own environment loses access during capture", async () => {
598 - const annotation = {
599 - id: "annotation-revoked",
600 - pageUrl: "https://example.com/dashboard",
601 - pageTitle: "Dashboard",
602 - comment: "Tighten this spacing",
603 - elements: [],
604 - regions: [],
605 - strokes: [],
606 - styleChanges: [],
607 - screenshot: null,
608 - createdAt: "2026-09-05T00:00:00.000Z",
609 - };
610 - const onSendAnnotation = vi.fn();
611 - let submitPick: (() => void) | undefined;
612 - mocks.pickElement.mockImplementationOnce(
613 - () =>
614 - new Promise((resolve) => {
615 - submitPick = () => resolve({ annotation, submission: "send" });
616 - }),
617 - );
618 - const document = installTestDom();
619 - const { createRoot } = await import("react-dom/client");
620 - const root = createRoot(document.createElement("div") as unknown as Element);
621 - const view = () => (
622 - <PreviewView
623 - threadRef={TEST_THREAD_REF}
624 - tabId="tab-1"
625 - visible
626 - onSendAnnotation={onSendAnnotation}
627 - />
628 - );
629 - try {
630 - await act(async () => root.render(view()));
631 - await act(async () => mocks.toggleAnnotation?.());
632 - expect(submitPick).toBeDefined();
633 - expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
634 -
635 - mocks.readEnvironmentScope.mockImplementation(
636 - (environmentId?: unknown) => environmentId !== TEST_THREAD_REF.environmentId,
637 - );
638 - await act(async () => root.render(view()));
639 - expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, false);
640 - await act(async () => submitPick!());
641 - expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, annotation);
642 - expect(onSendAnnotation).not.toHaveBeenCalled();
643 -
644 - mocks.readEnvironmentScope.mockReturnValue(true);
645 - mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
646 - await act(async () => root.render(view()));
647 - await act(async () => mocks.toggleAnnotation?.());
648 - expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
649 - expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null);
650 - } finally {
651 - await act(async () => root.unmount());
652 - vi.unstubAllGlobals();
653 - }
654 - });
655 -
656 - it("does not reopen a cancelled picker after the permission update finishes", async () => {
657 - let finishUpdate: (() => void) | undefined;
658 - mocks.setAnnotationSendEnabled.mockImplementationOnce(
659 - () =>
660 - new Promise<void>((resolve) => {
661 - finishUpdate = resolve;
662 - }),
663 - );
664 - const document = installTestDom();
665 - const { createRoot } = await import("react-dom/client");
666 - const root = createRoot(document.createElement("div") as unknown as Element);
667 - try {
668 - await act(async () =>
669 - root.render(<PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />),
670 - );
671 - await act(async () => mocks.toggleAnnotation?.());
672 - expect(finishUpdate).toBeDefined();
673 - expect(mocks.pickElement).not.toHaveBeenCalled();
674 - await act(async () => mocks.toggleAnnotation?.());
675 - expect(mocks.cancelPickElement).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID);
676 - await act(async () => finishUpdate!());
677 - expect(mocks.pickElement).not.toHaveBeenCalled();
678 - expect(mocks.addPreviewAnnotation).not.toHaveBeenCalled();
679 - } finally {
680 - await act(async () => root.unmount());
681 - vi.unstubAllGlobals();
682 - }
683 - });
684 -
685 - it("warns when main dropped the crop before handing over the pick", async () => {
686 - const annotation = {
687 - id: "annotation-3",
688 - pageUrl: "https://example.com/dashboard",
689 - pageTitle: "Dashboard",
690 - comment: "Tighten this spacing",
691 - elements: [],
692 - regions: [],
693 - strokes: [],
694 - styleChanges: [],
695 - screenshot: null,
696 - createdAt: "2026-07-27T00:00:00.000Z",
697 - };
698 - const onSendAnnotation = vi.fn();
699 - mocks.pickElement.mockResolvedValue({ annotation, submission: "send", screenshotFailed: true });
700 -
701 - renderToStaticMarkup(
702 - <PreviewView
703 - threadRef={TEST_THREAD_REF}
704 - tabId="tab-1"
705 - visible
706 - onSendAnnotation={onSendAnnotation}
707 - />,
708 - );
709 - mocks.toggleAnnotation?.();
710 -
711 - await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
712 - expect(toastManager.add).toHaveBeenCalledTimes(1);
713 - });
714 -
715 - it("still sends annotation text when the picked element's crop is malformed", async () => {
716 - const annotation = {
717 - id: "annotation-2",
718 - pageUrl: "https://example.com/dashboard",
719 - pageTitle: "Dashboard",
720 - comment: "Tighten this spacing",
721 - elements: [],
722 - regions: [],
723 - strokes: [],
724 - styleChanges: [],
725 - screenshot: {
726 - dataUrl: "data:image/png;base64,%%%",
727 - width: 10,
728 - height: 10,
729 - cropRect: { x: 0, y: 0, width: 10, height: 10 },
730 - },
731 - createdAt: "2026-07-27T00:00:00.000Z",
732 - };
733 - const onSendAnnotation = vi.fn();
734 - mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
735 -
736 - renderToStaticMarkup(
737 - <PreviewView
738 - threadRef={TEST_THREAD_REF}
739 - tabId="tab-1"
740 - visible
741 - onSendAnnotation={onSendAnnotation}
742 - />,
743 - );
744 - mocks.toggleAnnotation?.();
745 -
746 - const sent = { ...annotation, screenshot: null };
747 - await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(sent, null));
748 - expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, sent);
749 - expect(mocks.addImage).not.toHaveBeenCalled();
750 - });
751 -});
apps/web/src/components/usage/UsagePage.browser.test.tsx renamed
+18 -47
@@ -3,6 +3,9 @@ import { mergeUsage } from "@t3tools/shared/usageMerge";
3 import { act } from "react";
4 import { createRoot, type Root } from "react-dom/client";
5 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
6 +import { page, userEvent } from "vite-plus/test/browser";
7 +
8 +import "~/index.css";
9
10 const testState = vi.hoisted(() => ({
11 useUsage: vi.fn(),
@@ -10,43 +13,15 @@ const testState = vi.hoisted(() => ({
13 canGoBack: true,
14 }));
15
13 -vi.mock("../../env", () => ({ isElectron: false }));
14 -vi.mock("@tanstack/react-router", () => ({
15 - useNavigate: () => testState.navigate,
16 +vi.mock(import("@tanstack/react-router"), async (original) => ({
17 + ...(await original()),
18 + useNavigate: (() => testState.navigate) as never,
19 useCanGoBack: () => testState.canGoBack,
20 }));
18 -vi.mock("../../state/usage", () => ({ useUsage: testState.useUsage }));
19 -vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));
20 -vi.mock("../ui/select", () => ({
21 - Select: "div",
22 - SelectItem: "div",
23 - SelectPopup: "div",
24 - SelectTrigger: "div",
25 - SelectValue: "div",
26 -}));
27 -vi.mock("../ui/sidebar", () => ({ SidebarInset: "div" }));
28 -vi.mock("../ui/toggle-group", () => ({ Toggle: "button", ToggleGroup: "div" }));
29 -vi.mock("../WorkspaceBreadcrumb", () => ({
30 - WorkspaceBreadcrumb: "div",
31 - WorkspaceBreadcrumbItem: "div",
32 - WorkspaceBreadcrumbSeparator: "span",
33 - WorkspaceBreadcrumbText: "span",
21 +vi.mock(import("../../state/usage"), async (original) => ({
22 + ...(await original()),
23 + useUsage: testState.useUsage,
24 }));
35 -vi.mock("../WorkspacePageContainer", () => ({ WorkspacePageContainer: "main" }));
36 -vi.mock("../WorkspacePageHeader", () => ({ WorkspacePageHeader: "header" }));
37 -vi.mock("./UsageProviderChart", () => ({ UsageProviderChart: "div" }));
38 -vi.mock("./UsagePriceOverrides", () => ({ UsagePriceOverrides: () => null }));
39 -vi.mock("./usageProviders", async (importOriginal) => {
40 - const actual = await importOriginal<typeof import("./usageProviders")>();
41 - return {
42 - ...actual,
43 - PROVIDER_ORDER: ["codex", "claude"],
44 - PROVIDER_PRESENTATION: {
45 - codex: { color: "white", label: "Codex", mark: "span" },
46 - claude: { color: "orange", label: "Claude Code", mark: "span" },
47 - },
48 - };
49 -});
25
26 import { UsagePage } from "./UsagePage";
27 const environments = [
@@ -91,7 +66,6 @@ describe("UsagePage Escape navigation", () => {
66 back = vi.spyOn(window.history, "back").mockImplementation(() => {});
67 testState.navigate.mockClear();
68 testState.canGoBack = true;
94 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
69 container = document.createElement("div");
70 document.body.append(container);
71 renderer = createRoot(container);
@@ -104,9 +78,9 @@ describe("UsagePage Escape navigation", () => {
78 await act(() => renderer.unmount());
79 container.remove();
80 back.mockRestore();
107 - vi.unstubAllGlobals();
81 });
82
83 + // Playwright cannot press a repeating or composing key, so those cases dispatch the event.
84 function escape(properties: { repeat?: boolean; isComposing?: boolean } = {}) {
85 return new KeyboardEvent("keydown", {
86 bubbles: true,
@@ -116,8 +90,8 @@ describe("UsagePage Escape navigation", () => {
90 });
91 }
92
119 - it("returns to the previous page on Escape", () => {
120 - document.body.dispatchEvent(escape());
93 + it("returns to the previous page on Escape", async () => {
94 + await userEvent.keyboard("{Escape}");
95 expect(back).toHaveBeenCalledOnce();
96 expect(testState.navigate).not.toHaveBeenCalled();
97 });
@@ -126,23 +100,22 @@ describe("UsagePage Escape navigation", () => {
100 testState.canGoBack = false;
101 await act(() => renderer.render(<UsagePage />));
102
129 - document.body.dispatchEvent(escape());
103 + await userEvent.keyboard("{Escape}");
104 expect(testState.navigate).toHaveBeenCalledWith({ to: "/" });
105 expect(back).not.toHaveBeenCalled();
106 });
107
108 it("closes the environment menu before Escape navigates back", async () => {
109 const trigger = container.querySelector<HTMLButtonElement>('[data-slot="menu-trigger"]')!;
136 - await act(() => trigger.click());
137 - expect(document.querySelector('[role="menu"]')).not.toBeNull();
110 + await userEvent.click(trigger);
111 + await expect.element(page.getByRole("menu")).toBeVisible();
112
139 - await act(() => {
140 - document.activeElement!.dispatchEvent(escape());
141 - });
113 + await userEvent.keyboard("{Escape}");
114 + await vi.waitFor(() => expect(document.querySelector('[role="menu"]')).toBeNull());
115 expect(trigger.getAttribute("aria-expanded")).toBe("false");
116 expect(back).not.toHaveBeenCalled();
117
145 - document.body.dispatchEvent(escape());
118 + await userEvent.keyboard("{Escape}");
119 expect(back).toHaveBeenCalledOnce();
120 });
121
@@ -152,5 +125,3 @@ describe("UsagePage Escape navigation", () => {
125 expect(testState.navigate).not.toHaveBeenCalled();
126 });
127 });
155 -
156 -// @vitest-environment jsdom