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 } from "react";
11import { renderToStaticMarkup } from "react-dom/server";
12import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
13
14const 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 submittedUrl: null as ((url: string) => void) | null,
19 emptyStateUrl: null as ((url: string) => void) | null,
20 togglePictureInPicture: null as (() => void) | null,
21 toggleNativePictureInPicture: null as (() => void) | null,
22 pictureInPicturePressed: false,
23 miniPlayerTabId: null as string | null,
24 openMiniPlayer: vi.fn(),
25 closeMiniPlayer: vi.fn(),
26 closeRightPanel: vi.fn(),
27 openPictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
28 closePictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
29 pickElement: vi.fn(),
30 addPreviewAnnotation: vi.fn(),
31 addImage: vi.fn(),
32 toggleAnnotation: null as (() => void) | null,
33 pictureInPicture: false,
34 showEmptyState: false,
35 loading: false,
36 recordVisitForThread: vi.fn(),
37}));
38
39const EMPTY_HISTORY: never[] = [];
40
41const STUB_BROWSER_DEFAULTS = {
42 viewport: FILL_PREVIEW_VIEWPORT,
43 zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
44 appearance: DEFAULT_PREVIEW_APPEARANCE,
45 autoShowFloatingPreview: true,
46 profiles: BUILT_IN_BROWSER_PROFILES,
47 profileId: DEFAULT_BROWSER_PROFILE_ID,
48};
49
50vi.mock("~/browserHistoryStore", () => ({
51 recordVisitForThread: mocks.recordVisitForThread,
52 setTitleForThreadUrl: vi.fn(),
53 removeUrlForThread: vi.fn(),
54 BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT: 50,
55 useThreadRecentHistory: () => EMPTY_HISTORY,
56}));
57
58vi.mock("~/state/session", async (importOriginal) => ({
59 ...(await importOriginal<typeof import("~/state/session")>()),
60 readPreparedConnection: mocks.readPreparedConnection,
61}));
62
63// Stubbed at the direct dependency rather than letting the real module pull in
64// `useSettings` -> `state/server`, which would drag the whole settings and
65// connection graph into a test that only cares about the browser chrome.
66vi.mock("~/browser/browserDefaults", () => ({
67 useBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
68 getBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
69 browserDefaultOpenViewport: () => FILL_PREVIEW_VIEWPORT,
70 browserDefaultOpenProfileId: () => DEFAULT_BROWSER_PROFILE_ID,
71 browserDefaultTabState: () => ({
72 zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
73 colorScheme: DEFAULT_PREVIEW_APPEARANCE,
74 }),
75 browserResponsiveViewportForToggle: () => ({
76 _tag: "freeform" as const,
77 width: 1024,
78 height: 768,
79 }),
80}));
81
82vi.mock("~/composerDraftStore", () => ({
83 useComposerDraftStore: (
84 select: (store: { addPreviewAnnotation: () => void; addImage: () => void }) => unknown,
85 ) =>
86 select({
87 addPreviewAnnotation: mocks.addPreviewAnnotation,
88 addImage: mocks.addImage,
89 }),
90}));
91
92vi.mock("~/localApi", () => ({
93 ensureLocalApi: vi.fn(),
94}));
95
96vi.mock("~/previewStateStore", () => ({
97 rememberPreviewUrl: mocks.rememberPreviewUrl,
98 updatePreviewServerSnapshot: vi.fn(),
99 useThreadPreviewState: () => ({
100 activeTabId: "tab-1",
101 desktopByTabId: {
102 "tab-1": {
103 hasWebContents: true,
104 canGoBack: false,
105 canGoForward: false,
106 loading: mocks.loading,
107 zoomFactor: 1,
108 pictureInPicture: mocks.pictureInPicture,
109 colorScheme: "system",
110 audioMuted: false,
111 audible: false,
112 controller: "none",
113 },
114 },
115 recentlySeenUrls: [],
116 sessions: mocks.showEmptyState
117 ? {}
118 : {
119 "tab-1": {
120 threadId: "thread-1",
121 tabId: "tab-1",
122 navStatus: {
123 _tag: "Success",
124 url: "http://example.com/",
125 title: "Example",
126 },
127 canGoBack: false,
128 canGoForward: false,
129 updatedAt: "2026-07-13T00:00:00.000Z",
130 },
131 },
132 }),
133}));
134
135vi.mock("~/state/environments", () => ({
136 useEnvironment: () => ({ label: "WSL" }),
137 useEnvironmentHttpBaseUrl: () => "http://172.25.85.75:3773",
138}));
139
140vi.mock("~/state/preview", () => ({
141 previewEnvironment: { open: {}, resize: {} },
142}));
143
144vi.mock("~/state/use-atom-command", () => ({
145 useAtomCommand: () => vi.fn(),
146}));
147
148vi.mock("~/browser/browserRecording", () => ({
149 findActiveBrowserRecordingRuntimeTabId: vi.fn(() => null),
150 isBrowserRecordingStartCancelledError: vi.fn(() => false),
151 startBrowserRecording: vi.fn(),
152 stopBrowserRecording: vi.fn(),
153 useActiveBrowserRecordingTabIds: () => new Set(),
154}));
155
156vi.mock("~/browser/browserSurfaceStore", () => ({
157 useBrowserSurfaceStore: (
158 select: (state: { byTabId: Record<string, { rect?: unknown }> }) => unknown,
159 ) => select({ byTabId: {} }),
160}));
161
162vi.mock("~/previewMiniPlayerStore", () => {
163 const usePreviewMiniPlayerStore = Object.assign(
164 (select: (state: unknown) => unknown) =>
165 select({
166 byThreadKey: mocks.miniPlayerTabId
167 ? {
168 "environment-1:thread-1": {
169 source: { kind: "browser", tabId: mocks.miniPlayerTabId },
170 position: null,
171 },
172 }
173 : {},
174 }),
175 {
176 getState: () => ({
177 open: mocks.openMiniPlayer,
178 close: mocks.closeMiniPlayer,
179 }),
180 },
181 );
182 return {
183 browserMiniPlayerSource: (tabId: string) => ({ kind: "browser", tabId }),
184 selectThreadPreviewMiniPlayerTabId: (
185 byThreadKey: Record<string, { source: { tabId: string }; position: null }>,
186 ) => byThreadKey["environment-1:thread-1"]?.source.tabId ?? null,
187 usePreviewMiniPlayerStore,
188 };
189});
190
191vi.mock("~/rightPanelStore", () => ({
192 useRightPanelStore: {
193 getState: () => ({ close: mocks.closeRightPanel }),
194 },
195}));
196
197vi.mock("~/components/ui/toast", () => ({
198 stackedThreadToast: vi.fn(),
199 toastManager: { add: vi.fn() },
200}));
201
202vi.mock("./previewBridge", () => ({
203 previewBridge: {
204 navigate: mocks.navigate,
205 pickElement: mocks.pickElement,
206 pictureInPicture: {
207 open: mocks.openPictureInPicture,
208 close: mocks.closePictureInPicture,
209 },
210 },
211}));
212
213vi.mock("./PreviewChromeRow", () => ({
214 PreviewChromeRow: (props: {
215 onSubmit: (url: string) => void;
216 onPickElement?: () => void;
217 onPictureInPicture?: () => void;
218 pictureInPicture?: boolean;
219 trailingActions?: {
220 props: { onNativePictureInPicture?: () => void };
221 };
222 }) => {
223 mocks.submittedUrl = props.onSubmit;
224 mocks.toggleAnnotation = props.onPickElement ?? null;
225 mocks.togglePictureInPicture = props.onPictureInPicture ?? null;
226 mocks.toggleNativePictureInPicture =
227 props.trailingActions?.props.onNativePictureInPicture ?? null;
228 mocks.pictureInPicturePressed = props.pictureInPicture ?? false;
229 return null;
230 },
231}));
232
233vi.mock("./PreviewEmptyState", () => ({
234 PreviewEmptyState: (props: { onOpenUrl: (url: string) => void }) => {
235 mocks.emptyStateUrl = props.onOpenUrl;
236 return null;
237 },
238}));
239vi.mock("./PreviewMoreMenu", () => ({
240 PreviewMoreMenu: (props: { onNativePictureInPicture: () => void }) => {
241 mocks.toggleNativePictureInPicture = props.onNativePictureInPicture;
242 return null;
243 },
244}));
245vi.mock("./PreviewUnreachable", () => ({ PreviewUnreachable: () => null }));
246vi.mock("./ZoomIndicator", () => ({ ZoomIndicator: () => null }));
247vi.mock("./AgentBrowserCursor", () => ({ AgentBrowserCursor: () => null }));
248vi.mock("~/browser/BrowserSurfaceSlot", () => ({ BrowserSurfaceSlot: () => null }));
249vi.mock("./usePreviewSession", () => ({ usePreviewSession: vi.fn() }));
250
251import { PreviewView } from "./PreviewView";
252import { toastManager } from "~/components/ui/toast";
253import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
254
255const TEST_THREAD_REF = {
256 environmentId: EnvironmentId.make("environment-1"),
257 threadId: ThreadId.make("thread-1"),
258} as const;
259const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
260
261// ReactDOM needs a host, but this unit suite intentionally has no DOM dependency.
262class TestNode {
263 parentNode: TestNode | null = null;
264 childNodes: TestNode[] = [];
265 readonly nodeName: string;
266 readonly tagName: string;
267 readonly namespaceURI = "http://www.w3.org/1999/xhtml";
268 readonly style = {};
269
270 constructor(
271 name: string,
272 readonly ownerDocument: TestNode | null = null,
273 readonly nodeType = 1,
274 ) {
275 this.nodeName = name.toUpperCase();
276 this.tagName = this.nodeName;
277 }
278
279 set textContent(_value: string) {
280 this.childNodes = [];
281 }
282
283 appendChild(child: TestNode) {
284 child.parentNode = this;
285 this.childNodes.push(child);
286 return child;
287 }
288
289 removeChild(child: TestNode) {
290 this.childNodes.splice(this.childNodes.indexOf(child), 1);
291 child.parentNode = null;
292 return child;
293 }
294
295 createElement(name: string) {
296 return new TestNode(name, this);
297 }
298
299 addEventListener() {}
300 removeEventListener() {}
301 setAttribute() {}
302}
303
304function installTestDom() {
305 const document = new TestNode("#document", null, 9);
306 const window = {
307 document,
308 HTMLIFrameElement: TestNode,
309 setInterval: globalThis.setInterval,
310 clearInterval: globalThis.clearInterval,
311 setTimeout: globalThis.setTimeout,
312 clearTimeout: globalThis.clearTimeout,
313 addEventListener() {},
314 removeEventListener() {},
315 };
316 vi.stubGlobal("document", document);
317 vi.stubGlobal("window", window);
318 vi.stubGlobal("HTMLIFrameElement", window.HTMLIFrameElement);
319 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
320 return document;
321}
322
323describe("PreviewView navigation", () => {
324 beforeEach(() => {
325 mocks.navigate.mockClear();
326 mocks.rememberPreviewUrl.mockClear();
327 mocks.readPreparedConnection.mockClear();
328 mocks.submittedUrl = null;
329 mocks.emptyStateUrl = null;
330 mocks.togglePictureInPicture = null;
331 mocks.toggleNativePictureInPicture = null;
332 mocks.pictureInPicturePressed = false;
333 mocks.miniPlayerTabId = null;
334 mocks.openMiniPlayer.mockClear();
335 mocks.closeMiniPlayer.mockClear();
336 mocks.closeRightPanel.mockClear();
337 mocks.openPictureInPicture.mockClear();
338 mocks.closePictureInPicture.mockClear();
339 mocks.pickElement.mockReset();
340 mocks.addPreviewAnnotation.mockClear();
341 vi.mocked(toastManager.add).mockClear();
342 mocks.addImage.mockClear();
343 mocks.toggleAnnotation = null;
344 mocks.pictureInPicture = false;
345 mocks.showEmptyState = false;
346 mocks.loading = false;
347 mocks.recordVisitForThread.mockClear();
348 });
349
350 it("does not rerender while loading time passes", async () => {
351 vi.useFakeTimers();
352 mocks.loading = true;
353 const document = installTestDom();
354 const { createRoot } = await import("react-dom/client");
355 const root = createRoot(document.createElement("div") as unknown as Element);
356 const onRender = vi.fn();
357
358 try {
359 await act(() => {
360 root.render(
361 <Profiler id="preview" onRender={onRender}>
362 <PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />
363 </Profiler>,
364 );
365 });
366 const initialRenderCount = onRender.mock.calls.length;
367
368 await act(() => vi.advanceTimersByTimeAsync(1_000));
369
370 expect(onRender).toHaveBeenCalledTimes(initialRenderCount);
371 } finally {
372 await act(() => root.unmount());
373 vi.useRealTimers();
374 vi.unstubAllGlobals();
375 }
376 });
377
378 it.each([
379 [
380 "https://localhost:8000/dashboard?mode=test#top",
381 "https://localhost:8000/dashboard?mode=test#top",
382 ],
383 ["localhost:5173/app", "http://localhost:5173/app"],
384 ])("preserves a direct localhost URL in a WSL environment", async (submitted, expected) => {
385 renderToStaticMarkup(
386 <PreviewView
387 threadRef={{
388 environmentId: EnvironmentId.make("environment-1"),
389 threadId: ThreadId.make("thread-1"),
390 }}
391 tabId="tab-1"
392 visible
393 />,
394 );
395
396 expect(mocks.submittedUrl).not.toBeNull();
397 mocks.submittedUrl?.(submitted);
398
399 await vi.waitFor(() =>
400 expect(mocks.navigate).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID, expected),
401 );
402 expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
403 {
404 environmentId: "environment-1",
405 threadId: "thread-1",
406 },
407 expected,
408 );
409 });
410
411 it("records a history visit with the normalized requested url on submit", async () => {
412 renderToStaticMarkup(
413 <PreviewView
414 threadRef={{
415 environmentId: EnvironmentId.make("environment-1"),
416 threadId: ThreadId.make("thread-1"),
417 }}
418 tabId="tab-1"
419 visible
420 />,
421 );
422
423 mocks.submittedUrl?.("localhost:3000/admin");
424 await vi.waitFor(() => {
425 expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
426 expect.objectContaining({ threadId: expect.anything() }),
427 "http://localhost:3000/admin",
428 );
429 });
430 });
431
432 it("maps an empty-state localhost server onto the WSL host", async () => {
433 mocks.showEmptyState = true;
434 renderToStaticMarkup(
435 <PreviewView
436 threadRef={{
437 environmentId: EnvironmentId.make("environment-1"),
438 threadId: ThreadId.make("thread-1"),
439 }}
440 tabId="tab-1"
441 visible
442 />,
443 );
444
445 expect(mocks.emptyStateUrl).not.toBeNull();
446 mocks.emptyStateUrl?.("http://localhost:5173/app?mode=test#top");
447
448 await vi.waitFor(() =>
449 expect(mocks.navigate).toHaveBeenCalledWith(
450 TEST_RUNTIME_TAB_ID,
451 "http://172.25.85.75:5173/app?mode=test#top",
452 ),
453 );
454 expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
455 {
456 environmentId: "environment-1",
457 threadId: "thread-1",
458 },
459 "http://172.25.85.75:5173/app?mode=test#top",
460 );
461 await vi.waitFor(() =>
462 expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
463 expect.objectContaining({ threadId: expect.anything() }),
464 "http://localhost:5173/app?mode=test#top",
465 ),
466 );
467 });
468
469 it("opens and closes a thread-scoped floating preview for the active tab", async () => {
470 const props = {
471 threadRef: {
472 environmentId: EnvironmentId.make("environment-1"),
473 threadId: ThreadId.make("thread-1"),
474 },
475 tabId: "tab-1",
476 visible: true,
477 } as const;
478
479 renderToStaticMarkup(<PreviewView {...props} />);
480 expect(mocks.pictureInPicturePressed).toBe(false);
481 mocks.togglePictureInPicture?.();
482 expect(mocks.openMiniPlayer).toHaveBeenCalledWith(props.threadRef, {
483 kind: "browser",
484 tabId: "tab-1",
485 });
486 expect(mocks.closeRightPanel).toHaveBeenCalledWith(props.threadRef);
487
488 mocks.miniPlayerTabId = "tab-1";
489 renderToStaticMarkup(<PreviewView {...props} />);
490 expect(mocks.pictureInPicturePressed).toBe(true);
491 mocks.togglePictureInPicture?.();
492 expect(mocks.closeMiniPlayer).toHaveBeenCalledWith(props.threadRef);
493 });
494
495 it("keeps the native preview window as a secondary action", async () => {
496 const props = {
497 threadRef: {
498 environmentId: EnvironmentId.make("environment-1"),
499 threadId: ThreadId.make("thread-1"),
500 },
501 tabId: "tab-1",
502 visible: true,
503 } as const;
504
505 renderToStaticMarkup(<PreviewView {...props} />);
506 mocks.toggleNativePictureInPicture?.();
507 await vi.waitFor(() =>
508 expect(mocks.openPictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
509 );
510
511 mocks.pictureInPicture = true;
512 renderToStaticMarkup(<PreviewView {...props} />);
513 mocks.toggleNativePictureInPicture?.();
514 await vi.waitFor(() =>
515 expect(mocks.closePictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
516 );
517 });
518
519 it("forwards Cmd/Ctrl+Enter annotations to the composer send path", async () => {
520 const annotation = {
521 id: "annotation-1",
522 pageUrl: "https://example.com/dashboard",
523 pageTitle: "Dashboard",
524 comment: "Tighten this spacing",
525 elements: [],
526 regions: [],
527 strokes: [],
528 styleChanges: [],
529 screenshot: null,
530 createdAt: "2026-07-27T00:00:00.000Z",
531 };
532 const onSendAnnotation = vi.fn();
533 mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
534
535 renderToStaticMarkup(
536 <PreviewView
537 threadRef={TEST_THREAD_REF}
538 tabId="tab-1"
539 visible
540 onSendAnnotation={onSendAnnotation}
541 />,
542 );
543 mocks.toggleAnnotation?.();
544
545 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
546 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, annotation);
547 });
548
549 it("warns when main dropped the crop before handing over the pick", async () => {
550 const annotation = {
551 id: "annotation-3",
552 pageUrl: "https://example.com/dashboard",
553 pageTitle: "Dashboard",
554 comment: "Tighten this spacing",
555 elements: [],
556 regions: [],
557 strokes: [],
558 styleChanges: [],
559 screenshot: null,
560 createdAt: "2026-07-27T00:00:00.000Z",
561 };
562 const onSendAnnotation = vi.fn();
563 mocks.pickElement.mockResolvedValue({ annotation, submission: "send", screenshotFailed: true });
564
565 renderToStaticMarkup(
566 <PreviewView
567 threadRef={TEST_THREAD_REF}
568 tabId="tab-1"
569 visible
570 onSendAnnotation={onSendAnnotation}
571 />,
572 );
573 mocks.toggleAnnotation?.();
574
575 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
576 // A null screenshot alone looks like a comment-only pick; the flag is what
577 // separates "no crop requested" from "crop lost to a timeout".
578 expect(toastManager.add).toHaveBeenCalledTimes(1);
579 });
580
581 it("still sends annotation text when the picked element's crop is malformed", async () => {
582 const annotation = {
583 id: "annotation-2",
584 pageUrl: "https://example.com/dashboard",
585 pageTitle: "Dashboard",
586 comment: "Tighten this spacing",
587 elements: [],
588 regions: [],
589 strokes: [],
590 styleChanges: [],
591 screenshot: {
592 dataUrl: "data:image/png;base64,%%%",
593 width: 10,
594 height: 10,
595 cropRect: { x: 0, y: 0, width: 10, height: 10 },
596 },
597 createdAt: "2026-07-27T00:00:00.000Z",
598 };
599 const onSendAnnotation = vi.fn();
600 mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
601
602 renderToStaticMarkup(
603 <PreviewView
604 threadRef={TEST_THREAD_REF}
605 tabId="tab-1"
606 visible
607 onSendAnnotation={onSendAnnotation}
608 />,
609 );
610 mocks.toggleAnnotation?.();
611
612 // The forwarded and stored annotation both drop the screenshot, so the
613 // prompt does not claim a crop that was never attached.
614 const sent = { ...annotation, screenshot: null };
615 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(sent, null));
616 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, sent);
617 expect(mocks.addImage).not.toHaveBeenCalled();
618 });
619});