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 previewAnnotationScreenshotFile: 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 previewAnnotationScreenshotFile: mocks.previewAnnotationScreenshotFile,
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, previewProfileName } from "./PreviewView";
255import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
256
257const TEST_THREAD_REF = {
258 environmentId: EnvironmentId.make("environment-1"),
259 threadId: ThreadId.make("thread-1"),
260} as const;
261const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
262
263// ReactDOM needs a host, but this unit suite intentionally has no DOM dependency.
264class TestNode {
265 parentNode: TestNode | null = null;
266 childNodes: TestNode[] = [];
267 readonly nodeName: string;
268 readonly tagName: string;
269 readonly namespaceURI = "http://www.w3.org/1999/xhtml";
270 readonly style = {};
271
272 constructor(
273 name: string,
274 readonly ownerDocument: TestNode | null = null,
275 readonly nodeType = 1,
276 ) {
277 this.nodeName = name.toUpperCase();
278 this.tagName = this.nodeName;
279 }
280
281 set textContent(_value: string) {
282 this.childNodes = [];
283 }
284
285 appendChild(child: TestNode) {
286 child.parentNode = this;
287 this.childNodes.push(child);
288 return child;
289 }
290
291 removeChild(child: TestNode) {
292 this.childNodes.splice(this.childNodes.indexOf(child), 1);
293 child.parentNode = null;
294 return child;
295 }
296
297 createElement(name: string) {
298 return new TestNode(name, this);
299 }
300
301 addEventListener() {}
302 removeEventListener() {}
303 setAttribute() {}
304}
305
306function installTestDom() {
307 const document = new TestNode("#document", null, 9);
308 const window = {
309 document,
310 HTMLIFrameElement: TestNode,
311 setInterval: globalThis.setInterval,
312 clearInterval: globalThis.clearInterval,
313 setTimeout: globalThis.setTimeout,
314 clearTimeout: globalThis.clearTimeout,
315 addEventListener() {},
316 removeEventListener() {},
317 };
318 vi.stubGlobal("document", document);
319 vi.stubGlobal("window", window);
320 vi.stubGlobal("HTMLIFrameElement", window.HTMLIFrameElement);
321 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
322 return document;
323}
324
325describe("PreviewView navigation", () => {
326 beforeEach(() => {
327 mocks.navigate.mockClear();
328 mocks.rememberPreviewUrl.mockClear();
329 mocks.readPreparedConnection.mockClear();
330 mocks.submittedUrl = null;
331 mocks.emptyStateUrl = null;
332 mocks.togglePictureInPicture = null;
333 mocks.toggleNativePictureInPicture = null;
334 mocks.pictureInPicturePressed = false;
335 mocks.miniPlayerTabId = null;
336 mocks.openMiniPlayer.mockClear();
337 mocks.closeMiniPlayer.mockClear();
338 mocks.closeRightPanel.mockClear();
339 mocks.openPictureInPicture.mockClear();
340 mocks.closePictureInPicture.mockClear();
341 mocks.pickElement.mockReset();
342 mocks.previewAnnotationScreenshotFile.mockReset();
343 mocks.addPreviewAnnotation.mockClear();
344 mocks.addImage.mockClear();
345 mocks.toggleAnnotation = null;
346 mocks.pictureInPicture = false;
347 mocks.showEmptyState = false;
348 mocks.loading = false;
349 mocks.recordVisitForThread.mockClear();
350 });
351
352 it("labels a tab whose saved profile was removed", () => {
353 expect(previewProfileName(BUILT_IN_BROWSER_PROFILES, "profile-removed")).toBe(
354 "Removed profile",
355 );
356 });
357
358 it("does not rerender while loading time passes", async () => {
359 vi.useFakeTimers();
360 mocks.loading = true;
361 const document = installTestDom();
362 const { createRoot } = await import("react-dom/client");
363 const root = createRoot(document.createElement("div") as unknown as Element);
364 const onRender = vi.fn();
365
366 try {
367 await act(() => {
368 root.render(
369 <Profiler id="preview" onRender={onRender}>
370 <PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />
371 </Profiler>,
372 );
373 });
374 const initialRenderCount = onRender.mock.calls.length;
375
376 await act(() => vi.advanceTimersByTimeAsync(1_000));
377
378 expect(onRender).toHaveBeenCalledTimes(initialRenderCount);
379 } finally {
380 await act(() => root.unmount());
381 vi.useRealTimers();
382 vi.unstubAllGlobals();
383 }
384 });
385
386 it.each([
387 [
388 "https://localhost:8000/dashboard?mode=test#top",
389 "https://localhost:8000/dashboard?mode=test#top",
390 ],
391 ["localhost:5173/app", "http://localhost:5173/app"],
392 ])("preserves a direct localhost URL in a WSL environment", async (submitted, expected) => {
393 renderToStaticMarkup(
394 <PreviewView
395 threadRef={{
396 environmentId: EnvironmentId.make("environment-1"),
397 threadId: ThreadId.make("thread-1"),
398 }}
399 tabId="tab-1"
400 visible
401 />,
402 );
403
404 expect(mocks.submittedUrl).not.toBeNull();
405 mocks.submittedUrl?.(submitted);
406
407 await vi.waitFor(() =>
408 expect(mocks.navigate).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID, expected),
409 );
410 expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
411 {
412 environmentId: "environment-1",
413 threadId: "thread-1",
414 },
415 expected,
416 );
417 });
418
419 it("records a history visit with the normalized requested url on submit", async () => {
420 renderToStaticMarkup(
421 <PreviewView
422 threadRef={{
423 environmentId: EnvironmentId.make("environment-1"),
424 threadId: ThreadId.make("thread-1"),
425 }}
426 tabId="tab-1"
427 visible
428 />,
429 );
430
431 mocks.submittedUrl?.("localhost:3000/admin");
432 await vi.waitFor(() => {
433 expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
434 expect.objectContaining({ threadId: expect.anything() }),
435 "http://localhost:3000/admin",
436 );
437 });
438 });
439
440 it("maps an empty-state localhost server onto the WSL host", async () => {
441 mocks.showEmptyState = true;
442 renderToStaticMarkup(
443 <PreviewView
444 threadRef={{
445 environmentId: EnvironmentId.make("environment-1"),
446 threadId: ThreadId.make("thread-1"),
447 }}
448 tabId="tab-1"
449 visible
450 />,
451 );
452
453 expect(mocks.emptyStateUrl).not.toBeNull();
454 mocks.emptyStateUrl?.("http://localhost:5173/app?mode=test#top");
455
456 await vi.waitFor(() =>
457 expect(mocks.navigate).toHaveBeenCalledWith(
458 TEST_RUNTIME_TAB_ID,
459 "http://172.25.85.75:5173/app?mode=test#top",
460 ),
461 );
462 expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
463 {
464 environmentId: "environment-1",
465 threadId: "thread-1",
466 },
467 "http://172.25.85.75:5173/app?mode=test#top",
468 );
469 await vi.waitFor(() =>
470 expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
471 expect.objectContaining({ threadId: expect.anything() }),
472 "http://localhost:5173/app?mode=test#top",
473 ),
474 );
475 });
476
477 it("opens and closes a thread-scoped floating preview for the active tab", async () => {
478 const props = {
479 threadRef: {
480 environmentId: EnvironmentId.make("environment-1"),
481 threadId: ThreadId.make("thread-1"),
482 },
483 tabId: "tab-1",
484 visible: true,
485 } as const;
486
487 renderToStaticMarkup(<PreviewView {...props} />);
488 expect(mocks.pictureInPicturePressed).toBe(false);
489 mocks.togglePictureInPicture?.();
490 expect(mocks.openMiniPlayer).toHaveBeenCalledWith(props.threadRef, "tab-1");
491 expect(mocks.closeRightPanel).toHaveBeenCalledWith(props.threadRef);
492
493 mocks.miniPlayerTabId = "tab-1";
494 renderToStaticMarkup(<PreviewView {...props} />);
495 expect(mocks.pictureInPicturePressed).toBe(true);
496 mocks.togglePictureInPicture?.();
497 expect(mocks.closeMiniPlayer).toHaveBeenCalledWith(props.threadRef);
498 });
499
500 it("keeps the native preview window as a secondary action", async () => {
501 const props = {
502 threadRef: {
503 environmentId: EnvironmentId.make("environment-1"),
504 threadId: ThreadId.make("thread-1"),
505 },
506 tabId: "tab-1",
507 visible: true,
508 } as const;
509
510 renderToStaticMarkup(<PreviewView {...props} />);
511 mocks.toggleNativePictureInPicture?.();
512 await vi.waitFor(() =>
513 expect(mocks.openPictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
514 );
515
516 mocks.pictureInPicture = true;
517 renderToStaticMarkup(<PreviewView {...props} />);
518 mocks.toggleNativePictureInPicture?.();
519 await vi.waitFor(() =>
520 expect(mocks.closePictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
521 );
522 });
523
524 it("forwards Cmd/Ctrl+Enter annotations to the composer send path", async () => {
525 const annotation = {
526 id: "annotation-1",
527 pageUrl: "https://example.com/dashboard",
528 pageTitle: "Dashboard",
529 comment: "Tighten this spacing",
530 elements: [],
531 regions: [],
532 strokes: [],
533 styleChanges: [],
534 screenshot: null,
535 createdAt: "2026-07-27T00:00:00.000Z",
536 };
537 const onSendAnnotation = vi.fn();
538 mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
539
540 renderToStaticMarkup(
541 <PreviewView
542 threadRef={TEST_THREAD_REF}
543 tabId="tab-1"
544 visible
545 onSendAnnotation={onSendAnnotation}
546 />,
547 );
548 mocks.toggleAnnotation?.();
549
550 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
551 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, annotation);
552 });
553
554 it("still sends when screenshot attachment conversion fails", async () => {
555 const annotation = {
556 id: "annotation-2",
557 pageUrl: "https://example.com/dashboard",
558 pageTitle: "Dashboard",
559 comment: "Tighten this spacing",
560 elements: [],
561 regions: [],
562 strokes: [],
563 styleChanges: [],
564 screenshot: {
565 dataUrl: "data:image/png;base64,c2NyZWVuc2hvdA==",
566 width: 10,
567 height: 10,
568 cropRect: { x: 0, y: 0, width: 10, height: 10 },
569 },
570 createdAt: "2026-07-27T00:00:00.000Z",
571 };
572 const onSendAnnotation = vi.fn();
573 mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
574 mocks.previewAnnotationScreenshotFile.mockRejectedValue(new Error("conversion failed"));
575
576 renderToStaticMarkup(
577 <PreviewView
578 threadRef={TEST_THREAD_REF}
579 tabId="tab-1"
580 visible
581 onSendAnnotation={onSendAnnotation}
582 />,
583 );
584 mocks.toggleAnnotation?.();
585
586 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
587 expect(mocks.addImage).not.toHaveBeenCalled();
588 });
589});