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