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 idleDesktopTab: false,
35 idleDesktopOverlay: false,
36 loading: false,
37 nativeServerTab: false,
38 streamedServerTab: false,
39 serverEpoch: null as string | null,
40 servers: [] as PreviewableServer[],
41 recordingTabIds: new Set<string>(),
42 recordingRuntimeTabId: null as string | null,
43 recordVisitForThread: vi.fn(),
44 captureScreenshot: vi.fn(),
45 stopBrowserRecording: vi.fn(),
46 readArtifact: vi.fn(async (_path: string) => new Uint8Array([1, 2, 3])),
47}));
48
49const STUB_BROWSER_DEFAULTS = {
50 viewport: FILL_PREVIEW_VIEWPORT,
51 zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
52 appearance: DEFAULT_PREVIEW_APPEARANCE,
53 autoShowFloatingPreview: true,
54 profiles: BUILT_IN_BROWSER_PROFILES,
55 profileId: DEFAULT_BROWSER_PROFILE_ID,
56};
57
58// The desktop bridge only exists inside Electron; the view reads it once at import.
59vi.mock(import("./previewBridge"), async (original) => ({
60 ...(await original()),
61 previewBridge: {
62 navigate: mocks.navigate,
63 pickElement: mocks.pickElement,
64 captureScreenshot: mocks.captureScreenshot,
65 readArtifact: mocks.readArtifact,
66 revealArtifact: vi.fn(async () => undefined),
67 annotationVoice: { onEvent: () => () => {}, update: async () => {} },
68 setAnnotationSendEnabled: mocks.setAnnotationSendEnabled,
69 cancelPickElement: mocks.cancelPickElement,
70 refresh: vi.fn(async () => undefined),
71 goBack: vi.fn(async () => undefined),
72 goForward: vi.fn(async () => undefined),
73 hardReload: vi.fn(async () => undefined),
74 openDevTools: vi.fn(async () => undefined),
75 setColorScheme: vi.fn(async () => undefined),
76 zoomIn: vi.fn(async () => undefined),
77 zoomOut: vi.fn(async () => undefined),
78 resetZoom: vi.fn(async () => undefined),
79 clearCookies: vi.fn(async () => undefined),
80 clearCache: vi.fn(async () => undefined),
81 pictureInPicture: {
82 open: mocks.openPictureInPicture,
83 close: mocks.closePictureInPicture,
84 },
85 findInPage: vi.fn(async () => undefined),
86 stopFindInPage: vi.fn(async () => undefined),
87 onFindResult: vi.fn(() => () => undefined),
88 } as never,
89}));
90vi.mock(import("~/browserHistoryStore"), async (original) => ({
91 ...(await original()),
92 recordVisitForThread: mocks.recordVisitForThread,
93}));
94vi.mock(import("~/state/session"), async (original) => ({
95 ...(await original()),
96 readPreparedConnection: mocks.readPreparedConnection as never,
97 readEnvironmentScope: mocks.readEnvironmentScope,
98 useEnvironmentScope: mocks.readEnvironmentScope,
99}));
100vi.mock(import("~/browser/browserDefaults"), async (original) => ({
101 ...(await original()),
102 useBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
103 getBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
104}));
105vi.mock(import("~/previewStateStore"), async (original) => ({
106 ...(await original()),
107 rememberPreviewUrl: mocks.rememberPreviewUrl,
108 useThreadPreviewState: (() => ({
109 activeTabId: "tab-1",
110 serverEpoch: mocks.serverEpoch,
111 desktopByTabId: {
112 "tab-1": {
113 hasWebContents: true,
114 navStatus: mocks.idleDesktopOverlay
115 ? { _tag: "Idle" }
116 : { _tag: "Success", url: "http://example.com/", title: "Example" },
117 canGoBack: false,
118 canGoForward: false,
119 loading: mocks.loading,
120 zoomFactor: 1,
121 pictureInPicture: mocks.pictureInPicture,
122 colorScheme: "system",
123 audioMuted: false,
124 audible: false,
125 controller: "none",
126 },
127 },
128 recentlySeenUrls: [],
129 sessions: mocks.showEmptyState
130 ? {}
131 : mocks.idleServerTab || mocks.idleDesktopTab
132 ? {
133 "tab-1": {
134 threadId: "thread-1",
135 tabId: "tab-1",
136 runtime: mocks.idleDesktopTab ? "desktop" : "server",
137 navStatus: { _tag: "Idle" },
138 canGoBack: false,
139 canGoForward: false,
140 updatedAt: "2026-07-13T00:00:00.000Z",
141 },
142 }
143 : {
144 "tab-1": {
145 threadId: "thread-1",
146 tabId: "tab-1",
147 runtime: mocks.nativeServerTab || mocks.streamedServerTab ? "server" : "desktop",
148 navStatus: { _tag: "Success", url: "http://example.com/", title: "Example" },
149 canGoBack: false,
150 canGoForward: false,
151 updatedAt: "2026-07-13T00:00:00.000Z",
152 },
153 },
154 })) as never,
155}));
156vi.mock(import("~/state/environments"), async (original) => ({
157 ...(await original()),
158 useEnvironment: (() => ({ label: "WSL" })) as never,
159 useEnvironmentHttpBaseUrl: () => "http://172.25.85.75:3773",
160 usePrimaryEnvironmentId: () => null,
161}));
162vi.mock(import("~/browser/browserRecording"), async (original) => ({
163 ...(await original()),
164 findActiveBrowserRecordingRuntimeTabId: () => mocks.recordingRuntimeTabId,
165 useActiveBrowserRecordingTabIds: () => mocks.recordingTabIds,
166 stopBrowserRecording: mocks.stopBrowserRecording,
167}));
168vi.mock(import("./useDiscoveredLocalServers"), async (original) => ({
169 ...(await original()),
170 useDiscoveredLocalServers: () => mocks.servers,
171}));
172vi.mock(import("./usePreviewSession"), async (original) => ({
173 ...(await original()),
174 usePreviewSession: () => {},
175}));
176
177// Capture toasts belong to the capture's thread and only render while it is open.
178vi.mock(import("~/hooks/useThreadRouteTarget"), async (original) => ({
179 ...(await original()),
180 useThreadRouteTarget: () => ({
181 kind: "server" as const,
182 threadRef: { environmentId: "environment-1", threadId: "thread-1" } as never,
183 }),
184}));
185
186vi.mock(import("~/browser/previewRuntime"), async (original) => ({
187 ...(await original()),
188 useRendersServerTabNatively: () => mocks.nativeServerTab,
189}));
190
191vi.mock(import("~/browser/browserViewportActions"), { spy: true });
192// The real surface opens a preview stream to the server; only its box matters here.
193vi.mock(import("~/browser/ServerBrowserSurface"), async (original) => ({
194 ...(await original()),
195 ServerBrowserSurface: ((props: { className?: string }) => (
196 <div data-testid="server-browser-surface" className={props.className} />
197 )) as never,
198}));
199
200import { useComposerDraftStore } from "~/composerDraftStore";
201import { commitBrowserViewportChange } from "~/browser/browserViewportActions";
202import { resolveResponsiveBrowserViewportSize } from "~/browser/browserViewportLayout";
203import { useBrowserPointerStore } from "~/browser/browserPointerStore";
204import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
205import {
206 browserMiniPlayerSource,
207 selectThreadPreviewMiniPlayer,
208 usePreviewMiniPlayerStore,
209} from "~/previewMiniPlayerStore";
210import { dispatchPreviewAction } from "./previewActionBus";
211import { PreviewView } from "./PreviewView";
212import { ToastProvider } from "~/components/ui/toast";
213import { ComposerHandleContext } from "~/composerHandleContext";
214import type { ChatComposerHandle } from "../chat/ChatComposer";
215
216const TEST_THREAD_REF = {
217 environmentId: EnvironmentId.make("environment-1"),
218 threadId: ThreadId.make("thread-1"),
219} as const;
220const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
221
222function view(onSendAnnotation?: ComponentProps<typeof PreviewView>["onSendAnnotation"]) {
223 return (
224 <PreviewView
225 threadRef={TEST_THREAD_REF}
226 tabId="tab-1"
227 visible
228 {...(onSendAnnotation ? { onSendAnnotation } : {})}
229 />
230 );
231}
232
233function annotation(id: string, screenshot: unknown = null) {
234 return {
235 id,
236 pageUrl: "https://example.com/dashboard",
237 pageTitle: "Dashboard",
238 comment: "Tighten this spacing",
239 elements: [],
240 regions: [],
241 strokes: [],
242 styleChanges: [],
243 screenshot,
244 createdAt: "2026-07-27T00:00:00.000Z",
245 };
246}
247
248// The mocked modules and stores are shared by the whole file, so every test starts by
249// resetting them.
250function setup() {
251 vi.clearAllMocks();
252 mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
253 mocks.setAnnotationSendEnabled.mockReset().mockResolvedValue(undefined);
254 mocks.pickElement.mockReset();
255 mocks.pictureInPicture = false;
256 mocks.showEmptyState = false;
257 mocks.idleServerTab = false;
258 mocks.idleDesktopTab = false;
259 mocks.idleDesktopOverlay = false;
260 mocks.loading = false;
261 mocks.nativeServerTab = false;
262 mocks.streamedServerTab = false;
263 mocks.serverEpoch = null;
264 mocks.servers = [];
265 mocks.recordingTabIds = new Set();
266 mocks.recordingRuntimeTabId = null;
267 useComposerDraftStore.setState({
268 addPreviewAnnotation: mocks.addPreviewAnnotation,
269 addImage: mocks.addImage,
270 });
271 usePreviewMiniPlayerStore.setState({ byThreadKey: {} });
272 useBrowserPointerStore.setState({ byTabId: {} });
273}
274
275describe("PreviewView", () => {
276 it.each(["mailto:alice@example.com", "http://"])(
277 "reports rejected address %s without navigating or recording it",
278 async (address) => {
279 setup();
280 await using _screen = await render(<ToastProvider timeout={0}>{view()}</ToastProvider>);
281 const input = page.getByPlaceholder("Search or enter URL");
282 await input.fill(address);
283 await userEvent.keyboard("{Enter}");
284
285 await expect.element(page.getByText("Could not open this address")).toBeVisible();
286 await expect.element(page.getByText("Enter an http or https URL.")).toBeVisible();
287 expect(mocks.navigate).not.toHaveBeenCalled();
288 expect(mocks.recordVisitForThread).not.toHaveBeenCalled();
289 await userEvent.click(page.getByRole("button", { name: "Dismiss notification" }));
290 },
291 );
292
293 const savedCapture = (kind: "screenshot" | "recording", sizeBytes = 3) => {
294 const artifact =
295 kind === "screenshot"
296 ? { id: "shot", path: "/artifacts/shot.png", mimeType: "image/png", sizeBytes }
297 : { id: "clip", path: "/artifacts/clip.webm", mimeType: "video/webm", sizeBytes };
298 if (kind === "recording") {
299 mocks.recordingRuntimeTabId = TEST_RUNTIME_TAB_ID;
300 mocks.stopBrowserRecording.mockResolvedValue(artifact);
301 } else {
302 mocks.captureScreenshot.mockResolvedValue(artifact);
303 }
304 return artifact;
305 };
306
307 const renderWithComposer = (handle: Partial<ChatComposerHandle>) =>
308 render(
309 <ComposerHandleContext value={{ current: handle as ChatComposerHandle }}>
310 <ToastProvider timeout={0}>{view()}</ToastProvider>
311 </ComposerHandleContext>,
312 );
313
314 it.each([
315 { kind: "screenshot", capture: "Capture screenshot", saved: "Screenshot saved" },
316 { kind: "recording", capture: "Stop recording", saved: "Recording saved" },
317 ] as const)("stages a saved $kind in its chat from Attach to chat", async (capture) => {
318 setup();
319 const artifact = savedCapture(capture.kind);
320 const attachFilesToThread = vi.fn(async (_threadRef: unknown, _files: File[]) => true);
321 const attachmentLimitFor = vi.fn(() => ({ maxBytes: 1024 }));
322 await using _screen = await renderWithComposer({ attachFilesToThread, attachmentLimitFor });
323 await userEvent.click(page.getByRole("button", { name: capture.capture }));
324 await expect.element(page.getByText(capture.saved)).toBeVisible();
325 await expect.element(page.getByRole("button", { name: "Copy path" })).toBeVisible();
326 await expect.element(page.getByRole("button", { name: "Copy image" })).not.toBeInTheDocument();
327 await userEvent.click(page.getByRole("button", { name: "Attach to chat" }));
328
329 await vi.waitFor(() => expect(attachFilesToThread).toHaveBeenCalledOnce());
330 expect(attachmentLimitFor).toHaveBeenCalledWith(TEST_THREAD_REF, {
331 name: artifact.path.slice(11),
332 type: artifact.mimeType,
333 });
334 expect(mocks.readArtifact).toHaveBeenCalledWith(artifact.id, 1024);
335 const [threadRef, [file]] = attachFilesToThread.mock.calls[0]!;
336 expect(threadRef).toBe(TEST_THREAD_REF);
337 expect(file).toMatchObject({ name: artifact.path.slice(11), type: artifact.mimeType, size: 3 });
338
339 attachmentLimitFor.mockReturnValue(null as never);
340 await userEvent.click(page.getByRole("button", { name: "Attach to chat" }));
341 await expect
342 .element(page.getByText("Open the chat this capture came from and try again."))
343 .toBeVisible();
344 expect(mocks.readArtifact).toHaveBeenCalledOnce();
345 });
346
347 it("reports a capture the chat's intake declines, and keeps that result past Copy path", async () => {
348 setup();
349 savedCapture("recording");
350 await using _screen = await renderWithComposer({
351 attachFilesToThread: async () => false,
352 attachmentLimitFor: () => ({ maxBytes: 1024 }),
353 });
354 using writeText = vi
355 .spyOn(navigator.clipboard, "writeText")
356 .mockRejectedValueOnce(new Error("Clipboard write denied."))
357 .mockResolvedValue(undefined);
358 await userEvent.click(page.getByRole("button", { name: "Stop recording" }));
359 await userEvent.click(page.getByRole("button", { name: "Attach to chat" }));
360
361 await expect
362 .element(page.getByText("The chat isn't ready to accept input right now."))
363 .toBeVisible();
364 await expect
365 .element(page.getByText("Open the chat this capture came from and try again."))
366 .not.toBeInTheDocument();
367 // A failed copy is reported on its own; the attach result stays.
368 await userEvent.click(page.getByRole("button", { name: "Copy path" }));
369 await expect.element(page.getByText("Unable to copy recording path")).toBeVisible();
370 await expect.element(page.getByText("Clipboard write denied.")).toBeVisible();
371 await expect
372 .element(page.getByText("The chat isn't ready to accept input right now."))
373 .toBeVisible();
374
375 await userEvent.click(page.getByRole("button", { name: "Copy path" }));
376 await expect.element(page.getByRole("button", { name: "Copied!" })).toBeVisible();
377 await expect
378 .element(page.getByText("The chat isn't ready to accept input right now."))
379 .toBeVisible();
380 expect(writeText).toHaveBeenCalledWith("/artifacts/clip.webm");
381 });
382
383 it("rejects a recording over the chat's file limit without reading it", async () => {
384 setup();
385 savedCapture("recording", 2 * 1024 * 1024);
386 const attachFilesToThread = vi.fn(async () => true);
387 await using _screen = await renderWithComposer({
388 attachFilesToThread,
389 attachmentLimitFor: () => ({ maxBytes: 1024 * 1024 }),
390 });
391 await userEvent.click(page.getByRole("button", { name: "Stop recording" }));
392 await userEvent.click(page.getByRole("button", { name: "Attach to chat" }));
393
394 await expect.element(page.getByText("Unable to add to chat")).toBeVisible();
395 await expect.element(page.getByText(/clip\.webm.*1 MB/)).toBeVisible();
396 await expect.element(page.getByRole("button", { name: "Copy path" })).toBeEnabled();
397 // The label names the platform's file manager ("Reveal in Finder", "Reveal in Files", ...).
398 await expect.element(page.getByRole("button", { name: /^Reveal in / })).toBeEnabled();
399 expect(mocks.readArtifact).not.toHaveBeenCalled();
400 expect(attachFilesToThread).not.toHaveBeenCalled();
401 });
402
403 it("floats in one click while the panel shows a tab that was floated before", async () => {
404 setup();
405 usePreviewMiniPlayerStore.getState().open(TEST_THREAD_REF, browserMiniPlayerSource("tab-1"));
406 await using _screen = await render(view());
407 const float = page.getByRole("button", { name: "Float preview over chat" });
408 await expect.element(float).toHaveAttribute("aria-pressed", "false");
409 await userEvent.click(float);
410
411 expect(
412 selectThreadPreviewMiniPlayer(
413 usePreviewMiniPlayerStore.getState().byThreadKey,
414 TEST_THREAD_REF,
415 )?.source,
416 ).toEqual(browserMiniPlayerSource("tab-1"));
417 });
418
419 it("shows a desktop navigation before its backend status echo arrives", async () => {
420 setup();
421 mocks.idleDesktopTab = true;
422 await using _screen = await render(view());
423 await expect
424 .element(page.getByPlaceholder("Search or enter URL"))
425 .toHaveValue("http://example.com/");
426 await expect.element(page.getByText("No preview yet")).not.toBeInTheDocument();
427 await expect.element(page.getByRole("button", { name: "Annotate preview" })).toBeVisible();
428 });
429
430 it("keeps the server navigation while the new desktop tab is still idle", async () => {
431 setup();
432 mocks.idleDesktopOverlay = true;
433 await using _screen = await render(view());
434 await expect
435 .element(page.getByPlaceholder("Search or enter URL"))
436 .toHaveValue("http://example.com/");
437 await expect.element(page.getByText("No preview yet")).not.toBeInTheDocument();
438 });
439
440 it("keeps the address in the bar when Enter commits an IME composition", async () => {
441 setup();
442 await using _screen = await render(view());
443 const input = page.getByPlaceholder("Search or enter URL");
444 await input.fill("https://example.com/pinyin");
445
446 const enter = new KeyboardEvent("keydown", {
447 key: "Enter",
448 code: "Enter",
449 isComposing: true,
450 bubbles: true,
451 cancelable: true,
452 });
453 Object.defineProperty(enter, "keyCode", { value: 229 });
454 act(() => {
455 input.element().dispatchEvent(enter);
456 });
457
458 await expect.element(input).toHaveFocus();
459 await expect.element(input).toHaveValue("https://example.com/pinyin");
460 expect(mocks.navigate).not.toHaveBeenCalled();
461 expect(enter.defaultPrevented).toBe(true);
462 });
463
464 it("retains the annotation locally when its own environment loses access during capture", async () => {
465 setup();
466 const picked = annotation("annotation-revoked");
467 const onSendAnnotation = vi.fn();
468 let submitPick: (() => void) | undefined;
469 mocks.pickElement.mockImplementationOnce(
470 () =>
471 new Promise((resolve) => {
472 submitPick = () => resolve({ annotation: picked, submission: "send" });
473 }),
474 );
475 await using screen = await render(view(onSendAnnotation));
476 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
477 await vi.waitFor(() => expect(submitPick).toBeDefined());
478 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
479
480 mocks.readEnvironmentScope.mockImplementation(
481 (environmentId?: unknown) => environmentId !== TEST_THREAD_REF.environmentId,
482 );
483 await screen.rerender(view(onSendAnnotation));
484 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, false);
485 await act(async () => submitPick!());
486 await vi.waitFor(() =>
487 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, picked),
488 );
489 expect(onSendAnnotation).not.toHaveBeenCalled();
490
491 mocks.readEnvironmentScope.mockReturnValue(true);
492 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
493 await screen.rerender(view(onSendAnnotation));
494 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
495 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
496 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
497 });
498
499 it("still sends annotation text when the picked element's crop is malformed", async () => {
500 setup();
501 const picked = annotation("annotation-2", {
502 dataUrl: "data:image/png;base64,%%%",
503 width: 10,
504 height: 10,
505 cropRect: { x: 0, y: 0, width: 10, height: 10 },
506 });
507 const onSendAnnotation = vi.fn();
508 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
509 await using _screen = await render(view(onSendAnnotation));
510 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
511
512 const sent = { ...picked, screenshot: null };
513 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(sent, null));
514 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, sent);
515 expect(mocks.addImage).not.toHaveBeenCalled();
516 });
517
518 it("lets the pointer reach a local server card above an idle server-rendered tab", async () => {
519 setup();
520 mocks.idleServerTab = true;
521 mocks.servers = [
522 {
523 host: "localhost",
524 port: 8081,
525 url: "http://localhost:8081/",
526 requestedUrl: "http://localhost:8081/",
527 processName: "python3",
528 pid: 4242,
529 terminal: null,
530 source: "scanner",
531 },
532 ];
533 await using _screen = await render(<ToastProvider timeout={0}>{view()}</ToastProvider>);
534 const card = page.getByRole("button", { name: /localhost:8081/ });
535 await expect.element(card).toBeVisible();
536
537 const rect = card.element().getBoundingClientRect();
538 const hit = document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2);
539 expect(card.element().contains(hit)).toBe(true);
540 });
541
542 it("sizes the first device viewport of a streamed tab to its panel", async () => {
543 setup();
544 mocks.streamedServerTab = true;
545 await using _screen = await render(<ToastProvider timeout={0}>{view()}</ToastProvider>);
546 const surface = page.getByTestId("server-browser-surface");
547 await expect.element(surface).toBeInTheDocument();
548 const rect = surface.element().getBoundingClientRect();
549
550 await userEvent.click(page.getByRole("button", { name: "Preview menu" }));
551 await userEvent.click(page.getByRole("menuitem", { name: "Show device toolbar" }));
552
553 expect(commitBrowserViewportChange).toHaveBeenCalledWith(expect.anything(), {
554 _tag: "freeform",
555 ...resolveResponsiveBrowserViewportSize(rect, 1),
556 });
557 });
558
559 it("focuses and selects the address from forwarded desktop actions only while visible", async () => {
560 setup();
561 using stack = new DisposableStack();
562 const previousBridge = window.desktopBridge;
563 stack.defer(() => {
564 if (previousBridge) window.desktopBridge = previousBridge;
565 else delete window.desktopBridge;
566 });
567 const listeners = new Set<(action: string) => void>();
568 window.desktopBridge = {
569 getWindowZoomFactor: () => 1,
570 onMenuAction: (listener: (action: string) => void) => {
571 listeners.add(listener);
572 return () => {
573 listeners.delete(listener);
574 };
575 },
576 } as NonNullable<typeof window.desktopBridge>;
577 await using screen = await render(view());
578 const address = page.getByRole("textbox");
579 const input = address.element() as HTMLInputElement;
580 const forward = () =>
581 act(() => {
582 listeners.forEach((listener) => listener("preview.focusUrl"));
583 });
584
585 await forward();
586 await expect.element(address).toHaveFocus();
587 expect(input.selectionStart).toBe(0);
588 expect(input.selectionEnd).toBe(input.value.length);
589 await act(() => input.blur());
590 await forward();
591 await expect.element(address).toHaveFocus();
592
593 await act(() => input.blur());
594 await screen.rerender(
595 <PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible={false} />,
596 );
597 await forward();
598 await expect.element(address).not.toHaveFocus();
599 expect(listeners.size).toBe(0);
600 });
601
602 it("focuses the address bar each time the focus-url shortcut fires", async () => {
603 setup();
604 await using _screen = await render(view());
605 const address = page.getByRole("textbox");
606
607 act(() => dispatchPreviewAction("focus-url"));
608 await expect.element(address).toHaveFocus();
609
610 (address.element() as HTMLInputElement).blur();
611 await expect.element(address).not.toHaveFocus();
612 act(() => dispatchPreviewAction("focus-url"));
613 await expect.element(address).toHaveFocus();
614 });
615
616 it("does not reopen find when the user returns to a tab they left with find open", async () => {
617 setup();
618 const tabView = (tabId: string) => (
619 <PreviewView threadRef={TEST_THREAD_REF} tabId={tabId} visible />
620 );
621 await using screen = await render(tabView("tab-1"));
622 const findBar = page.getByRole("search", { name: "Find in page" });
623
624 act(() => dispatchPreviewAction("find"));
625 await expect.element(findBar).toBeInTheDocument();
626
627 await screen.rerender(tabView("tab-2"));
628 await expect.element(findBar).not.toBeInTheDocument();
629 await screen.rerender(tabView("tab-1"));
630 await expect.element(findBar).not.toBeInTheDocument();
631 });
632});