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

PreviewView.test.tsx

759 lines24.6 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, createElement, Profiler } from "react";
11import { renderToStaticMarkup } from "react-dom/server";
12import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
13​
14const mocks = vi.hoisted(() => ({
15 navigate: vi.fn(async (_tabId: string, _url: string): Promise<void> => undefined),
16 rememberPreviewUrl: vi.fn(),
17 readPreparedConnection: vi.fn(() => ({ httpBaseUrl: "http://172.25.85.75:3773" })),
18 readEnvironmentScope: vi.fn(() => true),
19 setAnnotationSendEnabled: vi.fn(async (): Promise<void> => undefined),
20 cancelPickElement: vi.fn(async () => undefined),
21 submittedUrl: null as ((url: string) => void) | null,
22 emptyStateUrl: null as ((url: string) => void) | null,
23 togglePictureInPicture: null as (() => void) | null,
24 toggleNativePictureInPicture: null as (() => void) | null,
25 pictureInPicturePressed: false,
26 miniPlayerTabId: null as string | null,
27 openMiniPlayer: vi.fn(),
28 closeMiniPlayer: vi.fn(),
29 closeRightPanel: vi.fn(),
30 openPictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
31 closePictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
32 pickElement: vi.fn(),
33 addPreviewAnnotation: vi.fn(),
34 addImage: vi.fn(),
35 toggleAnnotation: null as (() => void) | null,
36 pictureInPicture: false,
37 showEmptyState: false,
38 loading: false,
39 serverEpoch: null as string | null,
40 recordingTabIds: new Set<string>(),
41 recordingRuntimeTabId: null as string | null,
42 recordVisitForThread: vi.fn(),
43}));
44​
45const EMPTY_HISTORY: never[] = [];
46​
47const STUB_BROWSER_DEFAULTS = {
48 viewport: FILL_PREVIEW_VIEWPORT,
49 zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
50 appearance: DEFAULT_PREVIEW_APPEARANCE,
51 autoShowFloatingPreview: true,
52 profiles: BUILT_IN_BROWSER_PROFILES,
53 profileId: DEFAULT_BROWSER_PROFILE_ID,
54};
55​
56vi.mock("~/browserHistoryStore", () => ({
57 recordVisitForThread: mocks.recordVisitForThread,
58 setTitleForThreadUrl: vi.fn(),
59 removeUrlForThread: vi.fn(),
60 BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT: 50,
61 useThreadRecentHistory: () => EMPTY_HISTORY,
62}));
63​
64vi.mock("~/state/session", async (importOriginal) => ({
65 ...(await importOriginal<typeof import("~/state/session")>()),
66 readPreparedConnection: mocks.readPreparedConnection,
67 readEnvironmentScope: mocks.readEnvironmentScope,
68 useEnvironmentScope: mocks.readEnvironmentScope,
69}));
70​
71// File-preview errors share a module with asset hooks. Keep the pure URL resolver
72// without importing those hooks and their environment runtime into chrome tests.
73vi.mock("~/assets/assetUrls", async () => {
74 const { resolveAssetUrl } = await import("@t3tools/client-runtime/state/assets");
75 return { resolveAssetUrl };
76});
77​
78// Stubbed at the direct dependency rather than letting the real module pull in
79// `useSettings` -> `state/server`, which would drag the whole settings and
80// connection graph into a test that only cares about the browser chrome.
81vi.mock("~/browser/browserDefaults", () => ({
82 useBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
83 getBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
84 browserDefaultOpenViewport: () => FILL_PREVIEW_VIEWPORT,
85 browserDefaultOpenProfileId: () => DEFAULT_BROWSER_PROFILE_ID,
86 browserDefaultTabState: () => ({
87 zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
88 colorScheme: DEFAULT_PREVIEW_APPEARANCE,
89 }),
90 browserResponsiveViewportForToggle: () => ({
91 _tag: "freeform" as const,
92 width: 1024,
93 height: 768,
94 }),
95}));
96​
97vi.mock("~/composerDraftStore", () => ({
98 useComposerDraftStore: (
99 select: (store: { addPreviewAnnotation: () => void; addImage: () => void }) => unknown,
100 ) =>
101 select({
102 addPreviewAnnotation: mocks.addPreviewAnnotation,
103 addImage: mocks.addImage,
104 }),
105}));
106​
107vi.mock("~/localApi", () => ({
108 ensureLocalApi: vi.fn(),
109}));
110​
111vi.mock("~/previewStateStore", () => ({
112 rememberPreviewUrl: mocks.rememberPreviewUrl,
113 updatePreviewServerSnapshot: vi.fn(),
114 useThreadPreviewState: () => ({
115 activeTabId: "tab-1",
116 serverEpoch: mocks.serverEpoch,
117 desktopByTabId: {
118 "tab-1": {
119 hasWebContents: true,
120 canGoBack: false,
121 canGoForward: false,
122 loading: mocks.loading,
123 zoomFactor: 1,
124 pictureInPicture: mocks.pictureInPicture,
125 colorScheme: "system",
126 audioMuted: false,
127 audible: false,
128 controller: "none",
129 },
130 },
131 recentlySeenUrls: [],
132 sessions: mocks.showEmptyState
133 ? {}
134 : {
135 "tab-1": {
136 threadId: "thread-1",
137 tabId: "tab-1",
138 navStatus: {
139 _tag: "Success",
140 url: "http://example.com/",
141 title: "Example",
142 },
143 canGoBack: false,
144 canGoForward: false,
145 updatedAt: "2026-07-13T00:00:00.000Z",
146 },
147 },
148 }),
149}));
150​
151vi.mock("~/state/environments", () => ({
152 useEnvironment: () => ({ label: "WSL" }),
153 useEnvironmentHttpBaseUrl: () => "http://172.25.85.75:3773",
154}));
155​
156vi.mock("~/state/preview", () => ({
157 previewEnvironment: { open: {}, resize: {} },
158}));
159​
160vi.mock("~/state/use-atom-command", () => ({
161 useAtomCommand: () => vi.fn(),
162}));
163​
164vi.mock("~/browser/browserRecording", () => ({
165 findActiveBrowserRecordingRuntimeTabId: () => mocks.recordingRuntimeTabId,
166 isBrowserRecordingStartCancelledError: vi.fn(() => false),
167 startBrowserRecording: vi.fn(),
168 stopBrowserRecording: vi.fn(),
169 useActiveBrowserRecordingTabIds: () => mocks.recordingTabIds,
170}));
171​
172vi.mock("~/browser/browserSurfaceStore", () => ({
173 useBrowserSurfaceStore: (
174 select: (state: { byTabId: Record<string, { rect?: unknown }> }) => unknown,
175 ) => select({ byTabId: {} }),
176}));
177​
178vi.mock("~/previewMiniPlayerStore", () => {
179 const usePreviewMiniPlayerStore = Object.assign(
180 (select: (state: unknown) => unknown) =>
181 select({
182 byThreadKey: mocks.miniPlayerTabId
183 ? {
184 "environment-1:thread-1": {
185 source: { kind: "browser", tabId: mocks.miniPlayerTabId },
186 position: null,
187 },
188 }
189 : {},
190 }),
191 {
192 getState: () => ({
193 open: mocks.openMiniPlayer,
194 close: mocks.closeMiniPlayer,
195 }),
196 },
197 );
198 return {
199 browserMiniPlayerSource: (tabId: string) => ({ kind: "browser", tabId }),
200 selectThreadPreviewMiniPlayerTabId: (
201 byThreadKey: Record<string, { source: { tabId: string }; position: null }>,
202 ) => byThreadKey["environment-1:thread-1"]?.source.tabId ?? null,
203 usePreviewMiniPlayerStore,
204 };
205});
206​
207vi.mock("~/rightPanelStore", () => ({
208 useRightPanelStore: {
209 getState: () => ({ close: mocks.closeRightPanel }),
210 },
211}));
212​
213vi.mock("~/components/ui/toast", () => ({
214 stackedThreadToast: vi.fn(),
215 toastManager: { add: vi.fn() },
216}));
217​
218vi.mock("./previewBridge", () => ({
219 previewBridge: {
220 navigate: mocks.navigate,
221 pickElement: mocks.pickElement,
222 setAnnotationSendEnabled: mocks.setAnnotationSendEnabled,
223 cancelPickElement: mocks.cancelPickElement,
224 pictureInPicture: {
225 open: mocks.openPictureInPicture,
226 close: mocks.closePictureInPicture,
227 },
228 },
229}));
230​
231vi.mock("./PreviewChromeRow", () => ({
232 PreviewChromeRow: (props: {
233 onSubmit: (url: string) => void;
234 onPickElement?: () => void;
235 onPictureInPicture?: () => void;
236 pictureInPicture?: boolean;
237 trailingActions?: {
238 props: { actions?: { toggleNativePictureInPicture?: () => void } };
239 };
240 }) => {
241 mocks.submittedUrl = props.onSubmit;
242 mocks.toggleAnnotation = props.onPickElement ?? null;
243 mocks.togglePictureInPicture = props.onPictureInPicture ?? null;
244 mocks.toggleNativePictureInPicture =
245 props.trailingActions?.props.actions?.toggleNativePictureInPicture ?? null;
246 mocks.pictureInPicturePressed = props.pictureInPicture ?? false;
247 return null;
248 },
249}));
250​
251vi.mock("./PreviewEmptyState", () => ({
252 PreviewEmptyState: (props: { onOpenUrl: (url: string) => void }) => {
253 mocks.emptyStateUrl = props.onOpenUrl;
254 return null;
255 },
256}));
257vi.mock("./PreviewMoreMenu", () => ({
258 PreviewMoreMenu: (props: { actions: { toggleNativePictureInPicture?: () => void } }) => {
259 mocks.toggleNativePictureInPicture = props.actions.toggleNativePictureInPicture ?? null;
260 return null;
261 },
262}));
263vi.mock("./PreviewUnreachable", () => ({ PreviewUnreachable: () => null }));
264vi.mock("./ZoomIndicator", () => ({ ZoomIndicator: () => null }));
265vi.mock("./AgentBrowserCursor", () => ({
266 AgentBrowserCursor: () => createElement("agent-cursor"),
267}));
268vi.mock("~/browser/BrowserSurfaceSlot", () => ({ BrowserSurfaceSlot: () => null }));
269vi.mock("./usePreviewSession", () => ({ usePreviewSession: vi.fn() }));
270​
271import { PreviewView } from "./PreviewView";
272import { toastManager } from "~/components/ui/toast";
273import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
274​
275const TEST_THREAD_REF = {
276 environmentId: EnvironmentId.make("environment-1"),
277 threadId: ThreadId.make("thread-1"),
278} as const;
279const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
280​
281// ReactDOM needs a host, but this unit suite intentionally has no DOM dependency.
282class TestNode {
283 parentNode: TestNode | null = null;
284 childNodes: TestNode[] = [];
285 readonly nodeName: string;
286 readonly tagName: string;
287 readonly namespaceURI = "http://www.w3.org/1999/xhtml";
288 readonly style = {};
289​
290 constructor(
291 name: string,
292 readonly ownerDocument: TestNode | null = null,
293 readonly nodeType = 1,
294 ) {
295 this.nodeName = name.toUpperCase();
296 this.tagName = this.nodeName;
297 }
298​
299 set textContent(_value: string) {
300 this.childNodes = [];
301 }
302​
303 appendChild(child: TestNode) {
304 child.parentNode = this;
305 this.childNodes.push(child);
306 return child;
307 }
308​
309 removeChild(child: TestNode) {
310 this.childNodes.splice(this.childNodes.indexOf(child), 1);
311 child.parentNode = null;
312 return child;
313 }
314​
315 createElement(name: string) {
316 return new TestNode(name, this);
317 }
318​
319 addEventListener() {}
320 removeEventListener() {}
321 setAttribute() {}
323​
324function installTestDom() {
325 const document = new TestNode("#document", null, 9);
326 const window = {
327 document,
328 HTMLIFrameElement: TestNode,
329 setInterval: globalThis.setInterval,
330 clearInterval: globalThis.clearInterval,
331 setTimeout: globalThis.setTimeout,
332 clearTimeout: globalThis.clearTimeout,
333 addEventListener() {},
334 removeEventListener() {},
335 };
336 vi.stubGlobal("document", document);
337 vi.stubGlobal("window", window);
338 vi.stubGlobal("HTMLIFrameElement", window.HTMLIFrameElement);
339 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
340 return document;
342​
343describe("PreviewView navigation", () => {
344 beforeEach(() => {
345 mocks.navigate.mockClear();
346 mocks.rememberPreviewUrl.mockClear();
347 mocks.readPreparedConnection.mockClear();
348 mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
349 mocks.setAnnotationSendEnabled.mockClear();
350 mocks.cancelPickElement.mockClear();
351 mocks.submittedUrl = null;
352 mocks.emptyStateUrl = null;
353 mocks.togglePictureInPicture = null;
354 mocks.toggleNativePictureInPicture = null;
355 mocks.pictureInPicturePressed = false;
356 mocks.miniPlayerTabId = null;
357 mocks.openMiniPlayer.mockClear();
358 mocks.closeMiniPlayer.mockClear();
359 mocks.closeRightPanel.mockClear();
360 mocks.openPictureInPicture.mockClear();
361 mocks.closePictureInPicture.mockClear();
362 mocks.pickElement.mockReset();
363 mocks.addPreviewAnnotation.mockClear();
364 vi.mocked(toastManager.add).mockClear();
365 mocks.addImage.mockClear();
366 mocks.toggleAnnotation = null;
367 mocks.pictureInPicture = false;
368 mocks.showEmptyState = false;
369 mocks.loading = false;
370 mocks.serverEpoch = null;
371 mocks.recordingTabIds = new Set();
372 mocks.recordingRuntimeTabId = null;
373 mocks.recordVisitForThread.mockClear();
374 });
375​
376 it("shows the cursor in a replacement browser while the old instance still records", async () => {
377 const document = installTestDom();
378 const { createRoot } = await import("react-dom/client");
379 const container = document.createElement("div");
380 const root = createRoot(container as unknown as Element);
381 const hasCursor = (node: TestNode): boolean =>
382 node.nodeName === "AGENT-CURSOR" || node.childNodes.some(hasCursor);
383 mocks.recordingTabIds.add(TEST_RUNTIME_TAB_ID);
384 mocks.recordingRuntimeTabId = TEST_RUNTIME_TAB_ID;
385 try {
386 await act(() => {
387 root.render(<PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />);
388 });
389 expect(hasCursor(container)).toBe(false);
390 mocks.serverEpoch = "replacement-server";
391 await act(() => {
392 root.render(<PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />);
393 });
394 expect(hasCursor(container)).toBe(true);
395 expect(mocks.recordingTabIds.has(TEST_RUNTIME_TAB_ID)).toBe(true);
396 } finally {
397 await act(() => root.unmount());
398 vi.unstubAllGlobals();
399 }
400 });
401​
402 it("does not rerender while loading time passes", async () => {
403 vi.useFakeTimers();
404 mocks.loading = true;
405 const document = installTestDom();
406 const { createRoot } = await import("react-dom/client");
407 const root = createRoot(document.createElement("div") as unknown as Element);
408 const onRender = vi.fn();
409​
410 try {
411 await act(() => {
412 root.render(
413 <Profiler id="preview" onRender={onRender}>
414 <PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />
415 </Profiler>,
416 );
417 });
418 const initialRenderCount = onRender.mock.calls.length;
419​
420 await act(() => vi.advanceTimersByTimeAsync(1_000));
421​
422 expect(onRender).toHaveBeenCalledTimes(initialRenderCount);
423 } finally {
424 await act(() => root.unmount());
425 vi.useRealTimers();
426 vi.unstubAllGlobals();
427 }
428 });
429​
430 it.each([
431 [
432 "https://localhost:8000/dashboard?mode=test#top",
433 "https://localhost:8000/dashboard?mode=test#top",
434 ],
435 ["localhost:5173/app", "http://localhost:5173/app"],
436 ])("preserves a direct localhost URL in a WSL environment", async (submitted, expected) => {
437 renderToStaticMarkup(
438 <PreviewView
439 threadRef={{
440 environmentId: EnvironmentId.make("environment-1"),
441 threadId: ThreadId.make("thread-1"),
442 }}
443 tabId="tab-1"
444 visible
445 />,
446 );
447​
448 expect(mocks.submittedUrl).not.toBeNull();
449 mocks.submittedUrl?.(submitted);
450​
451 await vi.waitFor(() =>
452 expect(mocks.navigate).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID, expected),
453 );
454 expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
455 {
456 environmentId: "environment-1",
457 threadId: "thread-1",
458 },
459 expected,
460 );
461 });
462​
463 it("records a history visit with the normalized requested url on submit", async () => {
464 renderToStaticMarkup(
465 <PreviewView
466 threadRef={{
467 environmentId: EnvironmentId.make("environment-1"),
468 threadId: ThreadId.make("thread-1"),
469 }}
470 tabId="tab-1"
471 visible
472 />,
473 );
474​
475 mocks.submittedUrl?.("localhost:3000/admin");
476 await vi.waitFor(() => {
477 expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
478 expect.objectContaining({ threadId: expect.anything() }),
479 "http://localhost:3000/admin",
480 );
481 });
482 });
483​
484 it("maps an empty-state localhost server onto the WSL host", async () => {
485 mocks.showEmptyState = true;
486 renderToStaticMarkup(
487 <PreviewView
488 threadRef={{
489 environmentId: EnvironmentId.make("environment-1"),
490 threadId: ThreadId.make("thread-1"),
491 }}
492 tabId="tab-1"
493 visible
494 />,
495 );
496​
497 expect(mocks.emptyStateUrl).not.toBeNull();
498 mocks.emptyStateUrl?.("http://localhost:5173/app?mode=test#top");
499​
500 await vi.waitFor(() =>
501 expect(mocks.navigate).toHaveBeenCalledWith(
502 TEST_RUNTIME_TAB_ID,
503 "http://172.25.85.75:5173/app?mode=test#top",
504 ),
505 );
506 expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
507 {
508 environmentId: "environment-1",
509 threadId: "thread-1",
510 },
511 "http://172.25.85.75:5173/app?mode=test#top",
512 );
513 await vi.waitFor(() =>
514 expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
515 expect.objectContaining({ threadId: expect.anything() }),
516 "http://localhost:5173/app?mode=test#top",
517 ),
518 );
519 });
520​
521 it("opens and closes a thread-scoped floating preview for the active tab", async () => {
522 const props = {
523 threadRef: {
524 environmentId: EnvironmentId.make("environment-1"),
525 threadId: ThreadId.make("thread-1"),
526 },
527 tabId: "tab-1",
528 visible: true,
529 } as const;
530​
531 renderToStaticMarkup(<PreviewView {...props} />);
532 expect(mocks.pictureInPicturePressed).toBe(false);
533 mocks.togglePictureInPicture?.();
534 expect(mocks.openMiniPlayer).toHaveBeenCalledWith(props.threadRef, {
535 kind: "browser",
536 tabId: "tab-1",
537 });
538 expect(mocks.closeRightPanel).toHaveBeenCalledWith(props.threadRef);
539​
540 mocks.miniPlayerTabId = "tab-1";
541 renderToStaticMarkup(<PreviewView {...props} />);
542 expect(mocks.pictureInPicturePressed).toBe(true);
543 mocks.togglePictureInPicture?.();
544 expect(mocks.closeMiniPlayer).toHaveBeenCalledWith(props.threadRef);
545 });
546​
547 it("keeps the native preview window as a secondary action", async () => {
548 const props = {
549 threadRef: {
550 environmentId: EnvironmentId.make("environment-1"),
551 threadId: ThreadId.make("thread-1"),
552 },
553 tabId: "tab-1",
554 visible: true,
555 } as const;
556​
557 renderToStaticMarkup(<PreviewView {...props} />);
558 mocks.toggleNativePictureInPicture?.();
559 await vi.waitFor(() =>
560 expect(mocks.openPictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
561 );
562​
563 mocks.pictureInPicture = true;
564 renderToStaticMarkup(<PreviewView {...props} />);
565 mocks.toggleNativePictureInPicture?.();
566 await vi.waitFor(() =>
567 expect(mocks.closePictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
568 );
569 });
570​
571 it("forwards Cmd/Ctrl+Enter annotations to the composer send path", async () => {
572 const annotation = {
573 id: "annotation-1",
574 pageUrl: "https://example.com/dashboard",
575 pageTitle: "Dashboard",
576 comment: "Tighten this spacing",
577 elements: [],
578 regions: [],
579 strokes: [],
580 styleChanges: [],
581 screenshot: null,
582 createdAt: "2026-07-27T00:00:00.000Z",
583 };
584 const onSendAnnotation = vi.fn();
585 mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
586​
587 renderToStaticMarkup(
588 <PreviewView
589 threadRef={TEST_THREAD_REF}
590 tabId="tab-1"
591 visible
592 onSendAnnotation={onSendAnnotation}
593 />,
594 );
595 mocks.toggleAnnotation?.();
596​
597 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
598 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, annotation);
599 });
600​
601 it("retains the annotation locally when its own environment loses access during capture", async () => {
602 const annotation = {
603 id: "annotation-revoked",
604 pageUrl: "https://example.com/dashboard",
605 pageTitle: "Dashboard",
606 comment: "Tighten this spacing",
607 elements: [],
608 regions: [],
609 strokes: [],
610 styleChanges: [],
611 screenshot: null,
612 createdAt: "2026-09-05T00:00:00.000Z",
613 };
614 const onSendAnnotation = vi.fn();
615 let submitPick: (() => void) | undefined;
616 mocks.pickElement.mockImplementationOnce(
617 () =>
618 new Promise((resolve) => {
619 submitPick = () => resolve({ annotation, submission: "send" });
620 }),
621 );
622 const document = installTestDom();
623 const { createRoot } = await import("react-dom/client");
624 const root = createRoot(document.createElement("div") as unknown as Element);
625 const view = () => (
626 <PreviewView
627 threadRef={TEST_THREAD_REF}
628 tabId="tab-1"
629 visible
630 onSendAnnotation={onSendAnnotation}
631 />
632 );
633 try {
634 await act(async () => root.render(view()));
635 await act(async () => mocks.toggleAnnotation?.());
636 expect(submitPick).toBeDefined();
637 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
638​
639 mocks.readEnvironmentScope.mockImplementation(
640 (environmentId?: unknown) => environmentId !== TEST_THREAD_REF.environmentId,
641 );
642 await act(async () => root.render(view()));
643 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, false);
644 await act(async () => submitPick!());
645 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, annotation);
646 expect(onSendAnnotation).not.toHaveBeenCalled();
647​
648 mocks.readEnvironmentScope.mockReturnValue(true);
649 mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
650 await act(async () => root.render(view()));
651 await act(async () => mocks.toggleAnnotation?.());
652 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
653 expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null);
654 } finally {
655 await act(async () => root.unmount());
656 vi.unstubAllGlobals();
657 }
658 });
659​
660 it("does not reopen a cancelled picker after the permission update finishes", async () => {
661 let finishUpdate: (() => void) | undefined;
662 mocks.setAnnotationSendEnabled.mockImplementationOnce(
663 () =>
664 new Promise<void>((resolve) => {
665 finishUpdate = resolve;
666 }),
667 );
668 const document = installTestDom();
669 const { createRoot } = await import("react-dom/client");
670 const root = createRoot(document.createElement("div") as unknown as Element);
671 try {
672 await act(async () =>
673 root.render(<PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />),
674 );
675 await act(async () => mocks.toggleAnnotation?.());
676 expect(finishUpdate).toBeDefined();
677 expect(mocks.pickElement).not.toHaveBeenCalled();
678 await act(async () => mocks.toggleAnnotation?.());
679 expect(mocks.cancelPickElement).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID);
680 await act(async () => finishUpdate!());
681 expect(mocks.pickElement).not.toHaveBeenCalled();
682 expect(mocks.addPreviewAnnotation).not.toHaveBeenCalled();
683 } finally {
684 await act(async () => root.unmount());
685 vi.unstubAllGlobals();
686 }
687 });
688​
689 it("warns when main dropped the crop before handing over the pick", async () => {
690 const annotation = {
691 id: "annotation-3",
692 pageUrl: "https://example.com/dashboard",
693 pageTitle: "Dashboard",
694 comment: "Tighten this spacing",
695 elements: [],
696 regions: [],
697 strokes: [],
698 styleChanges: [],
699 screenshot: null,
700 createdAt: "2026-07-27T00:00:00.000Z",
701 };
702 const onSendAnnotation = vi.fn();
703 mocks.pickElement.mockResolvedValue({ annotation, submission: "send", screenshotFailed: true });
704​
705 renderToStaticMarkup(
706 <PreviewView
707 threadRef={TEST_THREAD_REF}
708 tabId="tab-1"
709 visible
710 onSendAnnotation={onSendAnnotation}
711 />,
712 );
713 mocks.toggleAnnotation?.();
714​
715 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
716 // A null screenshot alone looks like a comment-only pick; the flag is what
717 // separates "no crop requested" from "crop lost to a timeout".
718 expect(toastManager.add).toHaveBeenCalledTimes(1);
719 });
720​
721 it("still sends annotation text when the picked element's crop is malformed", async () => {
722 const annotation = {
723 id: "annotation-2",
724 pageUrl: "https://example.com/dashboard",
725 pageTitle: "Dashboard",
726 comment: "Tighten this spacing",
727 elements: [],
728 regions: [],
729 strokes: [],
730 styleChanges: [],
731 screenshot: {
732 dataUrl: "data:image/png;base64,%%%",
733 width: 10,
734 height: 10,
735 cropRect: { x: 0, y: 0, width: 10, height: 10 },
736 },
737 createdAt: "2026-07-27T00:00:00.000Z",
738 };
739 const onSendAnnotation = vi.fn();
740 mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
741​
742 renderToStaticMarkup(
743 <PreviewView
744 threadRef={TEST_THREAD_REF}
745 tabId="tab-1"
746 visible
747 onSendAnnotation={onSendAnnotation}
748 />,
749 );
750 mocks.toggleAnnotation?.();
751​
752 // The forwarded and stored annotation both drop the screenshot, so the
753 // prompt does not claim a crop that was never attached.
754 const sent = { ...annotation, screenshot: null };
755 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(sent, null));
756 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, sent);
757 expect(mocks.addImage).not.toHaveBeenCalled();
758 });
759});