Open History to see the last commit
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 { type ComponentProps } from "react";
11import { describe, expect, it, vi } from "vite-plus/test";
12import { page, userEvent } from "vite-plus/test/browser";
13
14import "~/index.css";
15import { act, render } from "../../../test/render";
16
17import type { PreviewableServer } from "./useDiscoveredLocalServers";
18
19const mocks = vi.hoisted(() => ({
20 navigate: vi.fn(async (_tabId: string, _url: string): Promise<void> => undefined),
21 rememberPreviewUrl: vi.fn(),
22 readPreparedConnection: vi.fn(() => ({ httpBaseUrl: "http://172.25.85.75:3773" })),
23 readEnvironmentScope: vi.fn((_environmentId?: unknown, _scope?: unknown) => true),
24 setAnnotationSendEnabled: vi.fn(async (_tabId: string, _enabled: boolean): Promise<void> => {}),
25 cancelPickElement: vi.fn(async (_tabId: string) => undefined),
26 openPictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
27 closePictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
28 pickElement: vi.fn(),
29 addPreviewAnnotation: vi.fn(),
30 addImage: vi.fn(),
31 pictureInPicture: false,
32 showEmptyState: false,
33 idleServerTab: false,
34 loading: false,
35 nativeServerTab: false,
36 streamedServerTab: false,
37 serverEpoch: null as string | null,
38 servers: [] as PreviewableServer[],
39 recordingTabIds: new Set<string>(),
40 recordingRuntimeTabId: null as string | null,
41 recordVisitForThread: vi.fn(),
42}));
43
44const STUB_BROWSER_DEFAULTS = {
45 viewport: FILL_PREVIEW_VIEWPORT,
46 zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
47 appearance: DEFAULT_PREVIEW_APPEARANCE,
48 autoShowFloatingPreview: true,
49 profiles: BUILT_IN_BROWSER_PROFILES,
50 profileId: DEFAULT_BROWSER_PROFILE_ID,
51};
52
53// The desktop bridge only exists inside Electron; the view reads it once at import.
54vi.mock(import("./previewBridge"), async (original) => ({
55 ...(await original()),
56 previewBridge: {
57 navigate: mocks.navigate,
58 pickElement: mocks.pickElement,
59 annotationVoice: { onEvent: () => () => {}, update: async () => {} },
60 setAnnotationSendEnabled: mocks.setAnnotationSendEnabled,
61 cancelPickElement: mocks.cancelPickElement,
62 refresh: vi.fn(async () => undefined),
63 goBack: vi.fn(async () => undefined),
64 goForward: vi.fn(async () => undefined),
65 hardReload: vi.fn(async () => undefined),
66 openDevTools: vi.fn(async () => undefined),
67 setColorScheme: vi.fn(async () => undefined),
68 zoomIn: vi.fn(async () => undefined),
69 zoomOut: vi.fn(async () => undefined),
70 resetZoom: vi.fn(async () => undefined),
71 clearCookies: vi.fn(async () => undefined),
72 clearCache: vi.fn(async () => undefined),
73 pictureInPicture: {
74 open: mocks.openPictureInPicture,
75 close: mocks.closePictureInPicture,
76 },
77 findInPage: vi.fn(async () => undefined),
78 stopFindInPage: vi.fn(async () => undefined),
79 onFindResult: vi.fn(() => () => undefined),
80 } as never,
81}));
82vi.mock(import("~/browserHistoryStore"), async (original) => ({
83 ...(await original()),
84 recordVisitForThread: mocks.recordVisitForThread,
85}));
86vi.mock(import("~/state/session"), async (original) => ({
87 ...(await original()),
88 readPreparedConnection: mocks.readPreparedConnection as never,
89 readEnvironmentScope: mocks.readEnvironmentScope,
90 useEnvironmentScope: mocks.readEnvironmentScope,
91}));
92vi.mock(import("~/browser/browserDefaults"), async (original) => ({
93 ...(await original()),
94 useBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
95 getBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
96}));
97vi.mock(import("~/previewStateStore"), async (original) => ({
98 ...(await original()),
99 rememberPreviewUrl: mocks.rememberPreviewUrl,
100 useThreadPreviewState: (() => ({
101 activeTabId: "tab-1",
102 serverEpoch: mocks.serverEpoch,
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 : mocks.idleServerTab
121 ? {
122 "tab-1": {
123 threadId: "thread-1",
124 tabId: "tab-1",
125 runtime: "server",
126 navStatus: { _tag: "Idle" },
127 canGoBack: false,
128 canGoForward: false,
129 updatedAt: "2026-07-13T00:00:00.000Z",
130 },
131 }
132 : {
133 "tab-1": {
134 threadId: "thread-1",
135 tabId: "tab-1",
136 runtime: mocks.nativeServerTab || mocks.streamedServerTab ? "server" : "desktop",
137 navStatus: { _tag: "Success", url: "http://example.com/", title: "Example" },
138 canGoBack: false,
139 canGoForward: false,
140 updatedAt: "2026-07-13T00:00:00.000Z",
141 },
142 },
143 })) as never,
144}));
145vi.mock(import("~/state/environments"), async (original) => ({
146 ...(await original()),
147 useEnvironment: (() => ({ label: "WSL" })) as never,
148 useEnvironmentHttpBaseUrl: () => "http://172.25.85.75:3773",
149 usePrimaryEnvironmentId: () => null,
150}));
151vi.mock(import("~/browser/browserRecording"), async (original) => ({
152 ...(await original()),
153 findActiveBrowserRecordingRuntimeTabId: () => mocks.recordingRuntimeTabId,
154 useActiveBrowserRecordingTabIds: () => mocks.recordingTabIds,
155}));
156vi.mock(import("./useDiscoveredLocalServers"), async (original) => ({
157 ...(await original()),
158 useDiscoveredLocalServers: () => mocks.servers,
159}));
160vi.mock(import("./usePreviewSession"), async (original) => ({
161 ...(await original()),
162 usePreviewSession: () => {},
163}));
164
165vi.mock(import("~/browser/previewRuntime"), async (original) => ({
166 ...(await original()),
167 useRendersServerTabNatively: () => mocks.nativeServerTab,
168}));
169
170vi.mock(import("~/browser/browserViewportActions"), { spy: true });
171// The real surface opens a preview stream to the server; only its box matters here.
172vi.mock(import("~/browser/ServerBrowserSurface"), async (original) => ({
173 ...(await original()),
174 ServerBrowserSurface: ((props: { className?: string }) => (
175 <div data-testid="server-browser-surface" className={props.className} />
176 )) as never,
177}));
178
179import { useComposerDraftStore } from "~/composerDraftStore";
180import { commitBrowserViewportChange } from "~/browser/browserViewportActions";
181import { resolveResponsiveBrowserViewportSize } from "~/browser/browserViewportLayout";
182import { useBrowserPointerStore } from "~/browser/browserPointerStore";
183import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
184import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
185import { dispatchPreviewAction } from "./previewActionBus";
186import { PreviewView } from "./PreviewView";
187import { ToastProvider } from "~/components/ui/toast";
188
189const TEST_THREAD_REF = {
190 environmentId: EnvironmentId.make("environment-1"),
191 threadId: ThreadId.make("thread-1"),
192} as const;
193const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
194
195function view(onSendAnnotation?: ComponentProps<typeof PreviewView>["onSendAnnotation"]) {
196 return (
197 <PreviewView
198 threadRef={TEST_THREAD_REF}
199 tabId="tab-1"
200 visible
201 {...(onSendAnnotation ? { onSendAnnotation } : {})}
202 />
203 );
204}
205
206function annotation(id: string, screenshot: unknown = null) {
207 return {
208 id,
209 pageUrl: "https://example.com/dashboard",
210 pageTitle: "Dashboard",
211 comment: "Tighten this spacing",
212 elements: [],
213 regions: [],
214 strokes: [],
215 styleChanges: [],
216 screenshot,
217 createdAt: "2026-07-27T00:00:00.000Z",
218 };
219}
220
221// The mocked modules and stores are shared by the whole file, so every test starts by
222// resetting them.
223function setup() {
224 vi.clearAllMocks();
225 mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
226 mocks.setAnnotationSendEnabled.mockReset().mockResolvedValue(undefined);
227 mocks.pickElement.mockReset();
228 mocks.pictureInPicture = false;
229 mocks.showEmptyState = false;
230 mocks.idleServerTab = false;
231 mocks.loading = false;
232 mocks.nativeServerTab = false;
233 mocks.streamedServerTab = false;
234 mocks.serverEpoch = null;
235 mocks.servers = [];
236 mocks.recordingTabIds = new Set();
237 mocks.recordingRuntimeTabId = null;
238 useComposerDraftStore.setState({
239 addPreviewAnnotation: mocks.addPreviewAnnotation,
240 addImage: mocks.addImage,
241 });
242 usePreviewMiniPlayerStore.setState({ byThreadKey: {} });
243 useBrowserPointerStore.setState({ byTabId: {} });
244}
245
246describe("PreviewView", () => {
247 it.each(["mailto:alice@example.com", "http://"])(
248 "reports rejected address %s without navigating or recording it",
249 async (address) => {
250 setup();
251 await using _screen = await render(<ToastProvider timeout={0}>{view()}</ToastProvider>);
252 const input = page.getByPlaceholder("Search or enter URL");
253 await input.fill(address);
254 await userEvent.keyboard("{Enter}");
255
256 await expect.element(page.getByText("Could not open this address")).toBeVisible();
257 await expect.element(page.getByText("Enter an http or https URL.")).toBeVisible();
258 expect(mocks.navigate).not.toHaveBeenCalled();
259 expect(mocks.recordVisitForThread).not.toHaveBeenCalled();
260 await userEvent.click(page.getByRole("button", { name: "Dismiss notification" }));
261 },
262 );
263
264 it("keeps the address in the bar when Enter commits an IME composition", async () => {
265 setup();
266 await using _screen = await render(view());
267 const input = page.getByPlaceholder("Search or enter URL");
268 await input.fill("https://example.com/pinyin");
269
270 const enter = new KeyboardEvent("keydown", {
271 key: "Enter",
272 code: "Enter",
273 isComposing: true,
274 bubbles: true,
275 cancelable: true,
276 });
277 Object.defineProperty(enter, "keyCode", { value: 229 });
278 act(() => {
279 input.element().dispatchEvent(enter);
280 });
281
282 await expect.element(input).toHaveFocus();
283 await expect.element(input).toHaveValue("https://example.com/pinyin");
284 expect(mocks.navigate).not.toHaveBeenCalled();
285 expect(enter.defaultPrevented).toBe(true);
286 });
287
288 it("retains the annotation locally when its own environment loses access during capture", async () => {
289 setup();
290 const picked = annotation("annotation-revoked");
291 const onSendAnnotation = vi.fn();
292 let submitPick: (() => void) | undefined;
293 mocks.pickElement.mockImplementationOnce(
294 () =>
295 new Promise((resolve) => {
296 submitPick = () => resolve({ annotation: picked, submission: "send" });
297 }),
298 );
299 await using screen = await render(view(onSendAnnotation));
300 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
301 await vi.waitFor(() => expect(submitPick).toBeDefined());
302 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
303
304 mocks.readEnvironmentScope.mockImplementation(
305 (environmentId?: unknown) => environmentId !== TEST_THREAD_REF.environmentId,
306 );
307 await screen.rerender(view(onSendAnnotation));
308 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, false);
309 await act(async () => submitPick!());
310 await vi.waitFor(() =>
311 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, picked),
312 );
313 expect(onSendAnnotation).not.toHaveBeenCalled();
314
315 mocks.readEnvironmentScope.mockReturnValue(true);
316 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
317 await screen.rerender(view(onSendAnnotation));
318 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
319 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
320 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
321 });
322
323 it("still sends annotation text when the picked element's crop is malformed", async () => {
324 setup();
325 const picked = annotation("annotation-2", {
326 dataUrl: "data:image/png;base64,%%%",
327 width: 10,
328 height: 10,
329 cropRect: { x: 0, y: 0, width: 10, height: 10 },
330 });
331 const onSendAnnotation = vi.fn();
332 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
333 await using _screen = await render(view(onSendAnnotation));
334 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
335
336 const sent = { ...picked, screenshot: null };
337 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(sent, null));
338 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, sent);
339 expect(mocks.addImage).not.toHaveBeenCalled();
340 });
341
342 it("lets the pointer reach a local server card above an idle server-rendered tab", async () => {
343 setup();
344 mocks.idleServerTab = true;
345 mocks.servers = [
346 {
347 host: "localhost",
348 port: 8081,
349 url: "http://localhost:8081/",
350 requestedUrl: "http://localhost:8081/",
351 processName: "python3",
352 pid: 4242,
353 terminal: null,
354 source: "scanner",
355 },
356 ];
357 await using _screen = await render(<ToastProvider timeout={0}>{view()}</ToastProvider>);
358 const card = page.getByRole("button", { name: /localhost:8081/ });
359 await expect.element(card).toBeVisible();
360
361 const rect = card.element().getBoundingClientRect();
362 const hit = document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2);
363 expect(card.element().contains(hit)).toBe(true);
364 });
365
366 it("sizes the first device viewport of a streamed tab to its panel", async () => {
367 setup();
368 mocks.streamedServerTab = true;
369 await using _screen = await render(<ToastProvider timeout={0}>{view()}</ToastProvider>);
370 const surface = page.getByTestId("server-browser-surface");
371 await expect.element(surface).toBeInTheDocument();
372 const rect = surface.element().getBoundingClientRect();
373
374 await userEvent.click(page.getByRole("button", { name: "Preview menu" }));
375 await userEvent.click(page.getByRole("menuitem", { name: "Show device toolbar" }));
376
377 expect(commitBrowserViewportChange).toHaveBeenCalledWith(expect.anything(), {
378 _tag: "freeform",
379 ...resolveResponsiveBrowserViewportSize(rect, 1),
380 });
381 });
382
383 it("focuses and selects the address from forwarded desktop actions only while visible", async () => {
384 setup();
385 using stack = new DisposableStack();
386 const previousBridge = window.desktopBridge;
387 stack.defer(() => {
388 if (previousBridge) window.desktopBridge = previousBridge;
389 else delete window.desktopBridge;
390 });
391 const listeners = new Set<(action: string) => void>();
392 window.desktopBridge = {
393 getWindowZoomFactor: () => 1,
394 onMenuAction: (listener: (action: string) => void) => {
395 listeners.add(listener);
396 return () => {
397 listeners.delete(listener);
398 };
399 },
400 } as NonNullable<typeof window.desktopBridge>;
401 await using screen = await render(view());
402 const address = page.getByRole("textbox");
403 const input = address.element() as HTMLInputElement;
404 const forward = () =>
405 act(() => {
406 listeners.forEach((listener) => listener("preview.focusUrl"));
407 });
408
409 await forward();
410 await expect.element(address).toHaveFocus();
411 expect(input.selectionStart).toBe(0);
412 expect(input.selectionEnd).toBe(input.value.length);
413 await act(() => input.blur());
414 await forward();
415 await expect.element(address).toHaveFocus();
416
417 await act(() => input.blur());
418 await screen.rerender(
419 <PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible={false} />,
420 );
421 await forward();
422 await expect.element(address).not.toHaveFocus();
423 expect(listeners.size).toBe(0);
424 });
425
426 it("focuses the address bar each time the focus-url shortcut fires", async () => {
427 setup();
428 await using _screen = await render(view());
429 const address = page.getByRole("textbox");
430
431 act(() => dispatchPreviewAction("focus-url"));
432 await expect.element(address).toHaveFocus();
433
434 (address.element() as HTMLInputElement).blur();
435 await expect.element(address).not.toHaveFocus();
436 act(() => dispatchPreviewAction("focus-url"));
437 await expect.element(address).toHaveFocus();
438 });
439
440 it("does not reopen find when the user returns to a tab they left with find open", async () => {
441 setup();
442 const tabView = (tabId: string) => (
443 <PreviewView threadRef={TEST_THREAD_REF} tabId={tabId} visible />
444 );
445 await using screen = await render(tabView("tab-1"));
446 const findBar = page.getByRole("search", { name: "Find in page" });
447
448 act(() => dispatchPreviewAction("find"));
449 await expect.element(findBar).toBeInTheDocument();
450
451 await screen.rerender(tabView("tab-2"));
452 await expect.element(findBar).not.toBeInTheDocument();
453 await screen.rerender(tabView("tab-1"));
454 await expect.element(findBar).not.toBeInTheDocument();
455 });
456});