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

PreviewView.tsx

752 lines27.3 KB

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