Open History to see the last commit
1import {
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";
10import { act, Profiler, type ComponentProps, type ReactNode } from "react";
11import { createRoot, type Root } from "react-dom/client";
12import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13import { page, userEvent } from "vite-plus/test/browser";
14
15import "~/index.css";
16
17import type { PreviewableServer } from "./useDiscoveredLocalServers";
18
19const 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
42const 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.
52vi.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}));
76vi.mock(import("~/browserHistoryStore"), async (original) => ({
77 ...(await original()),
78 recordVisitForThread: mocks.recordVisitForThread,
79}));
80vi.mock(import("~/state/session"), async (original) => ({
81 ...(await original()),
82 readPreparedConnection: mocks.readPreparedConnection as never,
83 readEnvironmentScope: mocks.readEnvironmentScope,
84 useEnvironmentScope: mocks.readEnvironmentScope,
85}));
86vi.mock(import("~/browser/browserDefaults"), async (original) => ({
87 ...(await original()),
88 useBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
89 getBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
90}));
91vi.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}));
126vi.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}));
132vi.mock(import("~/browser/browserRecording"), async (original) => ({
133 ...(await original()),
134 findActiveBrowserRecordingRuntimeTabId: () => mocks.recordingRuntimeTabId,
135 useActiveBrowserRecordingTabIds: () => mocks.recordingTabIds,
136}));
137vi.mock(import("~/components/ui/toast"), async (original) => {
138 const actual = await original();
139 return { ...actual, toastManager: { ...actual.toastManager, add: mocks.toast } };
140});
141vi.mock(import("./useDiscoveredLocalServers"), async (original) => ({
142 ...(await original()),
143 useDiscoveredLocalServers: () => mocks.servers,
144}));
145vi.mock(import("./usePreviewSession"), async (original) => ({
146 ...(await original()),
147 usePreviewSession: () => {},
148}));
149
150import { useComposerDraftStore } from "~/composerDraftStore";
151import { useBrowserPointerStore } from "~/browser/browserPointerStore";
152import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
153import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
154import { PreviewView } from "./PreviewView";
155
156const TEST_THREAD_REF = {
157 environmentId: EnvironmentId.make("environment-1"),
158 threadId: ThreadId.make("thread-1"),
159} as const;
160const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
161
162const roots: Root[] = [];
163let root: Root;
164
165async function render(node: ReactNode) {
166 await act(async () => root.render(node));
167}
168
169function 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
180function 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
195async 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
202function hasCursor() {
203 return document.querySelector("svg.lucide-mouse-pointer2") !== null;
204}
205
206describe("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});