Open History to see the last commit
1import {
2 DEFAULT_PREVIEW_APPEARANCE,
3 DEFAULT_PREVIEW_ZOOM_FACTOR,
4 EnvironmentId,
5 FILL_PREVIEW_VIEWPORT,
6 ThreadId,
7} from "@t3tools/contracts";
8import { act, Profiler } from "react";
9import { renderToStaticMarkup } from "react-dom/server";
10import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
11
12const mocks = vi.hoisted(() => ({
13 navigate: vi.fn(async (_tabId: string, _url: string): Promise<void> => undefined),
14 rememberPreviewUrl: vi.fn(),
15 readPreparedConnection: vi.fn(() => ({ httpBaseUrl: "http://172.25.85.75:3773" })),
16 submittedUrl: null as ((url: string) => void) | null,
17 emptyStateUrl: null as ((url: string) => void) | null,
18 togglePictureInPicture: null as (() => void) | null,
19 toggleNativePictureInPicture: null as (() => void) | null,
20 pictureInPicturePressed: false,
21 miniPlayerTabId: null as string | null,
22 openMiniPlayer: vi.fn(),
23 closeMiniPlayer: vi.fn(),
24 closeRightPanel: vi.fn(),
25 openPictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
26 closePictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
27 pickElement: vi.fn(),
28 previewAnnotationScreenshotFile: vi.fn(),
29 addPreviewAnnotation: vi.fn(),
30 addImage: vi.fn(),
31 toggleAnnotation: null as (() => void) | null,
32 pictureInPicture: false,
33 showEmptyState: false,
34 loading: false,
35 recordVisitForThread: vi.fn(),
36}));
37
38const EMPTY_HISTORY: never[] = [];
39
40vi.mock("~/browserHistoryStore", () => ({
41 recordVisitForThread: mocks.recordVisitForThread,
42 setTitleForThreadUrl: vi.fn(),
43 removeUrlForThread: vi.fn(),
44 BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT: 50,
45 useThreadRecentHistory: () => EMPTY_HISTORY,
46}));
47
48vi.mock("~/state/session", () => ({
49 readPreparedConnection: mocks.readPreparedConnection,
50}));
51
52// Stubbed at the direct dependency rather than letting the real module pull in
53// `useSettings` -> `state/server`, which would drag the whole settings and
54// connection graph into a test that only cares about the browser chrome.
55vi.mock("~/browser/browserDefaults", () => ({
56 useBrowserDefaults: () => ({
57 viewport: FILL_PREVIEW_VIEWPORT,
58 zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
59 appearance: DEFAULT_PREVIEW_APPEARANCE,
60 autoShowFloatingPreview: true,
61 }),
62 getBrowserDefaults: () => ({
63 viewport: FILL_PREVIEW_VIEWPORT,
64 zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
65 appearance: DEFAULT_PREVIEW_APPEARANCE,
66 autoShowFloatingPreview: true,
67 }),
68 browserDefaultOpenViewport: () => FILL_PREVIEW_VIEWPORT,
69 browserDefaultTabState: () => ({
70 zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
71 colorScheme: DEFAULT_PREVIEW_APPEARANCE,
72 }),
73 browserResponsiveViewportForToggle: () => ({
74 _tag: "freeform" as const,
75 width: 1024,
76 height: 768,
77 }),
78}));
79
80vi.mock("~/composerDraftStore", () => ({
81 useComposerDraftStore: (
82 select: (store: { addPreviewAnnotation: () => void; addImage: () => void }) => unknown,
83 ) =>
84 select({
85 addPreviewAnnotation: mocks.addPreviewAnnotation,
86 addImage: mocks.addImage,
87 }),
88}));
89
90vi.mock("~/lib/previewAnnotation", () => ({
91 previewAnnotationScreenshotFile: mocks.previewAnnotationScreenshotFile,
92}));
93
94vi.mock("~/localApi", () => ({
95 ensureLocalApi: vi.fn(),
96}));
97
98vi.mock("~/previewStateStore", () => ({
99 rememberPreviewUrl: mocks.rememberPreviewUrl,
100 updatePreviewServerSnapshot: vi.fn(),
101 useThreadPreviewState: () => ({
102 activeTabId: "tab-1",
103 desktopByTabId: {
104 "tab-1": {
105 hasWebContents: true,
106 canGoBack: false,
107 canGoForward: false,
108 loading: mocks.loading,
109 zoomFactor: 1,
110 pictureInPicture: mocks.pictureInPicture,
111 colorScheme: "system",
112 audioMuted: false,
113 audible: false,
114 controller: "none",
115 },
116 },
117 recentlySeenUrls: [],
118 sessions: mocks.showEmptyState
119 ? {}
120 : {
121 "tab-1": {
122 threadId: "thread-1",
123 tabId: "tab-1",
124 navStatus: {
125 _tag: "Success",
126 url: "http://example.com/",
127 title: "Example",
128 },
129 canGoBack: false,
130 canGoForward: false,
131 updatedAt: "2026-07-13T00:00:00.000Z",
132 },
133 },
134 }),
135}));
136
137vi.mock("~/state/environments", () => ({
138 useEnvironment: () => ({ label: "WSL" }),
139 useEnvironmentHttpBaseUrl: () => "http://172.25.85.75:3773",
140}));
141
142vi.mock("~/state/preview", () => ({
143 previewEnvironment: { open: {}, resize: {} },
144}));
145
146vi.mock("~/state/use-atom-command", () => ({
147 useAtomCommand: () => vi.fn(),
148}));
149
150vi.mock("~/browser/browserRecording", () => ({
151 findActiveBrowserRecordingRuntimeTabId: vi.fn(() => null),
152 isBrowserRecordingStartCancelledError: vi.fn(() => false),
153 startBrowserRecording: vi.fn(),
154 stopBrowserRecording: vi.fn(),
155 useActiveBrowserRecordingTabIds: () => new Set(),
156}));
157
158vi.mock("~/browser/browserSurfaceStore", () => ({
159 useBrowserSurfaceStore: (
160 select: (state: { byTabId: Record<string, { rect?: unknown }> }) => unknown,
161 ) => select({ byTabId: {} }),
162}));
163
164vi.mock("~/previewMiniPlayerStore", () => {
165 const usePreviewMiniPlayerStore = Object.assign(
166 (select: (state: unknown) => unknown) =>
167 select({
168 byThreadKey: mocks.miniPlayerTabId
169 ? {
170 "environment-1:thread-1": {
171 tabId: mocks.miniPlayerTabId,
172 position: null,
173 },
174 }
175 : {},
176 }),
177 {
178 getState: () => ({
179 open: mocks.openMiniPlayer,
180 close: mocks.closeMiniPlayer,
181 }),
182 },
183 );
184 return {
185 selectThreadPreviewMiniPlayer: (
186 byThreadKey: Record<string, { tabId: string; position: null }>,
187 ) => byThreadKey["environment-1:thread-1"] ?? null,
188 usePreviewMiniPlayerStore,
189 };
190});
191
192vi.mock("~/rightPanelStore", () => ({
193 useRightPanelStore: {
194 getState: () => ({ close: mocks.closeRightPanel }),
195 },
196}));
197
198vi.mock("~/components/ui/toast", () => ({
199 stackedThreadToast: vi.fn(),
200 toastManager: { add: vi.fn() },
201}));
202
203vi.mock("./previewBridge", () => ({
204 previewBridge: {
205 navigate: mocks.navigate,
206 pickElement: mocks.pickElement,
207 pictureInPicture: {
208 open: mocks.openPictureInPicture,
209 close: mocks.closePictureInPicture,
210 },
211 },
212}));
213
214vi.mock("./PreviewChromeRow", () => ({
215 PreviewChromeRow: (props: {
216 onSubmit: (url: string) => void;
217 onPickElement?: () => void;
218 onPictureInPicture?: () => void;
219 pictureInPicture?: boolean;
220 trailingActions?: {
221 props: { onNativePictureInPicture?: () => void };
222 };
223 }) => {
224 mocks.submittedUrl = props.onSubmit;
225 mocks.toggleAnnotation = props.onPickElement ?? null;
226 mocks.togglePictureInPicture = props.onPictureInPicture ?? null;
227 mocks.toggleNativePictureInPicture =
228 props.trailingActions?.props.onNativePictureInPicture ?? null;
229 mocks.pictureInPicturePressed = props.pictureInPicture ?? false;
230 return null;
231 },
232}));
233
234vi.mock("./PreviewEmptyState", () => ({
235 PreviewEmptyState: (props: { onOpenUrl: (url: string) => void }) => {
236 mocks.emptyStateUrl = props.onOpenUrl;
237 return null;
238 },
239}));
240vi.mock("./PreviewMoreMenu", () => ({
241 PreviewMoreMenu: (props: { onNativePictureInPicture: () => void }) => {
242 mocks.toggleNativePictureInPicture = props.onNativePictureInPicture;
243 return null;
244 },
245}));
246vi.mock("./PreviewUnreachable", () => ({ PreviewUnreachable: () => null }));
247vi.mock("./ZoomIndicator", () => ({ ZoomIndicator: () => null }));
248vi.mock("./AgentBrowserCursor", () => ({ AgentBrowserCursor: () => null }));
249vi.mock("~/browser/BrowserSurfaceSlot", () => ({ BrowserSurfaceSlot: () => null }));
250vi.mock("./usePreviewSession", () => ({ usePreviewSession: vi.fn() }));
251
252import { PreviewView } from "./PreviewView";
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.previewAnnotationScreenshotFile.mockReset();
341 mocks.addPreviewAnnotation.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, "tab-1");
483 expect(mocks.closeRightPanel).toHaveBeenCalledWith(props.threadRef);
484
485 mocks.miniPlayerTabId = "tab-1";
486 renderToStaticMarkup(<PreviewView {...props} />);
487 expect(mocks.pictureInPicturePressed).toBe(true);
488 mocks.togglePictureInPicture?.();
489 expect(mocks.closeMiniPlayer).toHaveBeenCalledWith(props.threadRef);
490 });
491
492 it("keeps the native preview window as a secondary action", async () => {
493 const props = {
494 threadRef: {
495 environmentId: EnvironmentId.make("environment-1"),
496 threadId: ThreadId.make("thread-1"),
497 },
498 tabId: "tab-1",
499 visible: true,
500 } as const;
501
502 renderToStaticMarkup(<PreviewView {...props} />);
503 mocks.toggleNativePictureInPicture?.();
504 await vi.waitFor(() =>
505 expect(mocks.openPictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
506 );
507
508 mocks.pictureInPicture = true;
509 renderToStaticMarkup(<PreviewView {...props} />);
510 mocks.toggleNativePictureInPicture?.();
511 await vi.waitFor(() =>
512 expect(mocks.closePictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
513 );
514 });
515
516 it("forwards Cmd/Ctrl+Enter annotations to the composer send path", async () => {
517 const annotation = {
518 id: "annotation-1",
519 pageUrl: "https://example.com/dashboard",
520 pageTitle: "Dashboard",
521 comment: "Tighten this spacing",
522 elements: [],
523 regions: [],
524 strokes: [],
525 styleChanges: [],
526 screenshot: null,
527 createdAt: "2026-07-27T00:00:00.000Z",
528 };
529 const onSendAnnotation = vi.fn();
530 mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
531
532 renderToStaticMarkup(
533 <PreviewView
534 threadRef={TEST_THREAD_REF}
535 tabId="tab-1"
536 visible
537 onSendAnnotation={onSendAnnotation}
538 />,
539 );
540 mocks.toggleAnnotation?.();
541
542 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
543 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, annotation);
544 });
545
546 it("still sends when screenshot attachment conversion fails", async () => {
547 const annotation = {
548 id: "annotation-2",
549 pageUrl: "https://example.com/dashboard",
550 pageTitle: "Dashboard",
551 comment: "Tighten this spacing",
552 elements: [],
553 regions: [],
554 strokes: [],
555 styleChanges: [],
556 screenshot: {
557 dataUrl: "data:image/png;base64,c2NyZWVuc2hvdA==",
558 width: 10,
559 height: 10,
560 cropRect: { x: 0, y: 0, width: 10, height: 10 },
561 },
562 createdAt: "2026-07-27T00:00:00.000Z",
563 };
564 const onSendAnnotation = vi.fn();
565 mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
566 mocks.previewAnnotationScreenshotFile.mockRejectedValue(new Error("conversion failed"));
567
568 renderToStaticMarkup(
569 <PreviewView
570 threadRef={TEST_THREAD_REF}
571 tabId="tab-1"
572 visible
573 onSendAnnotation={onSendAnnotation}
574 />,
575 );
576 mocks.toggleAnnotation?.();
577
578 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
579 expect(mocks.addImage).not.toHaveBeenCalled();
580 });
581});