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