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