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

PreviewView.test.tsx

580 lines17.3 KB

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