Open History to see the last commit
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 { usePreviewSession } from "./usePreviewSession";
54import { ZoomIndicator } from "./ZoomIndicator";
55import { AgentBrowserCursor } from "./AgentBrowserCursor";
56import {
57 findActiveBrowserRecordingRuntimeTabId,
58 isBrowserRecordingStartCancelledError,
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;
74}
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 viewport = snapshot?.viewport ?? FILL_PREVIEW_VIEWPORT;
146 const browserDefaults = useBrowserDefaults();
147 const panelRect = useBrowserSurfaceStore((state) =>
148 runtimeTabId ? (state.byTabId[runtimeTabId]?.rect ?? null) : null,
149 );
150
151 const navUrl = navStatus._tag === "Success" ? navStatus.url : null;
152 const navTitle = navStatus._tag === "Success" ? navStatus.title : null;
153 const latestHistoryUrl = recentHistoryEntries[0]?.url;
154 const threadKey = scopedThreadKey(threadRef);
155 useEffect(() => {
156 if (!navUrl || !navTitle || !latestHistoryUrl) return;
157 // Agent-driven pages only enrich an existing requested URL.
158 setTitleForThreadUrl(threadRefRef.current, navUrl, navTitle, environmentHostname);
159 // threadKey stands in for threadRef, whose identity churns on every thread update.
160 }, [environmentHostname, latestHistoryUrl, navTitle, navUrl, threadKey]);
161
162 const navigateToResolvedUrl = useCallback(
163 async (resolvedUrl: string) => {
164 if (runtimeTabId && previewBridge) {
165 // The bridge mirrors the resolved URL back to the server.
166 await previewBridge.navigate(runtimeTabId, resolvedUrl);
167 rememberPreviewUrl(threadRef, resolvedUrl);
168 return true;
169 }
170 const result = await openPreviewSession({ openPreview: open, threadRef, url: resolvedUrl });
171 return result._tag === "Success";
172 },
173 [open, runtimeTabId, threadRef],
174 );
175
176 const handleSubmitUrl = useCallback(
177 async (next: string) => {
178 try {
179 const normalized = normalizePreviewUrl(next);
180 if (await navigateToResolvedUrl(normalized)) {
181 recordVisitForThread(threadRef, normalized);
182 }
183 } catch {
184 // Server-side `failed` event renders the unreachable view.
185 }
186 },
187 [navigateToResolvedUrl, threadRef],
188 );
189
190 const handleOpenServerUrl = useCallback(
191 async (next: string) => {
192 try {
193 const resolved = resolveDiscoveredServerUrl(threadRef.environmentId, next);
194 if (await navigateToResolvedUrl(resolved)) {
195 recordVisitForThread(threadRef, next);
196 }
197 } catch {
198 // Server-side `failed` event renders the unreachable view.
199 }
200 },
201 [navigateToResolvedUrl, threadRef],
202 );
203
204 const handleRefresh = useCallback(() => {
205 if (previewBridge && runtimeTabId) void previewBridge.refresh(runtimeTabId);
206 }, [runtimeTabId]);
207
208 const handleZoomIn = useCallback(() => {
209 if (previewBridge && runtimeTabId) void previewBridge.zoomIn(runtimeTabId);
210 }, [runtimeTabId]);
211
212 const handleZoomOut = useCallback(() => {
213 if (previewBridge && runtimeTabId) void previewBridge.zoomOut(runtimeTabId);
214 }, [runtimeTabId]);
215
216 const handleResetZoom = useCallback(() => {
217 if (previewBridge && runtimeTabId) void previewBridge.resetZoom(runtimeTabId);
218 }, [runtimeTabId]);
219
220 const handleViewportChange = useCallback(
221 async (nextViewport: PreviewViewportSetting) => {
222 if (!tabId) return;
223 const result = await resize({
224 environmentId: threadRef.environmentId,
225 input: {
226 threadId: threadRef.threadId,
227 tabId,
228 viewport: nextViewport,
229 },
230 });
231 if (result._tag === "Failure") {
232 const error = squashAtomCommandFailure(result);
233 toastManager.add({
234 type: "error",
235 title: "Unable to resize browser viewport",
236 description: error instanceof Error ? error.message : "An error occurred.",
237 });
238 throw error;
239 }
240 updatePreviewServerSnapshot(threadRef, result.value);
241 },
242 [resize, tabId, threadRef],
243 );
244
245 const handleToggleDeviceToolbar = () => {
246 if (!runtimeTabId) return;
247 if (viewport._tag !== "fill") {
248 void commitBrowserViewportChange(runtimeTabId, FILL_PREVIEW_VIEWPORT).catch(() => undefined);
249 return;
250 }
251
252 void commitBrowserViewportChange(
253 runtimeTabId,
254 browserResponsiveViewportForToggle({
255 defaults: browserDefaults,
256 panelRect,
257 zoomFactor: desktopOverlay?.zoomFactor,
258 }),
259 ).catch(() => undefined);
260 };
261
262 useEffect(() => {
263 if (!runtimeTabId) return;
264 return subscribeBrowserViewportChange(runtimeTabId, handleViewportChange);
265 }, [handleViewportChange, runtimeTabId]);
266
267 const handleBack = useCallback(() => {
268 if (previewBridge && runtimeTabId) void previewBridge.goBack(runtimeTabId);
269 }, [runtimeTabId]);
270
271 const handleForward = useCallback(() => {
272 if (previewBridge && runtimeTabId) void previewBridge.goForward(runtimeTabId);
273 }, [runtimeTabId]);
274
275 const handleOpenInBrowser = useCallback(() => {
276 if (!localApi || !url) return;
277 void localApi.shell.openExternal(url).catch(() => undefined);
278 }, [url]);
279
280 const handlePictureInPicture = useCallback(() => {
281 if (!tabId) return;
282 if (miniPlayer?.tabId === tabId) {
283 usePreviewMiniPlayerStore.getState().close(threadRef);
284 return;
285 }
286 usePreviewMiniPlayerStore.getState().open(threadRef, tabId);
287 useRightPanelStore.getState().close(threadRef);
288 }, [miniPlayer?.tabId, tabId, threadRef]);
289
290 const handleNativePictureInPicture = useCallback(() => {
291 if (!previewBridge || !runtimeTabId) return;
292 const operation = desktopOverlay?.pictureInPicture
293 ? previewBridge.pictureInPicture.close
294 : previewBridge.pictureInPicture.open;
295 void operation(runtimeTabId).catch((error) => {
296 toastManager.add({
297 type: "error",
298 title: "Unable to update popped-out preview",
299 description: error instanceof Error ? error.message : "An error occurred.",
300 });
301 });
302 }, [desktopOverlay?.pictureInPicture, runtimeTabId]);
303
304 const handleCapture = useCallback(
305 (record: boolean) => {
306 if (!previewBridge || !runtimeTabId || !tabId) return;
307 const bridge = previewBridge;
308 if (recordingRuntimeTabId) {
309 void stopBrowserRecording(recordingRuntimeTabId).then(
310 (artifact) => {
311 if (!artifact) return;
312 let pathCopied = false;
313 let toastId: ReturnType<typeof toastManager.add>;
314
315 const copyPath = () => {
316 if (!navigator.clipboard?.writeText) {
317 toastManager.update(
318 toastId,
319 stackedThreadToast({
320 type: "error",
321 title: "Unable to copy recording path",
322 description: "Clipboard API unavailable.",
323 actionProps: revealAction,
324 }),
325 );
326 return;
327 }
328
329 void navigator.clipboard.writeText(artifact.path).then(
330 () => {
331 pathCopied = true;
332 updateRecordingToast();
333 window.setTimeout(() => {
334 pathCopied = false;
335 updateRecordingToast();
336 }, 2_000);
337 },
338 (error) => {
339 toastManager.update(
340 toastId,
341 stackedThreadToast({
342 type: "error",
343 title: "Unable to copy recording path",
344 description: error instanceof Error ? error.message : "An error occurred.",
345 actionProps: revealAction,
346 }),
347 );
348 },
349 );
350 };
351
352 const revealAction = {
353 children: revealInFileExplorerLabel(navigator.platform),
354 onClick: () => void bridge.revealArtifact(artifact.path),
355 };
356 const updateRecordingToast = () => {
357 toastManager.update(
358 toastId,
359 stackedThreadToast({
360 type: "success",
361 title: "Recording saved",
362 actionProps: revealAction,
363 data: {
364 secondaryActionProps: {
365 children: pathCopied ? "Copied!" : "Copy path",
366 disabled: pathCopied,
367 onClick: copyPath,
368 },
369 secondaryActionVariant: "outline",
370 },
371 }),
372 );
373 };
374
375 toastId = toastManager.add(
376 stackedThreadToast({
377 type: "success",
378 title: "Recording saved",
379 actionProps: revealAction,
380 data: {
381 secondaryActionProps: {
382 children: "Copy path",
383 onClick: copyPath,
384 },
385 secondaryActionVariant: "outline",
386 },
387 }),
388 );
389 },
390 (error) => {
391 toastManager.add({
392 type: "error",
393 title: "Unable to stop recording",
394 description: error instanceof Error ? error.message : "An error occurred.",
395 });
396 },
397 );
398 return;
399 }
400 if (record) {
401 void startBrowserRecording(runtimeTabId, threadRef, tabId).catch((error) => {
402 const description = error instanceof Error ? error.message : "An error occurred.";
403 if (isBrowserRecordingStartCancelledError(error)) return;
404 toastManager.add({
405 type: "error",
406 title: "Unable to start recording",
407 description,
408 });
409 });
410 return;
411 }
412 void bridge.captureScreenshot(runtimeTabId).then(
413 (artifact) => {
414 const revealAction = {
415 children: revealInFileExplorerLabel(navigator.platform),
416 onClick: () => void bridge.revealArtifact(artifact.path),
417 };
418 let pathCopied = false;
419 let imageCopied = false;
420 let toastId: ReturnType<typeof toastManager.add>;
421
422 const updateScreenshotToast = (
423 type: "success" | "error" = "success",
424 title = "Screenshot saved",
425 description?: string,
426 ) => {
427 toastManager.update(
428 toastId,
429 stackedThreadToast({
430 type,
431 title,
432 description,
433 actionProps: {
434 children: imageCopied ? "Copied!" : "Copy image",
435 disabled: imageCopied,
436 onClick: copyImage,
437 },
438 data: {
439 additionalActions: [
440 {
441 id: "copy-path",
442 props: {
443 children: pathCopied ? "Copied!" : "Copy path",
444 disabled: pathCopied,
445 onClick: copyPath,
446 },
447 },
448 ],
449 secondaryActionProps: {
450 ...revealAction,
451 },
452 secondaryActionVariant: "outline",
453 },
454 }),
455 );
456 };
457
458 const copyPath = () => {
459 if (!navigator.clipboard?.writeText) {
460 updateScreenshotToast(
461 "error",
462 "Unable to copy screenshot path",
463 "Clipboard API unavailable.",
464 );
465 return;
466 }
467
468 void navigator.clipboard.writeText(artifact.path).then(
469 () => {
470 pathCopied = true;
471 updateScreenshotToast();
472 window.setTimeout(() => {
473 pathCopied = false;
474 updateScreenshotToast();
475 }, 2_000);
476 },
477 (error) => {
478 updateScreenshotToast(
479 "error",
480 "Unable to copy screenshot path",
481 error instanceof Error ? error.message : "An error occurred.",
482 );
483 },
484 );
485 };
486
487 const copyImage = () => {
488 void bridge.copyArtifactToClipboard(artifact.path).then(
489 () => {
490 imageCopied = true;
491 updateScreenshotToast();
492 window.setTimeout(() => {
493 imageCopied = false;
494 updateScreenshotToast();
495 }, 2_000);
496 },
497 (error) => {
498 updateScreenshotToast(
499 "error",
500 "Unable to copy screenshot",
501 error instanceof Error ? error.message : "An error occurred.",
502 );
503 },
504 );
505 };
506
507 toastId = toastManager.add(
508 stackedThreadToast({
509 type: "success",
510 title: "Screenshot saved",
511 actionProps: {
512 children: "Copy image",
513 onClick: copyImage,
514 },
515 data: {
516 additionalActions: [
517 {
518 id: "copy-path",
519 props: {
520 children: "Copy path",
521 onClick: copyPath,
522 },
523 },
524 ],
525 secondaryActionProps: {
526 ...revealAction,
527 },
528 secondaryActionVariant: "outline",
529 },
530 }),
531 );
532 },
533 (error) => {
534 toastManager.add({
535 type: "error",
536 title: "Unable to capture screenshot",
537 description: error instanceof Error ? error.message : "An error occurred.",
538 });
539 },
540 );
541 },
542 [recordingRuntimeTabId, runtimeTabId, tabId, threadRef],
543 );
544
545 const handlePickElement = useCallback(() => {
546 if (!previewBridge || !runtimeTabId) return;
547 if (pickActiveRef.current) {
548 void previewBridge.cancelPickElement(runtimeTabId).catch(() => undefined);
549 return;
550 }
551 // Snapshot whatever the user was focused on (typically the chat
552 // composer textarea or the chrome-row pick button) BEFORE main steals
553 // focus into the guest webContents. We restore it when the pick
554 // resolves so the user's typing context isn't lost — otherwise after
555 // every pick they'd have to click back into the textarea.
556 const previouslyFocused =
557 typeof document !== "undefined" ? (document.activeElement as HTMLElement | null) : null;
558 pickActiveRef.current = true;
559 setPickActive(true);
560 void (async () => {
561 try {
562 const result = await previewBridge.pickElement(runtimeTabId);
563 if (!result) return;
564 const { annotation, submission } = result;
565 addPreviewAnnotation(threadRef, annotation);
566 let screenshotFile: File | null = null;
567 try {
568 screenshotFile = await previewAnnotationScreenshotFile(annotation);
569 } catch {
570 // The structured annotation is still sendable when converting its
571 // optional screenshot into a composer attachment fails.
572 }
573 const image =
574 screenshotFile && annotation.screenshot
575 ? ({
576 type: "image",
577 id: annotation.id,
578 name: screenshotFile.name,
579 mimeType: screenshotFile.type,
580 sizeBytes: screenshotFile.size,
581 previewUrl: annotation.screenshot.dataUrl,
582 file: screenshotFile,
583 } satisfies ComposerImageAttachment)
584 : null;
585 if (image) {
586 addImage(threadRef, image);
587 }
588 if (submission === "send") {
589 onSendAnnotation?.(annotation, image);
590 }
591 } catch {
592 // Picker failed (e.g. webview navigated). Treat as silent cancel.
593 } finally {
594 pickActiveRef.current = false;
595 // Avoid `setState on unmounted component` if the panel/thread closed
596 // while the pick was in flight.
597 if (isMountedRef.current) setPickActive(false);
598 // Best-effort: restore focus to whatever the user had before the
599 // pick stole it into the guest webContents. Skip if the previously-
600 // focused element was unmounted or is no longer focusable.
601 if (
602 previouslyFocused &&
603 previouslyFocused.isConnected &&
604 typeof previouslyFocused.focus === "function"
605 ) {
606 try {
607 previouslyFocused.focus({ preventScroll: true });
608 } catch {
609 // Some elements throw on .focus() (detached iframes, etc.).
610 }
611 }
612 }
613 })();
614 }, [addImage, addPreviewAnnotation, onSendAnnotation, runtimeTabId, threadRef]);
615
616 // If the active tab changes mid-pick (close, thread switch, hot restart),
617 // tell main to tear down the in-flight session AND reset our local toggle
618 // state so the button doesn't get stuck pressed against a stale tab id.
619 useEffect(() => {
620 return () => {
621 if (!pickActiveRef.current) return;
622 pickActiveRef.current = false;
623 if (previewBridge && runtimeTabId) {
624 void previewBridge.cancelPickElement(runtimeTabId).catch(() => undefined);
625 }
626 if (isMountedRef.current) setPickActive(false);
627 };
628 }, [runtimeTabId]);
629
630 // Subscribe only while visible; `toggle-panel` is owned by ChatView's
631 // URL-aware handler regardless of whether the panel is currently mounted.
632 useEffect(() => {
633 if (!visible) return;
634 return subscribePreviewAction((action) => {
635 switch (action) {
636 case "refresh":
637 handleRefresh();
638 return;
639 case "focus-url":
640 setFocusUrlNonce((value) => (value ?? 0) + 1);
641 return;
642 case "zoom-in":
643 handleZoomIn();
644 return;
645 case "zoom-out":
646 handleZoomOut();
647 return;
648 case "reset-zoom":
649 handleResetZoom();
650 return;
651 case "toggle-panel":
652 return;
653 }
654 });
655 }, [handleRefresh, handleResetZoom, handleZoomIn, handleZoomOut, visible]);
656
657 return (
658 <div
659 className="flex min-h-0 flex-1 flex-col bg-background"
660 data-thread-key={scopedThreadKey(threadRef)}
661 >
662 <PreviewChromeRow
663 url={url}
664 loading={loading}
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 );
752}