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

PreviewView.test.tsx

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