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