Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PreviewView.test.tsx

628 lines19.1 KB

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, previewProfileName } 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() {}
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;
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("labels a tab whose saved profile was removed", () => {
356 expect(previewProfileName(BUILT_IN_BROWSER_PROFILES, "profile-removed")).toBe(
357 "Removed profile",
358 );
359 });
360​
361 it("does not rerender while loading time passes", async () => {
362 vi.useFakeTimers();
363 mocks.loading = true;
364 const document = installTestDom();
365 const { createRoot } = await import("react-dom/client");
366 const root = createRoot(document.createElement("div") as unknown as Element);
367 const onRender = vi.fn();
368​
369 try {
370 await act(() => {
371 root.render(
372 <Profiler id="preview" onRender={onRender}>
373 <PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />
374 </Profiler>,
375 );
376 });
377 const initialRenderCount = onRender.mock.calls.length;
378​
379 await act(() => vi.advanceTimersByTimeAsync(1_000));
380​
381 expect(onRender).toHaveBeenCalledTimes(initialRenderCount);
382 } finally {
383 await act(() => root.unmount());
384 vi.useRealTimers();
385 vi.unstubAllGlobals();
386 }
387 });
388​
389 it.each([
390 [
391 "https://localhost:8000/dashboard?mode=test#top",
392 "https://localhost:8000/dashboard?mode=test#top",
393 ],
394 ["localhost:5173/app", "http://localhost:5173/app"],
395 ])("preserves a direct localhost URL in a WSL environment", async (submitted, expected) => {
396 renderToStaticMarkup(
397 <PreviewView
398 threadRef={{
399 environmentId: EnvironmentId.make("environment-1"),
400 threadId: ThreadId.make("thread-1"),
401 }}
402 tabId="tab-1"
403 visible
404 />,
405 );
406​
407 expect(mocks.submittedUrl).not.toBeNull();
408 mocks.submittedUrl?.(submitted);
409​
410 await vi.waitFor(() =>
411 expect(mocks.navigate).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID, expected),
412 );
413 expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
414 {
415 environmentId: "environment-1",
416 threadId: "thread-1",
417 },
418 expected,
419 );
420 });
421​
422 it("records a history visit with the normalized requested url on submit", async () => {
423 renderToStaticMarkup(
424 <PreviewView
425 threadRef={{
426 environmentId: EnvironmentId.make("environment-1"),
427 threadId: ThreadId.make("thread-1"),
428 }}
429 tabId="tab-1"
430 visible
431 />,
432 );
433​
434 mocks.submittedUrl?.("localhost:3000/admin");
435 await vi.waitFor(() => {
436 expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
437 expect.objectContaining({ threadId: expect.anything() }),
438 "http://localhost:3000/admin",
439 );
440 });
441 });
442​
443 it("maps an empty-state localhost server onto the WSL host", async () => {
444 mocks.showEmptyState = true;
445 renderToStaticMarkup(
446 <PreviewView
447 threadRef={{
448 environmentId: EnvironmentId.make("environment-1"),
449 threadId: ThreadId.make("thread-1"),
450 }}
451 tabId="tab-1"
452 visible
453 />,
454 );
455​
456 expect(mocks.emptyStateUrl).not.toBeNull();
457 mocks.emptyStateUrl?.("http://localhost:5173/app?mode=test#top");
458​
459 await vi.waitFor(() =>
460 expect(mocks.navigate).toHaveBeenCalledWith(
461 TEST_RUNTIME_TAB_ID,
462 "http://172.25.85.75:5173/app?mode=test#top",
463 ),
464 );
465 expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
466 {
467 environmentId: "environment-1",
468 threadId: "thread-1",
469 },
470 "http://172.25.85.75:5173/app?mode=test#top",
471 );
472 await vi.waitFor(() =>
473 expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
474 expect.objectContaining({ threadId: expect.anything() }),
475 "http://localhost:5173/app?mode=test#top",
476 ),
477 );
478 });
479​
480 it("opens and closes a thread-scoped floating preview for the active tab", async () => {
481 const props = {
482 threadRef: {
483 environmentId: EnvironmentId.make("environment-1"),
484 threadId: ThreadId.make("thread-1"),
485 },
486 tabId: "tab-1",
487 visible: true,
488 } as const;
489​
490 renderToStaticMarkup(<PreviewView {...props} />);
491 expect(mocks.pictureInPicturePressed).toBe(false);
492 mocks.togglePictureInPicture?.();
493 expect(mocks.openMiniPlayer).toHaveBeenCalledWith(props.threadRef, "tab-1");
494 expect(mocks.closeRightPanel).toHaveBeenCalledWith(props.threadRef);
495​
496 mocks.miniPlayerTabId = "tab-1";
497 renderToStaticMarkup(<PreviewView {...props} />);
498 expect(mocks.pictureInPicturePressed).toBe(true);
499 mocks.togglePictureInPicture?.();
500 expect(mocks.closeMiniPlayer).toHaveBeenCalledWith(props.threadRef);
501 });
502​
503 it("keeps the native preview window as a secondary action", async () => {
504 const props = {
505 threadRef: {
506 environmentId: EnvironmentId.make("environment-1"),
507 threadId: ThreadId.make("thread-1"),
508 },
509 tabId: "tab-1",
510 visible: true,
511 } as const;
512​
513 renderToStaticMarkup(<PreviewView {...props} />);
514 mocks.toggleNativePictureInPicture?.();
515 await vi.waitFor(() =>
516 expect(mocks.openPictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
517 );
518​
519 mocks.pictureInPicture = true;
520 renderToStaticMarkup(<PreviewView {...props} />);
521 mocks.toggleNativePictureInPicture?.();
522 await vi.waitFor(() =>
523 expect(mocks.closePictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
524 );
525 });
526​
527 it("forwards Cmd/Ctrl+Enter annotations to the composer send path", async () => {
528 const annotation = {
529 id: "annotation-1",
530 pageUrl: "https://example.com/dashboard",
531 pageTitle: "Dashboard",
532 comment: "Tighten this spacing",
533 elements: [],
534 regions: [],
535 strokes: [],
536 styleChanges: [],
537 screenshot: null,
538 createdAt: "2026-07-27T00:00:00.000Z",
539 };
540 const onSendAnnotation = vi.fn();
541 mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
542​
543 renderToStaticMarkup(
544 <PreviewView
545 threadRef={TEST_THREAD_REF}
546 tabId="tab-1"
547 visible
548 onSendAnnotation={onSendAnnotation}
549 />,
550 );
551 mocks.toggleAnnotation?.();
552​
553 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
554 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, annotation);
555 });
556​
557 it("warns when main dropped the crop before handing over the pick", async () => {
558 const annotation = {
559 id: "annotation-3",
560 pageUrl: "https://example.com/dashboard",
561 pageTitle: "Dashboard",
562 comment: "Tighten this spacing",
563 elements: [],
564 regions: [],
565 strokes: [],
566 styleChanges: [],
567 screenshot: null,
568 createdAt: "2026-07-27T00:00:00.000Z",
569 };
570 const onSendAnnotation = vi.fn();
571 mocks.pickElement.mockResolvedValue({ annotation, submission: "send", screenshotFailed: true });
572​
573 renderToStaticMarkup(
574 <PreviewView
575 threadRef={TEST_THREAD_REF}
576 tabId="tab-1"
577 visible
578 onSendAnnotation={onSendAnnotation}
579 />,
580 );
581 mocks.toggleAnnotation?.();
582​
583 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
584 // A null screenshot alone looks like a comment-only pick; the flag is what
585 // separates "no crop requested" from "crop lost to a timeout".
586 expect(toastManager.add).toHaveBeenCalledTimes(1);
587 });
588​
589 it("still sends when the picked element's crop cannot be captured", async () => {
590 const annotation = {
591 id: "annotation-2",
592 pageUrl: "https://example.com/dashboard",
593 pageTitle: "Dashboard",
594 comment: "Tighten this spacing",
595 elements: [],
596 regions: [],
597 strokes: [],
598 styleChanges: [],
599 screenshot: {
600 dataUrl: "data:image/png;base64,c2NyZWVuc2hvdA==",
601 width: 10,
602 height: 10,
603 cropRect: { x: 0, y: 0, width: 10, height: 10 },
604 },
605 createdAt: "2026-07-27T00:00:00.000Z",
606 };
607 const onSendAnnotation = vi.fn();
608 mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
609 mocks.capturePreviewAnnotationScreenshot.mockResolvedValue({ status: "failed" });
610​
611 renderToStaticMarkup(
612 <PreviewView
613 threadRef={TEST_THREAD_REF}
614 tabId="tab-1"
615 visible
616 onSendAnnotation={onSendAnnotation}
617 />,
618 );
619 mocks.toggleAnnotation?.();
620​
621 // The forwarded and stored annotation both drop the screenshot, so the
622 // prompt does not claim a crop that was never attached.
623 const sent = { ...annotation, screenshot: null };
624 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(sent, null));
625 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, sent);
626 expect(mocks.addImage).not.toHaveBeenCalled();
627 });
628});