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