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

PreviewView.browser.test.tsx

527 lines19.5 KB

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 { act, Profiler, type ComponentProps, type ReactNode } from "react";
11import { createRoot, type Root } from "react-dom/client";
12import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13import { page, userEvent } from "vite-plus/test/browser";
14​
15import "~/index.css";
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 toast: vi.fn(),
32 pictureInPicture: false,
33 showEmptyState: 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 setAnnotationSendEnabled: mocks.setAnnotationSendEnabled,
59 cancelPickElement: mocks.cancelPickElement,
60 refresh: vi.fn(async () => undefined),
61 goBack: vi.fn(async () => undefined),
62 goForward: vi.fn(async () => undefined),
63 hardReload: vi.fn(async () => undefined),
64 openDevTools: vi.fn(async () => undefined),
65 setColorScheme: vi.fn(async () => undefined),
66 zoomIn: vi.fn(async () => undefined),
67 zoomOut: vi.fn(async () => undefined),
68 resetZoom: vi.fn(async () => undefined),
69 clearCookies: vi.fn(async () => undefined),
70 clearCache: vi.fn(async () => undefined),
71 pictureInPicture: {
72 open: mocks.openPictureInPicture,
73 close: mocks.closePictureInPicture,
74 },
75 } as never,
76}));
77vi.mock(import("~/browserHistoryStore"), async (original) => ({
78 ...(await original()),
79 recordVisitForThread: mocks.recordVisitForThread,
80}));
81vi.mock(import("~/state/session"), async (original) => ({
82 ...(await original()),
83 readPreparedConnection: mocks.readPreparedConnection as never,
84 readEnvironmentScope: mocks.readEnvironmentScope,
85 useEnvironmentScope: mocks.readEnvironmentScope,
86}));
87vi.mock(import("~/browser/browserDefaults"), async (original) => ({
88 ...(await original()),
89 useBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
90 getBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
91}));
92vi.mock(import("~/previewStateStore"), async (original) => ({
93 ...(await original()),
94 rememberPreviewUrl: mocks.rememberPreviewUrl,
95 useThreadPreviewState: (() => ({
96 activeTabId: "tab-1",
97 serverEpoch: mocks.serverEpoch,
98 desktopByTabId: {
99 "tab-1": {
100 hasWebContents: true,
101 canGoBack: false,
102 canGoForward: false,
103 loading: mocks.loading,
104 zoomFactor: 1,
105 pictureInPicture: mocks.pictureInPicture,
106 colorScheme: "system",
107 audioMuted: false,
108 audible: false,
109 controller: "none",
110 },
111 },
112 recentlySeenUrls: [],
113 sessions: mocks.showEmptyState
114 ? {}
115 : {
116 "tab-1": {
117 threadId: "thread-1",
118 tabId: "tab-1",
119 runtime: mocks.nativeServerTab ? "server" : "desktop",
120 navStatus: { _tag: "Success", url: "http://example.com/", title: "Example" },
121 canGoBack: false,
122 canGoForward: false,
123 updatedAt: "2026-07-13T00:00:00.000Z",
124 },
125 },
126 })) as never,
127}));
128vi.mock(import("~/state/environments"), async (original) => ({
129 ...(await original()),
130 useEnvironment: (() => ({ label: "WSL" })) as never,
131 useEnvironmentHttpBaseUrl: () => "http://172.25.85.75:3773",
132 usePrimaryEnvironmentId: () => null,
133}));
134vi.mock(import("~/browser/browserRecording"), async (original) => ({
135 ...(await original()),
136 findActiveBrowserRecordingRuntimeTabId: () => mocks.recordingRuntimeTabId,
137 useActiveBrowserRecordingTabIds: () => mocks.recordingTabIds,
138}));
139vi.mock(import("~/components/ui/toast"), async (original) => {
140 const actual = await original();
141 return { ...actual, toastManager: { ...actual.toastManager, add: mocks.toast } };
142});
143vi.mock(import("./useDiscoveredLocalServers"), async (original) => ({
144 ...(await original()),
145 useDiscoveredLocalServers: () => mocks.servers,
146}));
147vi.mock(import("./usePreviewSession"), async (original) => ({
148 ...(await original()),
149 usePreviewSession: () => {},
150}));
151​
152vi.mock(import("~/browser/previewRuntime"), async (original) => ({
153 ...(await original()),
154 useRendersServerTabNatively: () => mocks.nativeServerTab,
155}));
156​
157vi.mock(import("~/browser/browserViewportActions"), { spy: true });
158​
159import { commitBrowserViewportChange } from "~/browser/browserViewportActions";
160import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
161import { useComposerDraftStore } from "~/composerDraftStore";
162import { useBrowserPointerStore } from "~/browser/browserPointerStore";
163import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
164import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
165import { PreviewView } from "./PreviewView";
166​
167const TEST_THREAD_REF = {
168 environmentId: EnvironmentId.make("environment-1"),
169 threadId: ThreadId.make("thread-1"),
170} as const;
171const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
172​
173const roots: Root[] = [];
174let root: Root;
175​
176async function render(node: ReactNode) {
177 await act(async () => root.render(node));
179​
180function view(onSendAnnotation?: ComponentProps<typeof PreviewView>["onSendAnnotation"]) {
181 return (
182 <PreviewView
183 threadRef={TEST_THREAD_REF}
184 tabId="tab-1"
185 visible
186 {...(onSendAnnotation ? { onSendAnnotation } : {})}
187 />
188 );
190​
191function annotation(id: string, screenshot: unknown = null) {
192 return {
193 id,
194 pageUrl: "https://example.com/dashboard",
195 pageTitle: "Dashboard",
196 comment: "Tighten this spacing",
197 elements: [],
198 regions: [],
199 strokes: [],
200 styleChanges: [],
201 screenshot,
202 createdAt: "2026-07-27T00:00:00.000Z",
203 };
205​
206async function submitAddress(text: string) {
207 const input = page.getByPlaceholder("Search or enter URL");
208 await userEvent.click(input);
209 await userEvent.fill(input, text);
210 await userEvent.keyboard("{Enter}");
212​
213function hasCursor() {
214 return document.querySelector("svg.lucide-mouse-pointer2") !== null;
216​
217describe("PreviewView", () => {
218 beforeEach(() => {
219 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
220 vi.clearAllMocks();
221 mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
222 mocks.setAnnotationSendEnabled.mockReset().mockResolvedValue(undefined);
223 mocks.pickElement.mockReset();
224 mocks.pictureInPicture = false;
225 mocks.showEmptyState = false;
226 mocks.loading = false;
227 mocks.nativeServerTab = false;
228 mocks.serverEpoch = null;
229 mocks.servers = [];
230 mocks.recordingTabIds = new Set();
231 mocks.recordingRuntimeTabId = null;
232 useComposerDraftStore.setState({
233 addPreviewAnnotation: mocks.addPreviewAnnotation,
234 addImage: mocks.addImage,
235 });
236 usePreviewMiniPlayerStore.setState({ byThreadKey: {} });
237 useBrowserPointerStore.setState({ byTabId: {} });
238 const container = document.createElement("div");
239 document.body.append(container);
240 root = createRoot(container);
241 roots.push(root);
242 });
243​
244 afterEach(async () => {
245 for (const each of roots.splice(0)) await act(async () => each.unmount());
246 document.body.replaceChildren();
247 vi.useRealTimers();
248 vi.unstubAllGlobals();
249 });
250​
251 it("shows the cursor in a replacement browser while the old instance still records", async () => {
252 mocks.recordingTabIds.add(TEST_RUNTIME_TAB_ID);
253 mocks.recordingRuntimeTabId = TEST_RUNTIME_TAB_ID;
254 const replacementTabId = previewRuntimeTabId(TEST_THREAD_REF, "replacement-server", "tab-1");
255 useBrowserPointerStore.setState({
256 byTabId: Object.fromEntries(
257 [TEST_RUNTIME_TAB_ID, replacementTabId].map((tabId) => [
258 tabId,
259 { tabId, phase: "move", x: 10, y: 10, sequence: 1, createdAt: "2026-07-27T00:00:00Z" },
260 ]),
261 ),
262 });
263 await render(view());
264 expect(hasCursor()).toBe(false);
265 mocks.serverEpoch = "replacement-server";
266 await render(view());
267 expect(hasCursor()).toBe(true);
268 expect(mocks.recordingTabIds.has(TEST_RUNTIME_TAB_ID)).toBe(true);
269 });
270​
271 it.each([false, true])(
272 "aligns the cursor and responsive viewport after host zoom changes (native server tab: %s)",
273 async (nativeServerTab) => {
274 mocks.nativeServerTab = nativeServerTab;
275 let windowZoom = 1;
276 vi.stubGlobal("desktopBridge", {
277 getWindowZoomFactor: () => windowZoom,
278 getLocalEnvironmentBootstraps: () => [],
279 });
280 const commit = vi.mocked(commitBrowserViewportChange).mockResolvedValueOnce(undefined);
281 try {
282 await render(view());
283 await act(() => {
284 const surfaces = useBrowserSurfaceStore.getState();
285 const slot = document.querySelector<HTMLElement>("[data-browser-surface-slot]")!;
286 slot.style.width = "1020px";
287 slot.style.height = "798px";
288 surfaces.presentContent(TEST_RUNTIME_TAB_ID, {
289 x: 20,
290 y: 40,
291 width: 500,
292 height: 375,
293 scale: 0.5,
294 scrollLeft: 7,
295 scrollTop: 11,
296 });
297 useBrowserPointerStore.setState({
298 byTabId: {
299 [TEST_RUNTIME_TAB_ID]: {
300 tabId: TEST_RUNTIME_TAB_ID,
301 phase: "move",
302 x: 100,
303 y: 200,
304 sequence: 1,
305 createdAt: "2026-07-27T00:00:00Z",
306 },
307 },
308 });
309 windowZoom = 1.25;
310 window.dispatchEvent(new Event("resize"));
311 });
312 const cursor = document.querySelector("[data-agent-browser-cursor]");
313 expect(cursor).not.toBeNull();
314 const position = new DOMMatrixReadOnly(getComputedStyle(cursor!).transform);
315 expect(position.e).toBe(53);
316 expect(position.f).toBe(109);
317​
318 await userEvent.click(page.getByRole("button", { name: "Preview menu" }));
319 await userEvent.click(page.getByRole("menuitem", { name: "Show device toolbar" }));
320 expect(commit).toHaveBeenCalledExactlyOnceWith(TEST_RUNTIME_TAB_ID, {
321 _tag: "freeform",
322 width: 1250,
323 height: 938,
324 });
325 } finally {
326 commit.mockReset();
327 await act(() => useBrowserSurfaceStore.setState({ activityByTabId: {}, byTabId: {} }));
328 }
329 },
330 );
331​
332 it("does not rerender while loading time passes", async () => {
333 vi.useFakeTimers();
334 mocks.loading = true;
335 const onRender = vi.fn();
336 await render(
337 <Profiler id="preview" onRender={onRender}>
338 {view()}
339 </Profiler>,
340 );
341 const initialRenderCount = onRender.mock.calls.length;
342 await act(() => vi.advanceTimersByTimeAsync(1_000));
343 expect(onRender).toHaveBeenCalledTimes(initialRenderCount);
344 });
345​
346 it.each([
347 [
348 "https://localhost:8000/dashboard?mode=test#top",
349 "https://localhost:8000/dashboard?mode=test#top",
350 ],
351 ["localhost:5173/app", "http://localhost:5173/app"],
352 ])(
353 "preserves a direct localhost URL %s in a WSL environment and records it",
354 async (submitted, expected) => {
355 await render(view());
356 await submitAddress(submitted);
357 await vi.waitFor(() =>
358 expect(mocks.navigate).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID, expected),
359 );
360 expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(TEST_THREAD_REF, expected);
361 expect(mocks.recordVisitForThread).toHaveBeenCalledWith(TEST_THREAD_REF, expected);
362 },
363 );
364​
365 it("maps an empty-state localhost server onto the WSL host", async () => {
366 mocks.showEmptyState = true;
367 mocks.servers = [
368 {
369 host: "localhost",
370 port: 5173,
371 url: "http://localhost:5173/app?mode=test#top",
372 requestedUrl: "http://localhost:5173/app?mode=test#top",
373 processName: "vite",
374 pid: 1,
375 terminal: null,
376 source: "scanner",
377 } as unknown as PreviewableServer,
378 ];
379 await render(view());
380 await userEvent.click(page.getByRole("button", { name: /vite/ }));
381​
382 await vi.waitFor(() =>
383 expect(mocks.navigate).toHaveBeenCalledWith(
384 TEST_RUNTIME_TAB_ID,
385 "http://172.25.85.75:5173/app?mode=test#top",
386 ),
387 );
388 expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
389 TEST_THREAD_REF,
390 "http://172.25.85.75:5173/app?mode=test#top",
391 );
392 // History keys off the requested loopback URL, which stays stable across hosts.
393 await vi.waitFor(() =>
394 expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
395 TEST_THREAD_REF,
396 "http://localhost:5173/app?mode=test#top",
397 ),
398 );
399 });
400​
401 it("opens and closes a thread-scoped floating preview for the active tab", async () => {
402 await render(view());
403 await userEvent.click(page.getByRole("button", { name: "Float preview over chat" }));
404 expect(usePreviewMiniPlayerStore.getState().byThreadKey).toMatchObject({
405 "environment-1:thread-1": { source: { kind: "browser", tabId: "tab-1" } },
406 });
407 const closeButton = page.getByRole("button", { name: "Close floating preview" });
408 await expect.element(closeButton).toHaveAttribute("aria-pressed", "true");
409 await userEvent.click(closeButton);
410 expect(usePreviewMiniPlayerStore.getState().byThreadKey).toEqual({});
411 });
412​
413 it("keeps the native preview window as a secondary menu action", async () => {
414 await render(view());
415 await userEvent.click(page.getByRole("button", { name: "Preview menu" }));
416 await userEvent.click(page.getByRole("menuitem", { name: "Open separate preview window" }));
417 await vi.waitFor(() =>
418 expect(mocks.openPictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
419 );
420 await vi.waitFor(() => expect(document.querySelector('[role="menu"]')).toBeNull());
421​
422 mocks.pictureInPicture = true;
423 await render(view());
424 await userEvent.click(page.getByRole("button", { name: "Preview menu" }));
425 await userEvent.click(page.getByRole("menuitem", { name: "Close separate preview window" }));
426 await vi.waitFor(() =>
427 expect(mocks.closePictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
428 );
429 });
430​
431 it("forwards Cmd/Ctrl+Enter annotations to the composer send path", async () => {
432 const picked = annotation("annotation-1");
433 const onSendAnnotation = vi.fn();
434 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
435 await render(view(onSendAnnotation));
436 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
437​
438 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
439 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, picked);
440 });
441​
442 it("retains the annotation locally when its own environment loses access during capture", async () => {
443 const picked = annotation("annotation-revoked");
444 const onSendAnnotation = vi.fn();
445 let submitPick: (() => void) | undefined;
446 mocks.pickElement.mockImplementationOnce(
447 () =>
448 new Promise((resolve) => {
449 submitPick = () => resolve({ annotation: picked, submission: "send" });
450 }),
451 );
452 await render(view(onSendAnnotation));
453 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
454 await vi.waitFor(() => expect(submitPick).toBeDefined());
455 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
456​
457 mocks.readEnvironmentScope.mockImplementation(
458 (environmentId?: unknown) => environmentId !== TEST_THREAD_REF.environmentId,
459 );
460 await render(view(onSendAnnotation));
461 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, false);
462 await act(async () => submitPick!());
463 await vi.waitFor(() =>
464 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, picked),
465 );
466 expect(onSendAnnotation).not.toHaveBeenCalled();
467​
468 mocks.readEnvironmentScope.mockReturnValue(true);
469 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
470 await render(view(onSendAnnotation));
471 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
472 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
473 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
474 });
475​
476 it("does not reopen a cancelled picker after the permission update finishes", async () => {
477 let finishUpdate: (() => void) | undefined;
478 mocks.setAnnotationSendEnabled.mockImplementationOnce(
479 () =>
480 new Promise<void>((resolve) => {
481 finishUpdate = resolve;
482 }),
483 );
484 await render(view());
485 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
486 await vi.waitFor(() => expect(finishUpdate).toBeDefined());
487 expect(mocks.pickElement).not.toHaveBeenCalled();
488 await userEvent.click(page.getByRole("button", { name: "Cancel annotation" }));
489 expect(mocks.cancelPickElement).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID);
490 await act(async () => finishUpdate!());
491 expect(mocks.pickElement).not.toHaveBeenCalled();
492 expect(mocks.addPreviewAnnotation).not.toHaveBeenCalled();
493 });
494​
495 it("warns when main dropped the crop before handing over the pick", async () => {
496 const picked = annotation("annotation-3");
497 const onSendAnnotation = vi.fn();
498 mocks.pickElement.mockResolvedValue({
499 annotation: picked,
500 submission: "send",
501 screenshotFailed: true,
502 });
503 await render(view(onSendAnnotation));
504 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
505​
506 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
507 expect(mocks.toast).toHaveBeenCalledOnce();
508 });
509​
510 it("still sends annotation text when the picked element's crop is malformed", async () => {
511 const picked = annotation("annotation-2", {
512 dataUrl: "data:image/png;base64,%%%",
513 width: 10,
514 height: 10,
515 cropRect: { x: 0, y: 0, width: 10, height: 10 },
516 });
517 const onSendAnnotation = vi.fn();
518 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
519 await render(view(onSendAnnotation));
520 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
521​
522 const sent = { ...picked, screenshot: null };
523 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(sent, null));
524 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, sent);
525 expect(mocks.addImage).not.toHaveBeenCalled();
526 });
527});