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