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

PreviewView.test.tsx

488 lines14.9 KB

1import {
2 DEFAULT_PREVIEW_APPEARANCE,
3 DEFAULT_PREVIEW_ZOOM_FACTOR,
4 EnvironmentId,
5 FILL_PREVIEW_VIEWPORT,
6 ThreadId,
7} from "@t3tools/contracts";
8import { renderToStaticMarkup } from "react-dom/server";
9import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
10​
11const mocks = vi.hoisted(() => ({
12 navigate: vi.fn(async (_tabId: string, _url: string): Promise<void> => undefined),
13 rememberPreviewUrl: vi.fn(),
14 readPreparedConnection: vi.fn(() => ({ httpBaseUrl: "http://172.25.85.75:3773" })),
15 submittedUrl: null as ((url: string) => void) | null,
16 emptyStateUrl: null as ((url: string) => void) | null,
17 togglePictureInPicture: null as (() => void) | null,
18 toggleNativePictureInPicture: null as (() => void) | null,
19 pictureInPicturePressed: false,
20 miniPlayerTabId: null as string | null,
21 openMiniPlayer: vi.fn(),
22 closeMiniPlayer: vi.fn(),
23 closeRightPanel: vi.fn(),
24 openPictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
25 closePictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
26 pickElement: vi.fn(),
27 previewAnnotationScreenshotFile: vi.fn(),
28 addPreviewAnnotation: vi.fn(),
29 addImage: vi.fn(),
30 toggleAnnotation: null as (() => void) | null,
31 pictureInPicture: false,
32 showEmptyState: false,
33 recordVisitForThread: vi.fn(),
34}));
35​
36const EMPTY_HISTORY: never[] = [];
37​
38vi.mock("~/browserHistoryStore", () => ({
39 recordVisitForThread: mocks.recordVisitForThread,
40 setTitleForThreadUrl: vi.fn(),
41 removeUrlForThread: vi.fn(),
42 BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT: 50,
43 useThreadRecentHistory: () => EMPTY_HISTORY,
44}));
45​
46vi.mock("~/state/session", () => ({
47 readPreparedConnection: mocks.readPreparedConnection,
48}));
49​
50// Stubbed at the direct dependency rather than letting the real module pull in
51// `useSettings` -> `state/server`, which would drag the whole settings and
52// connection graph into a test that only cares about the browser chrome.
53vi.mock("~/browser/browserDefaults", () => ({
54 useBrowserDefaults: () => ({
55 viewport: FILL_PREVIEW_VIEWPORT,
56 zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
57 appearance: DEFAULT_PREVIEW_APPEARANCE,
58 autoShowFloatingPreview: true,
59 }),
60 getBrowserDefaults: () => ({
61 viewport: FILL_PREVIEW_VIEWPORT,
62 zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
63 appearance: DEFAULT_PREVIEW_APPEARANCE,
64 autoShowFloatingPreview: true,
65 }),
66 browserDefaultOpenViewport: () => FILL_PREVIEW_VIEWPORT,
67 browserDefaultTabState: () => ({
68 zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
69 colorScheme: DEFAULT_PREVIEW_APPEARANCE,
70 }),
71 browserResponsiveViewportForToggle: () => ({
72 _tag: "freeform" as const,
73 width: 1024,
74 height: 768,
75 }),
76}));
77​
78vi.mock("~/composerDraftStore", () => ({
79 useComposerDraftStore: (
80 select: (store: { addPreviewAnnotation: () => void; addImage: () => void }) => unknown,
81 ) =>
82 select({
83 addPreviewAnnotation: mocks.addPreviewAnnotation,
84 addImage: mocks.addImage,
85 }),
86}));
87​
88vi.mock("~/lib/previewAnnotation", () => ({
89 previewAnnotationScreenshotFile: mocks.previewAnnotationScreenshotFile,
90}));
91​
92vi.mock("~/localApi", () => ({
93 ensureLocalApi: vi.fn(),
94}));
95​
96vi.mock("~/previewStateStore", () => ({
97 rememberPreviewUrl: mocks.rememberPreviewUrl,
98 updatePreviewServerSnapshot: vi.fn(),
99 useThreadPreviewState: () => ({
100 activeTabId: "tab-1",
101 desktopByTabId: {
102 "tab-1": {
103 hasWebContents: true,
104 canGoBack: false,
105 canGoForward: false,
106 loading: false,
107 zoomFactor: 1,
108 pictureInPicture: mocks.pictureInPicture,
109 colorScheme: "system",
110 audioMuted: false,
111 audible: false,
112 controller: "none",
113 },
114 },
115 recentlySeenUrls: [],
116 sessions: mocks.showEmptyState
117 ? {}
118 : {
119 "tab-1": {
120 threadId: "thread-1",
121 tabId: "tab-1",
122 navStatus: {
123 _tag: "Success",
124 url: "http://example.com/",
125 title: "Example",
126 },
127 canGoBack: false,
128 canGoForward: false,
129 updatedAt: "2026-07-13T00:00:00.000Z",
130 },
131 },
132 }),
133}));
134​
135vi.mock("~/state/environments", () => ({
136 useEnvironment: () => ({ label: "WSL" }),
137 useEnvironmentHttpBaseUrl: () => "http://172.25.85.75:3773",
138}));
139​
140vi.mock("~/state/preview", () => ({
141 previewEnvironment: { open: {}, resize: {} },
142}));
143​
144vi.mock("~/state/use-atom-command", () => ({
145 useAtomCommand: () => vi.fn(),
146}));
147​
148vi.mock("~/browser/browserRecording", () => ({
149 findActiveBrowserRecordingRuntimeTabId: vi.fn(() => null),
150 startBrowserRecording: vi.fn(),
151 stopBrowserRecording: vi.fn(),
152 useActiveBrowserRecordingTabIds: () => new Set(),
153}));
154​
155vi.mock("~/browser/browserSurfaceStore", () => ({
156 useBrowserSurfaceStore: (
157 select: (state: { byTabId: Record<string, { rect?: unknown }> }) => unknown,
158 ) => select({ byTabId: {} }),
159}));
160​
161vi.mock("~/previewMiniPlayerStore", () => {
162 const usePreviewMiniPlayerStore = Object.assign(
163 (select: (state: unknown) => unknown) =>
164 select({
165 byThreadKey: mocks.miniPlayerTabId
166 ? {
167 "environment-1:thread-1": {
168 tabId: mocks.miniPlayerTabId,
169 position: null,
170 },
171 }
172 : {},
173 }),
174 {
175 getState: () => ({
176 open: mocks.openMiniPlayer,
177 close: mocks.closeMiniPlayer,
178 }),
179 },
180 );
181 return {
182 selectThreadPreviewMiniPlayer: (
183 byThreadKey: Record<string, { tabId: string; position: null }>,
184 ) => byThreadKey["environment-1:thread-1"] ?? null,
185 usePreviewMiniPlayerStore,
186 };
187});
188​
189vi.mock("~/rightPanelStore", () => ({
190 useRightPanelStore: {
191 getState: () => ({ close: mocks.closeRightPanel }),
192 },
193}));
194​
195vi.mock("~/components/ui/toast", () => ({
196 stackedThreadToast: vi.fn(),
197 toastManager: { add: vi.fn() },
198}));
199​
200vi.mock("./previewBridge", () => ({
201 previewBridge: {
202 navigate: mocks.navigate,
203 pickElement: mocks.pickElement,
204 pictureInPicture: {
205 open: mocks.openPictureInPicture,
206 close: mocks.closePictureInPicture,
207 },
208 },
209}));
210​
211vi.mock("./PreviewChromeRow", () => ({
212 PreviewChromeRow: (props: {
213 onSubmit: (url: string) => void;
214 onPickElement?: () => void;
215 onPictureInPicture?: () => void;
216 pictureInPicture?: boolean;
217 trailingActions?: {
218 props: { onNativePictureInPicture?: () => void };
219 };
220 }) => {
221 mocks.submittedUrl = props.onSubmit;
222 mocks.toggleAnnotation = props.onPickElement ?? null;
223 mocks.togglePictureInPicture = props.onPictureInPicture ?? null;
224 mocks.toggleNativePictureInPicture =
225 props.trailingActions?.props.onNativePictureInPicture ?? null;
226 mocks.pictureInPicturePressed = props.pictureInPicture ?? false;
227 return null;
228 },
229}));
230​
231vi.mock("./PreviewEmptyState", () => ({
232 PreviewEmptyState: (props: { onOpenUrl: (url: string) => void }) => {
233 mocks.emptyStateUrl = props.onOpenUrl;
234 return null;
235 },
236}));
237vi.mock("./PreviewMoreMenu", () => ({
238 PreviewMoreMenu: (props: { onNativePictureInPicture: () => void }) => {
239 mocks.toggleNativePictureInPicture = props.onNativePictureInPicture;
240 return null;
241 },
242}));
243vi.mock("./PreviewUnreachable", () => ({ PreviewUnreachable: () => null }));
244vi.mock("./ZoomIndicator", () => ({ ZoomIndicator: () => null }));
245vi.mock("./AgentBrowserCursor", () => ({ AgentBrowserCursor: () => null }));
246vi.mock("~/browser/BrowserSurfaceSlot", () => ({ BrowserSurfaceSlot: () => null }));
247vi.mock("./useLoadingProgress", () => ({ useLoadingProgress: () => 0 }));
248vi.mock("./usePreviewSession", () => ({ usePreviewSession: vi.fn() }));
249​
250import { PreviewView } from "./PreviewView";
251import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
252​
253const TEST_THREAD_REF = {
254 environmentId: EnvironmentId.make("environment-1"),
255 threadId: ThreadId.make("thread-1"),
256} as const;
257const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
258​
259describe("PreviewView navigation", () => {
260 beforeEach(() => {
261 mocks.navigate.mockClear();
262 mocks.rememberPreviewUrl.mockClear();
263 mocks.readPreparedConnection.mockClear();
264 mocks.submittedUrl = null;
265 mocks.emptyStateUrl = null;
266 mocks.togglePictureInPicture = null;
267 mocks.toggleNativePictureInPicture = null;
268 mocks.pictureInPicturePressed = false;
269 mocks.miniPlayerTabId = null;
270 mocks.openMiniPlayer.mockClear();
271 mocks.closeMiniPlayer.mockClear();
272 mocks.closeRightPanel.mockClear();
273 mocks.openPictureInPicture.mockClear();
274 mocks.closePictureInPicture.mockClear();
275 mocks.pickElement.mockReset();
276 mocks.previewAnnotationScreenshotFile.mockReset();
277 mocks.addPreviewAnnotation.mockClear();
278 mocks.addImage.mockClear();
279 mocks.toggleAnnotation = null;
280 mocks.pictureInPicture = false;
281 mocks.showEmptyState = false;
282 mocks.recordVisitForThread.mockClear();
283 });
284​
285 it.each([
286 [
287 "https://localhost:8000/dashboard?mode=test#top",
288 "https://localhost:8000/dashboard?mode=test#top",
289 ],
290 ["localhost:5173/app", "http://localhost:5173/app"],
291 ])("preserves a direct localhost URL in a WSL environment", async (submitted, expected) => {
292 renderToStaticMarkup(
293 <PreviewView
294 threadRef={{
295 environmentId: EnvironmentId.make("environment-1"),
296 threadId: ThreadId.make("thread-1"),
297 }}
298 tabId="tab-1"
299 visible
300 />,
301 );
302​
303 expect(mocks.submittedUrl).not.toBeNull();
304 mocks.submittedUrl?.(submitted);
305​
306 await vi.waitFor(() =>
307 expect(mocks.navigate).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID, expected),
308 );
309 expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
310 {
311 environmentId: "environment-1",
312 threadId: "thread-1",
313 },
314 expected,
315 );
316 });
317​
318 it("records a history visit with the normalized requested url on submit", async () => {
319 renderToStaticMarkup(
320 <PreviewView
321 threadRef={{
322 environmentId: EnvironmentId.make("environment-1"),
323 threadId: ThreadId.make("thread-1"),
324 }}
325 tabId="tab-1"
326 visible
327 />,
328 );
329​
330 mocks.submittedUrl?.("localhost:3000/admin");
331 await vi.waitFor(() => {
332 expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
333 expect.objectContaining({ threadId: expect.anything() }),
334 "http://localhost:3000/admin",
335 );
336 });
337 });
338​
339 it("maps an empty-state localhost server onto the WSL host", async () => {
340 mocks.showEmptyState = true;
341 renderToStaticMarkup(
342 <PreviewView
343 threadRef={{
344 environmentId: EnvironmentId.make("environment-1"),
345 threadId: ThreadId.make("thread-1"),
346 }}
347 tabId="tab-1"
348 visible
349 />,
350 );
351​
352 expect(mocks.emptyStateUrl).not.toBeNull();
353 mocks.emptyStateUrl?.("http://localhost:5173/app?mode=test#top");
354​
355 await vi.waitFor(() =>
356 expect(mocks.navigate).toHaveBeenCalledWith(
357 TEST_RUNTIME_TAB_ID,
358 "http://172.25.85.75:5173/app?mode=test#top",
359 ),
360 );
361 expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
362 {
363 environmentId: "environment-1",
364 threadId: "thread-1",
365 },
366 "http://172.25.85.75:5173/app?mode=test#top",
367 );
368 await vi.waitFor(() =>
369 expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
370 expect.objectContaining({ threadId: expect.anything() }),
371 "http://localhost:5173/app?mode=test#top",
372 ),
373 );
374 });
375​
376 it("opens and closes a thread-scoped floating preview for the active tab", async () => {
377 const props = {
378 threadRef: {
379 environmentId: EnvironmentId.make("environment-1"),
380 threadId: ThreadId.make("thread-1"),
381 },
382 tabId: "tab-1",
383 visible: true,
384 } as const;
385​
386 renderToStaticMarkup(<PreviewView {...props} />);
387 expect(mocks.pictureInPicturePressed).toBe(false);
388 mocks.togglePictureInPicture?.();
389 expect(mocks.openMiniPlayer).toHaveBeenCalledWith(props.threadRef, "tab-1");
390 expect(mocks.closeRightPanel).toHaveBeenCalledWith(props.threadRef);
391​
392 mocks.miniPlayerTabId = "tab-1";
393 renderToStaticMarkup(<PreviewView {...props} />);
394 expect(mocks.pictureInPicturePressed).toBe(true);
395 mocks.togglePictureInPicture?.();
396 expect(mocks.closeMiniPlayer).toHaveBeenCalledWith(props.threadRef);
397 });
398​
399 it("keeps the native preview window as a secondary action", async () => {
400 const props = {
401 threadRef: {
402 environmentId: EnvironmentId.make("environment-1"),
403 threadId: ThreadId.make("thread-1"),
404 },
405 tabId: "tab-1",
406 visible: true,
407 } as const;
408​
409 renderToStaticMarkup(<PreviewView {...props} />);
410 mocks.toggleNativePictureInPicture?.();
411 await vi.waitFor(() =>
412 expect(mocks.openPictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
413 );
414​
415 mocks.pictureInPicture = true;
416 renderToStaticMarkup(<PreviewView {...props} />);
417 mocks.toggleNativePictureInPicture?.();
418 await vi.waitFor(() =>
419 expect(mocks.closePictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
420 );
421 });
422​
423 it("forwards Cmd/Ctrl+Enter annotations to the composer send path", async () => {
424 const annotation = {
425 id: "annotation-1",
426 pageUrl: "https://example.com/dashboard",
427 pageTitle: "Dashboard",
428 comment: "Tighten this spacing",
429 elements: [],
430 regions: [],
431 strokes: [],
432 styleChanges: [],
433 screenshot: null,
434 createdAt: "2026-07-27T00:00:00.000Z",
435 };
436 const onSendAnnotation = vi.fn();
437 mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
438​
439 renderToStaticMarkup(
440 <PreviewView
441 threadRef={TEST_THREAD_REF}
442 tabId="tab-1"
443 visible
444 onSendAnnotation={onSendAnnotation}
445 />,
446 );
447 mocks.toggleAnnotation?.();
448​
449 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
450 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, annotation);
451 });
452​
453 it("still sends when screenshot attachment conversion fails", async () => {
454 const annotation = {
455 id: "annotation-2",
456 pageUrl: "https://example.com/dashboard",
457 pageTitle: "Dashboard",
458 comment: "Tighten this spacing",
459 elements: [],
460 regions: [],
461 strokes: [],
462 styleChanges: [],
463 screenshot: {
464 dataUrl: "data:image/png;base64,c2NyZWVuc2hvdA==",
465 width: 10,
466 height: 10,
467 cropRect: { x: 0, y: 0, width: 10, height: 10 },
468 },
469 createdAt: "2026-07-27T00:00:00.000Z",
470 };
471 const onSendAnnotation = vi.fn();
472 mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
473 mocks.previewAnnotationScreenshotFile.mockRejectedValue(new Error("conversion failed"));
474​
475 renderToStaticMarkup(
476 <PreviewView
477 threadRef={TEST_THREAD_REF}
478 tabId="tab-1"
479 visible
480 onSendAnnotation={onSendAnnotation}
481 />,
482 );
483 mocks.toggleAnnotation?.();
484​
485 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
486 expect(mocks.addImage).not.toHaveBeenCalled();
487 });
488});