Open History to see the last commit
1"use client";
2
3import { scopedThreadKey } from "@t3tools/client-runtime/environment";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import {
9 DEFAULT_BROWSER_PROFILE_ID,
10 FILL_PREVIEW_VIEWPORT,
11 type PreviewAnnotationPayload,
12 type PreviewViewportSetting,
13 type ScopedThreadRef,
14} from "@t3tools/contracts";
15import { normalizePreviewUrl } from "@t3tools/shared/preview";
16import { useCallback, useEffect, useRef, useState } from "react";
17
18import {
19 BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT,
20 recordVisitForThread,
21 removeUrlForThread,
22 setTitleForThreadUrl,
23 useThreadRecentHistory,
24} from "~/browserHistoryStore";
25import { type ComposerImageAttachment, useComposerDraftStore } from "~/composerDraftStore";
26import { capturePreviewAnnotationScreenshot } from "~/lib/previewAnnotation";
27import { ensureLocalApi } from "~/localApi";
28import {
29 rememberPreviewUrl,
30 updatePreviewServerSnapshot,
31 useThreadPreviewState,
32} from "~/previewStateStore";
33import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
34import { useEnvironmentHttpBaseUrl } from "~/state/environments";
35import { previewEnvironment } from "~/state/preview";
36import { useAtomCommand } from "~/state/use-atom-command";
37import {
38 browserMiniPlayerSource,
39 selectThreadPreviewMiniPlayerTabId,
40 usePreviewMiniPlayerStore,
41} from "~/previewMiniPlayerStore";
42import { useRightPanelStore } from "~/rightPanelStore";
43
44import { previewBridge } from "./previewBridge";
45import { subscribePreviewAction } from "./previewActionBus";
46import { openPreviewSession } from "./openPreviewSession";
47import { PreviewChromeRow } from "./PreviewChromeRow";
48import { PreviewEmptyState } from "./PreviewEmptyState";
49import { PreviewMoreMenu } from "./PreviewMoreMenu";
50import {
51 commitBrowserViewportChange,
52 subscribeBrowserViewportChange,
53} from "~/browser/browserViewportActions";
54import { browserResponsiveViewportForToggle, useBrowserDefaults } from "~/browser/browserDefaults";
55import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
56import { BrowserSettingsReadError } from "~/browser/openFileInPreview";
57import { PreviewUnreachable } from "./PreviewUnreachable";
58import { revealInFileExplorerLabel } from "./fileExplorerLabel";
59import { shouldShowPreviewEmptyState } from "./previewEmptyStateLogic";
60import { Badge } from "~/components/ui/badge";
61import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot";
62import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
63import { usePreviewSession } from "./usePreviewSession";
64import { ZoomIndicator } from "./ZoomIndicator";
65import { AgentBrowserCursor } from "./AgentBrowserCursor";
66import {
67 findActiveBrowserRecordingRuntimeTabId,
68 isBrowserRecordingStartCancelledError,
69 startBrowserRecording,
70 stopBrowserRecording,
71 useActiveBrowserRecordingTabIds,
72} from "~/browser/browserRecording";
73import { stackedThreadToast, toastManager } from "~/components/ui/toast";
74import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
75
76interface Props {
77 threadRef: ScopedThreadRef;
78 tabId?: string | null;
79 configuredUrls?: ReadonlyArray<string> | undefined;
80 visible: boolean;
81 onSendAnnotation?: (
82 annotation: PreviewAnnotationPayload,
83 image: ComposerImageAttachment | null,
84 ) => void;
85}
86
87function previewProfileName(
88 profiles: ReadonlyArray<{ readonly id: string; readonly name: string }>,
89 profileId: string,
90): string {
91 return profiles.find((profile) => profile.id === profileId)?.name ?? "Removed profile";
92}
93
94const localApi = typeof window === "undefined" ? null : ensureLocalApi();
95
96/**
97 * Single-tab preview surface: chrome row on top, one webview below, empty
98 * state when no session exists for the thread.
99 */
100export function PreviewView({
101 threadRef,
102 tabId: requestedTabId,
103 configuredUrls,
104 visible,
105 onSendAnnotation,
106}: Props) {
107 const [focusUrlNonce, setFocusUrlNonce] = useState<number | undefined>(undefined);
108 const [pickActive, setPickActive] = useState(false);
109 const activeRecordingTabIds = useActiveBrowserRecordingTabIds();
110 const pickActiveRef = useRef(false);
111 const isMountedRef = useRef(true);
112 // Kept in sync so the title effect can depend on the stable thread key
113 // instead of the thread object, which is recreated on every update.
114 const threadRefRef = useRef(threadRef);
115 threadRefRef.current = threadRef;
116 const previewState = useThreadPreviewState(threadRef);
117 const recentHistoryEntries = useThreadRecentHistory(
118 threadRef,
119 BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT,
120 );
121 const miniPlayerTabId = usePreviewMiniPlayerStore((state) =>
122 selectThreadPreviewMiniPlayerTabId(state.byThreadKey, threadRef),
123 );
124 const addPreviewAnnotation = useComposerDraftStore((store) => store.addPreviewAnnotation);
125 const addImage = useComposerDraftStore((store) => store.addImage);
126 const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(threadRef.environmentId);
127 const environmentHostname = environmentHttpBaseUrl
128 ? new URL(environmentHttpBaseUrl).hostname
129 : null;
130 const open = useAtomCommand(previewEnvironment.open);
131 const resize = useAtomCommand(previewEnvironment.resize, "preview viewport resize");
132
133 usePreviewSession(threadRef);
134
135 useEffect(() => {
136 isMountedRef.current = true;
137 return () => {
138 isMountedRef.current = false;
139 };
140 }, []);
141
142 const tabId = requestedTabId ?? previewState.activeTabId;
143 const runtimeTabId = tabId
144 ? previewRuntimeTabId(threadRef, previewState.serverEpoch, tabId)
145 : null;
146 const recordingRuntimeTabId =
147 tabId && runtimeTabId
148 ? activeRecordingTabIds.has(runtimeTabId)
149 ? runtimeTabId
150 : findActiveBrowserRecordingRuntimeTabId(threadRef, tabId)
151 : null;
152 const snapshot = tabId ? (previewState.sessions[tabId] ?? null) : null;
153 const desktopOverlay = tabId ? (previewState.desktopByTabId[tabId] ?? null) : null;
154 const navStatus = snapshot?.navStatus ?? { _tag: "Idle" as const };
155 const url = navStatus._tag === "Idle" ? "" : navStatus.url;
156 const loading = desktopOverlay?.loading ?? navStatus._tag === "Loading";
157 const canGoBack = desktopOverlay?.canGoBack ?? snapshot?.canGoBack ?? false;
158 const canGoForward = desktopOverlay?.canGoForward ?? snapshot?.canGoForward ?? false;
159 const refreshDisabled = navStatus._tag === "Idle";
160 const isUnreachable = navStatus._tag === "LoadFailed";
161 const showEmptyState = shouldShowPreviewEmptyState(snapshot);
162 const controller = desktopOverlay?.controller ?? "none";
163 const viewport = snapshot?.viewport ?? FILL_PREVIEW_VIEWPORT;
164 const browserDefaults = useBrowserDefaults();
165 // A tab created before profiles existed carries no profile of its own. It
166 // runs in the built-in `default` partition — the scope the browser used
167 // before profiles — not in whatever profile is configured as the default
168 // now, so that is what its label names and its clear actions target.
169 // Passing the snapshot's raw `undefined` through would reach the IPC layer
170 // as "every profile".
171 const activeProfileId = snapshot?.profileId ?? DEFAULT_BROWSER_PROFILE_ID;
172 const activeProfileName = previewProfileName(browserDefaults.profiles, activeProfileId);
173 const panelRect = useBrowserSurfaceStore((state) =>
174 runtimeTabId ? (state.byTabId[runtimeTabId]?.rect ?? null) : null,
175 );
176
177 const navUrl = navStatus._tag === "Success" ? navStatus.url : null;
178 const navTitle = navStatus._tag === "Success" ? navStatus.title : null;
179 const latestHistoryUrl = recentHistoryEntries[0]?.url;
180 const threadKey = scopedThreadKey(threadRef);
181 useEffect(() => {
182 if (!navUrl || !navTitle || !latestHistoryUrl) return;
183 // Agent-driven pages only enrich an existing requested URL.
184 setTitleForThreadUrl(threadRefRef.current, navUrl, navTitle, environmentHostname);
185 // threadKey stands in for threadRef, whose identity churns on every thread update.
186 }, [environmentHostname, latestHistoryUrl, navTitle, navUrl, threadKey]);
187
188 const navigateToResolvedUrl = useCallback(
189 async (resolvedUrl: string) => {
190 if (runtimeTabId && previewBridge) {
191 // The bridge mirrors the resolved URL back to the server.
192 await previewBridge.navigate(runtimeTabId, resolvedUrl);
193 rememberPreviewUrl(threadRef, resolvedUrl);
194 return true;
195 }
196 const result = await openPreviewSession({ openPreview: open, threadRef, url: resolvedUrl });
197 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
198 const error = squashAtomCommandFailure(result);
199 if (error instanceof BrowserSettingsReadError) {
200 toastManager.add({
201 type: "error",
202 title: "Unable to open browser",
203 description: error.message,
204 });
205 }
206 }
207 return result._tag === "Success";
208 },
209 [open, runtimeTabId, threadRef],
210 );
211
212 const handleSubmitUrl = useCallback(
213 async (next: string) => {
214 try {
215 const normalized = normalizePreviewUrl(next);
216 if (await navigateToResolvedUrl(normalized)) {
217 recordVisitForThread(threadRef, normalized);
218 }
219 } catch {
220 // Server-side `failed` event renders the unreachable view.
221 }
222 },
223 [navigateToResolvedUrl, threadRef],
224 );
225
226 const handleOpenServerUrl = useCallback(
227 async (next: string) => {
228 try {
229 const resolved = resolveDiscoveredServerUrl(threadRef.environmentId, next);
230 if (await navigateToResolvedUrl(resolved)) {
231 recordVisitForThread(threadRef, next);
232 }
233 } catch {
234 // Server-side `failed` event renders the unreachable view.
235 }
236 },
237 [navigateToResolvedUrl, threadRef],
238 );
239
240 const handleRefresh = useCallback(() => {
241 if (previewBridge && runtimeTabId) void previewBridge.refresh(runtimeTabId);
242 }, [runtimeTabId]);
243
244 const handleZoomIn = useCallback(() => {
245 if (previewBridge && runtimeTabId) void previewBridge.zoomIn(runtimeTabId);
246 }, [runtimeTabId]);
247
248 const handleZoomOut = useCallback(() => {
249 if (previewBridge && runtimeTabId) void previewBridge.zoomOut(runtimeTabId);
250 }, [runtimeTabId]);
251
252 const handleResetZoom = useCallback(() => {
253 if (previewBridge && runtimeTabId) void previewBridge.resetZoom(runtimeTabId);
254 }, [runtimeTabId]);
255
256 const handleViewportChange = useCallback(
257 async (nextViewport: PreviewViewportSetting) => {
258 if (!tabId) return;
259 const result = await resize({
260 environmentId: threadRef.environmentId,
261 input: {
262 threadId: threadRef.threadId,
263 tabId,
264 viewport: nextViewport,
265 },
266 });
267 if (result._tag === "Failure") {
268 const error = squashAtomCommandFailure(result);
269 toastManager.add({
270 type: "error",
271 title: "Unable to resize browser viewport",
272 description: error instanceof Error ? error.message : "An error occurred.",
273 });
274 throw error;
275 }
276 updatePreviewServerSnapshot(threadRef, result.value);
277 },
278 [resize, tabId, threadRef],
279 );
280
281 const handleToggleDeviceToolbar = () => {
282 if (!runtimeTabId) return;
283 if (viewport._tag !== "fill") {
284 void commitBrowserViewportChange(runtimeTabId, FILL_PREVIEW_VIEWPORT).catch(() => undefined);
285 return;
286 }
287
288 void commitBrowserViewportChange(
289 runtimeTabId,
290 browserResponsiveViewportForToggle({
291 defaults: browserDefaults,
292 panelRect,
293 zoomFactor: desktopOverlay?.zoomFactor,
294 }),
295 ).catch(() => undefined);
296 };
297
298 useEffect(() => {
299 if (!runtimeTabId) return;
300 return subscribeBrowserViewportChange(runtimeTabId, handleViewportChange);
301 }, [handleViewportChange, runtimeTabId]);
302
303 const handleBack = useCallback(() => {
304 if (previewBridge && runtimeTabId) void previewBridge.goBack(runtimeTabId);
305 }, [runtimeTabId]);
306
307 const handleForward = useCallback(() => {
308 if (previewBridge && runtimeTabId) void previewBridge.goForward(runtimeTabId);
309 }, [runtimeTabId]);
310
311 const handleOpenInBrowser = useCallback(() => {
312 if (!localApi || !url) return;
313 void localApi.shell.openExternal(url).catch(() => undefined);
314 }, [url]);
315
316 const handlePictureInPicture = useCallback(() => {
317 if (!tabId) return;
318 if (miniPlayerTabId === tabId) {
319 usePreviewMiniPlayerStore.getState().close(threadRef);
320 return;
321 }
322 usePreviewMiniPlayerStore.getState().open(threadRef, browserMiniPlayerSource(tabId));
323 useRightPanelStore.getState().close(threadRef);
324 }, [miniPlayerTabId, tabId, threadRef]);
325
326 const handleNativePictureInPicture = useCallback(() => {
327 if (!previewBridge || !runtimeTabId) return;
328 const operation = desktopOverlay?.pictureInPicture
329 ? previewBridge.pictureInPicture.close
330 : previewBridge.pictureInPicture.open;
331 void operation(runtimeTabId).catch((error) => {
332 toastManager.add({
333 type: "error",
334 title: "Unable to update popped-out preview",
335 description: error instanceof Error ? error.message : "An error occurred.",
336 });
337 });
338 }, [desktopOverlay?.pictureInPicture, runtimeTabId]);
339
340 const handleCapture = useCallback(
341 (record: boolean) => {
342 if (!previewBridge || !runtimeTabId || !tabId) return;
343 const bridge = previewBridge;
344 if (recordingRuntimeTabId) {
345 void stopBrowserRecording(recordingRuntimeTabId).then(
346 (artifact) => {
347 if (!artifact) return;
348 let pathCopied = false;
349 let toastId: ReturnType<typeof toastManager.add>;
350
351 const copyPath = () => {
352 if (!navigator.clipboard?.writeText) {
353 toastManager.update(
354 toastId,
355 stackedThreadToast({
356 type: "error",
357 title: "Unable to copy recording path",
358 description: "Clipboard API unavailable.",
359 actionProps: revealAction,
360 }),
361 );
362 return;
363 }
364
365 void navigator.clipboard.writeText(artifact.path).then(
366 () => {
367 pathCopied = true;
368 updateRecordingToast();
369 window.setTimeout(() => {
370 pathCopied = false;
371 updateRecordingToast();
372 }, 2_000);
373 },
374 (error) => {
375 toastManager.update(
376 toastId,
377 stackedThreadToast({
378 type: "error",
379 title: "Unable to copy recording path",
380 description: error instanceof Error ? error.message : "An error occurred.",
381 actionProps: revealAction,
382 }),
383 );
384 },
385 );
386 };
387
388 const revealAction = {
389 children: revealInFileExplorerLabel(navigator.platform),
390 onClick: () => void bridge.revealArtifact(artifact.path),
391 };
392 const updateRecordingToast = () => {
393 toastManager.update(
394 toastId,
395 stackedThreadToast({
396 type: "success",
397 title: "Recording saved",
398 actionProps: revealAction,
399 data: {
400 secondaryActionProps: {
401 children: pathCopied ? "Copied!" : "Copy path",
402 disabled: pathCopied,
403 onClick: copyPath,
404 },
405 secondaryActionVariant: "outline",
406 },
407 }),
408 );
409 };
410
411 toastId = toastManager.add(
412 stackedThreadToast({
413 type: "success",
414 title: "Recording saved",
415 actionProps: revealAction,
416 data: {
417 secondaryActionProps: {
418 children: "Copy path",
419 onClick: copyPath,
420 },
421 secondaryActionVariant: "outline",
422 },
423 }),
424 );
425 },
426 (error) => {
427 toastManager.add({
428 type: "error",
429 title: "Unable to stop recording",
430 description: error instanceof Error ? error.message : "An error occurred.",
431 });
432 },
433 );
434 return;
435 }
436 if (record) {
437 void startBrowserRecording(runtimeTabId, threadRef, tabId).catch((error) => {
438 const description = error instanceof Error ? error.message : "An error occurred.";
439 if (isBrowserRecordingStartCancelledError(error)) return;
440 toastManager.add({
441 type: "error",
442 title: "Unable to start recording",
443 description,
444 });
445 });
446 return;
447 }
448 void bridge.captureScreenshot(runtimeTabId).then(
449 (artifact) => {
450 const revealAction = {
451 children: revealInFileExplorerLabel(navigator.platform),
452 onClick: () => void bridge.revealArtifact(artifact.path),
453 };
454 let pathCopied = false;
455 let imageCopied = false;
456 let toastId: ReturnType<typeof toastManager.add>;
457
458 const updateScreenshotToast = (
459 type: "success" | "error" = "success",
460 title = "Screenshot saved",
461 description?: string,
462 ) => {
463 toastManager.update(
464 toastId,
465 stackedThreadToast({
466 type,
467 title,
468 description,
469 actionProps: {
470 children: imageCopied ? "Copied!" : "Copy image",
471 disabled: imageCopied,
472 onClick: copyImage,
473 },
474 data: {
475 additionalActions: [
476 {
477 id: "copy-path",
478 props: {
479 children: pathCopied ? "Copied!" : "Copy path",
480 disabled: pathCopied,
481 onClick: copyPath,
482 },
483 },
484 ],
485 secondaryActionProps: {
486 ...revealAction,
487 },
488 secondaryActionVariant: "outline",
489 },
490 }),
491 );
492 };
493
494 const copyPath = () => {
495 if (!navigator.clipboard?.writeText) {
496 updateScreenshotToast(
497 "error",
498 "Unable to copy screenshot path",
499 "Clipboard API unavailable.",
500 );
501 return;
502 }
503
504 void navigator.clipboard.writeText(artifact.path).then(
505 () => {
506 pathCopied = true;
507 updateScreenshotToast();
508 window.setTimeout(() => {
509 pathCopied = false;
510 updateScreenshotToast();
511 }, 2_000);
512 },
513 (error) => {
514 updateScreenshotToast(
515 "error",
516 "Unable to copy screenshot path",
517 error instanceof Error ? error.message : "An error occurred.",
518 );
519 },
520 );
521 };
522
523 const copyImage = () => {
524 void bridge.copyArtifactToClipboard(artifact.path).then(
525 () => {
526 imageCopied = true;
527 updateScreenshotToast();
528 window.setTimeout(() => {
529 imageCopied = false;
530 updateScreenshotToast();
531 }, 2_000);
532 },
533 (error) => {
534 updateScreenshotToast(
535 "error",
536 "Unable to copy screenshot",
537 error instanceof Error ? error.message : "An error occurred.",
538 );
539 },
540 );
541 };
542
543 toastId = toastManager.add(
544 stackedThreadToast({
545 type: "success",
546 title: "Screenshot saved",
547 actionProps: {
548 children: "Copy image",
549 onClick: copyImage,
550 },
551 data: {
552 additionalActions: [
553 {
554 id: "copy-path",
555 props: {
556 children: "Copy path",
557 onClick: copyPath,
558 },
559 },
560 ],
561 secondaryActionProps: {
562 ...revealAction,
563 },
564 secondaryActionVariant: "outline",
565 },
566 }),
567 );
568 },
569 (error) => {
570 toastManager.add({
571 type: "error",
572 title: "Unable to capture screenshot",
573 description: error instanceof Error ? error.message : "An error occurred.",
574 });
575 },
576 );
577 },
578 [recordingRuntimeTabId, runtimeTabId, tabId, threadRef],
579 );
580
581 const handlePickElement = useCallback(() => {
582 if (!previewBridge || !runtimeTabId) return;
583 if (pickActiveRef.current) {
584 void previewBridge.cancelPickElement(runtimeTabId).catch(() => undefined);
585 return;
586 }
587 // Snapshot whatever the user was focused on (typically the chat
588 // composer textarea or the chrome-row pick button) BEFORE main steals
589 // focus into the guest webContents. We restore it when the pick
590 // resolves so the user's typing context isn't lost — otherwise after
591 // every pick they'd have to click back into the textarea.
592 const previouslyFocused =
593 typeof document !== "undefined" ? (document.activeElement as HTMLElement | null) : null;
594 pickActiveRef.current = true;
595 setPickActive(true);
596 void (async () => {
597 try {
598 const result = await previewBridge.pickElement(runtimeTabId);
599 if (!result) return;
600 const { annotation: picked, submission, screenshotFailed = false } = result;
601 // The structured annotation is still sendable when its optional crop
602 // stalls or fails, so tell the user what they lost and keep going
603 // instead of holding the composer for an attachment that never lands.
604 // The stored copy drops the screenshot on failure, otherwise the prompt
605 // would tell the agent a crop is attached when none was sent.
606 const capture = capturePreviewAnnotationScreenshot(picked);
607 // Main reports a crop that failed or timed out on its side; the local
608 // conversion can fail too. Either way the user should hear about it.
609 const cropDropped = screenshotFailed || capture.status === "failed";
610 const annotation = capture.status === "failed" ? { ...picked, screenshot: null } : picked;
611 addPreviewAnnotation(threadRef, annotation);
612 if (cropDropped) {
613 toastManager.add(
614 stackedThreadToast({
615 type: "error",
616 title: "Could not capture the picked element",
617 // The send path reports its own outcome, so only say what this
618 // handler knows: the crop was dropped.
619 description: "The annotation was kept without the screenshot.",
620 }),
621 );
622 }
623 const screenshotFile = capture.status === "captured" ? capture.file : null;
624 const image =
625 screenshotFile && annotation.screenshot
626 ? ({
627 type: "image",
628 id: annotation.id,
629 name: screenshotFile.name,
630 mimeType: screenshotFile.type,
631 sizeBytes: screenshotFile.size,
632 previewUrl: annotation.screenshot.dataUrl,
633 file: screenshotFile,
634 } satisfies ComposerImageAttachment)
635 : null;
636 if (image) {
637 addImage(threadRef, image);
638 }
639 if (submission === "send") {
640 onSendAnnotation?.(annotation, image);
641 }
642 } catch {
643 // Picker failed (e.g. webview navigated). Treat as silent cancel.
644 } finally {
645 pickActiveRef.current = false;
646 // Avoid `setState on unmounted component` if the panel/thread closed
647 // while the pick was in flight.
648 if (isMountedRef.current) setPickActive(false);
649 // Best-effort: restore focus to whatever the user had before the
650 // pick stole it into the guest webContents. Skip if the previously-
651 // focused element was unmounted or is no longer focusable.
652 if (
653 previouslyFocused &&
654 previouslyFocused.isConnected &&
655 typeof previouslyFocused.focus === "function"
656 ) {
657 try {
658 previouslyFocused.focus({ preventScroll: true });
659 } catch {
660 // Some elements throw on .focus() (detached iframes, etc.).
661 }
662 }
663 }
664 })();
665 }, [addImage, addPreviewAnnotation, onSendAnnotation, runtimeTabId, threadRef]);
666
667 // If the active tab changes mid-pick (close, thread switch, hot restart),
668 // tell main to tear down the in-flight session AND reset our local toggle
669 // state so the button doesn't get stuck pressed against a stale tab id.
670 useEffect(() => {
671 return () => {
672 if (!pickActiveRef.current) return;
673 pickActiveRef.current = false;
674 if (previewBridge && runtimeTabId) {
675 void previewBridge.cancelPickElement(runtimeTabId).catch(() => undefined);
676 }
677 if (isMountedRef.current) setPickActive(false);
678 };
679 }, [runtimeTabId]);
680
681 // Subscribe only while visible; `toggle-panel` is owned by ChatView's
682 // URL-aware handler regardless of whether the panel is currently mounted.
683 useEffect(() => {
684 if (!visible) return;
685 return subscribePreviewAction((action) => {
686 switch (action) {
687 case "refresh":
688 handleRefresh();
689 return;
690 case "focus-url":
691 setFocusUrlNonce((value) => (value ?? 0) + 1);
692 return;
693 case "zoom-in":
694 handleZoomIn();
695 return;
696 case "zoom-out":
697 handleZoomOut();
698 return;
699 case "reset-zoom":
700 handleResetZoom();
701 return;
702 case "toggle-panel":
703 return;
704 }
705 });
706 }, [handleRefresh, handleResetZoom, handleZoomIn, handleZoomOut, visible]);
707
708 return (
709 <div
710 className="flex min-h-0 flex-1 flex-col bg-background"
711 data-thread-key={scopedThreadKey(threadRef)}
712 >
713 <PreviewChromeRow
714 url={url}
715 loading={loading}
716 canGoBack={canGoBack}
717 canGoForward={canGoForward}
718 refreshDisabled={refreshDisabled}
719 focusUrlNonce={focusUrlNonce}
720 onBack={handleBack}
721 onForward={handleForward}
722 onRefresh={handleRefresh}
723 onSubmit={(next) => void handleSubmitUrl(next)}
724 onOpenInBrowser={tabId ? handleOpenInBrowser : undefined}
725 onCapture={previewBridge && tabId ? handleCapture : undefined}
726 captureDisabled={!desktopOverlay || isUnreachable}
727 recording={recordingRuntimeTabId !== null}
728 onPictureInPicture={previewBridge && tabId ? handlePictureInPicture : undefined}
729 pictureInPicture={miniPlayerTabId === tabId}
730 pictureInPictureDisabled={!desktopOverlay?.hasWebContents || isUnreachable}
731 onPickElement={previewBridge && tabId ? handlePickElement : undefined}
732 pickActive={pickActive}
733 // Disable when there's no tab (nothing to pick on) OR the page
734 // failed to load (a React overlay covers the webview, so the
735 // user wouldn't be able to actually click anything underneath).
736 pickDisabled={!tabId || isUnreachable}
737 pickDisabledReason={
738 isUnreachable ? "Page didn't load — pick unavailable until the page renders" : undefined
739 }
740 leadingActions={
741 // Only when it differs from the default: labelling every tab
742 // "Default" would be noise on the common case, while a tab in
743 // another profile is exactly what needs calling out.
744 activeProfileId !== browserDefaults.profileId ? (
745 // Capped: profile names run to 48 characters, and an unbounded
746 // badge in this row takes its width from the URL input, the only
747 // flexible element in the compact chrome. The cap sits on the
748 // badge and the truncation on an inner span, because `Badge` is an
749 // `inline-flex` with `whitespace-nowrap` — `text-overflow` never
750 // reaches a bare text node inside it, so the name would be cut off
751 // at both ends with no ellipsis.
752 <Tooltip>
753 <TooltipTrigger render={<Badge variant="outline" className="max-w-28 shrink-0" />}>
754 <span className="truncate">{activeProfileName}</span>
755 </TooltipTrigger>
756 <TooltipPopup side="top">{activeProfileName}</TooltipPopup>
757 </Tooltip>
758 ) : null
759 }
760 trailingActions={
761 previewBridge ? (
762 <PreviewMoreMenu
763 environmentId={threadRef.environmentId}
764 profileId={activeProfileId}
765 profileName={activeProfileName}
766 tabId={runtimeTabId}
767 hasWebContents={desktopOverlay?.hasWebContents ?? false}
768 zoomFactor={desktopOverlay?.zoomFactor ?? 1}
769 colorScheme={desktopOverlay?.colorScheme ?? "system"}
770 deviceToolbarVisible={viewport._tag !== "fill"}
771 onToggleDeviceToolbar={handleToggleDeviceToolbar}
772 nativePictureInPicture={desktopOverlay?.pictureInPicture ?? false}
773 onNativePictureInPicture={handleNativePictureInPicture}
774 />
775 ) : null
776 }
777 />
778
779 <div className="relative min-h-0 flex-1 overflow-hidden">
780 {runtimeTabId && snapshot && !showEmptyState ? (
781 <BrowserSurfaceSlot
782 key={runtimeTabId}
783 tabId={runtimeTabId}
784 visible={visible && !isUnreachable}
785 className="absolute inset-0 h-full w-full"
786 />
787 ) : null}
788 {showEmptyState ? (
789 <PreviewEmptyState
790 threadRef={threadRef}
791 environmentId={threadRef.environmentId}
792 configuredUrls={configuredUrls}
793 recentEntries={recentHistoryEntries}
794 onRemoveRecent={(url) => removeUrlForThread(threadRef, url)}
795 onOpenUrl={(next) => void handleOpenServerUrl(next)}
796 />
797 ) : null}
798 {snapshot && desktopOverlay ? (
799 <ZoomIndicator zoomFactor={desktopOverlay.zoomFactor} />
800 ) : null}
801 {runtimeTabId &&
802 desktopOverlay &&
803 !showEmptyState &&
804 !isUnreachable &&
805 !activeRecordingTabIds.has(runtimeTabId) ? (
806 <AgentBrowserCursor
807 tabId={runtimeTabId}
808 zoomFactor={desktopOverlay.zoomFactor}
809 controller={controller}
810 />
811 ) : null}
812 {navStatus._tag === "LoadFailed" ? (
813 <div className="absolute inset-0 z-10 bg-background">
814 <PreviewUnreachable
815 url={navStatus.url}
816 code={navStatus.code}
817 description={navStatus.description}
818 onReload={handleRefresh}
819 />
820 </div>
821 ) : null}
822 </div>
823 </div>
824 );
825}