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 { resolveResponsiveBrowserViewportSize } from "~/browser/browserViewportLayout";
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;
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 loadProgress = useLoadingProgress(loading);
146 const viewport = snapshot?.viewport ?? FILL_PREVIEW_VIEWPORT;
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 const responsiveSize = panelRect
253 ? resolveResponsiveBrowserViewportSize(panelRect, desktopOverlay?.zoomFactor)
254 : { width: 1024, height: 768 };
255 void commitBrowserViewportChange(runtimeTabId, { _tag: "freeform", ...responsiveSize }).catch(
256 () => undefined,
257 );
258 };
259
260 useEffect(() => {
261 if (!runtimeTabId) return;
262 return subscribeBrowserViewportChange(runtimeTabId, handleViewportChange);
263 }, [handleViewportChange, runtimeTabId]);
264
265 const handleBack = useCallback(() => {
266 if (previewBridge && runtimeTabId) void previewBridge.goBack(runtimeTabId);
267 }, [runtimeTabId]);
268
269 const handleForward = useCallback(() => {
270 if (previewBridge && runtimeTabId) void previewBridge.goForward(runtimeTabId);
271 }, [runtimeTabId]);
272
273 const handleOpenInBrowser = useCallback(() => {
274 if (!localApi || !url) return;
275 void localApi.shell.openExternal(url).catch(() => undefined);
276 }, [url]);
277
278 const handlePictureInPicture = useCallback(() => {
279 if (!tabId) return;
280 if (miniPlayer?.tabId === tabId) {
281 usePreviewMiniPlayerStore.getState().close(threadRef);
282 return;
283 }
284 usePreviewMiniPlayerStore.getState().open(threadRef, tabId);
285 useRightPanelStore.getState().close(threadRef);
286 }, [miniPlayer?.tabId, tabId, threadRef]);
287
288 const handleNativePictureInPicture = useCallback(() => {
289 if (!previewBridge || !runtimeTabId) return;
290 const operation = desktopOverlay?.pictureInPicture
291 ? previewBridge.pictureInPicture.close
292 : previewBridge.pictureInPicture.open;
293 void operation(runtimeTabId).catch((error) => {
294 toastManager.add({
295 type: "error",
296 title: "Unable to update popped-out preview",
297 description: error instanceof Error ? error.message : "An error occurred.",
298 });
299 });
300 }, [desktopOverlay?.pictureInPicture, runtimeTabId]);
301
302 const handleCapture = useCallback(
303 (record: boolean) => {
304 if (!previewBridge || !runtimeTabId || !tabId) return;
305 const bridge = previewBridge;
306 if (recordingRuntimeTabId) {
307 void stopBrowserRecording(recordingRuntimeTabId).then(
308 (artifact) => {
309 if (!artifact) return;
310 let pathCopied = false;
311 let toastId: ReturnType<typeof toastManager.add>;
312
313 const copyPath = () => {
314 if (!navigator.clipboard?.writeText) {
315 toastManager.update(
316 toastId,
317 stackedThreadToast({
318 type: "error",
319 title: "Unable to copy recording path",
320 description: "Clipboard API unavailable.",
321 actionProps: revealAction,
322 }),
323 );
324 return;
325 }
326
327 void navigator.clipboard.writeText(artifact.path).then(
328 () => {
329 pathCopied = true;
330 updateRecordingToast();
331 window.setTimeout(() => {
332 pathCopied = false;
333 updateRecordingToast();
334 }, 2_000);
335 },
336 (error) => {
337 toastManager.update(
338 toastId,
339 stackedThreadToast({
340 type: "error",
341 title: "Unable to copy recording path",
342 description: error instanceof Error ? error.message : "An error occurred.",
343 actionProps: revealAction,
344 }),
345 );
346 },
347 );
348 };
349
350 const revealAction = {
351 children: revealInFileExplorerLabel(navigator.platform),
352 onClick: () => void bridge.revealArtifact(artifact.path),
353 };
354 const updateRecordingToast = () => {
355 toastManager.update(
356 toastId,
357 stackedThreadToast({
358 type: "success",
359 title: "Recording saved",
360 actionProps: revealAction,
361 data: {
362 secondaryActionProps: {
363 children: pathCopied ? "Copied!" : "Copy path",
364 disabled: pathCopied,
365 onClick: copyPath,
366 },
367 secondaryActionVariant: "outline",
368 },
369 }),
370 );
371 };
372
373 toastId = toastManager.add(
374 stackedThreadToast({
375 type: "success",
376 title: "Recording saved",
377 actionProps: revealAction,
378 data: {
379 secondaryActionProps: {
380 children: "Copy path",
381 onClick: copyPath,
382 },
383 secondaryActionVariant: "outline",
384 },
385 }),
386 );
387 },
388 (error) => {
389 toastManager.add({
390 type: "error",
391 title: "Unable to stop recording",
392 description: error instanceof Error ? error.message : "An error occurred.",
393 });
394 },
395 );
396 return;
397 }
398 if (record) {
399 void startBrowserRecording(runtimeTabId, threadRef, tabId).catch((error) => {
400 toastManager.add({
401 type: "error",
402 title: "Unable to start recording",
403 description: error instanceof Error ? error.message : "An error occurred.",
404 });
405 });
406 return;
407 }
408 void bridge.captureScreenshot(runtimeTabId).then(
409 (artifact) => {
410 const revealAction = {
411 children: revealInFileExplorerLabel(navigator.platform),
412 onClick: () => void bridge.revealArtifact(artifact.path),
413 };
414 let pathCopied = false;
415 let imageCopied = false;
416 let toastId: ReturnType<typeof toastManager.add>;
417
418 const updateScreenshotToast = (
419 type: "success" | "error" = "success",
420 title = "Screenshot saved",
421 description?: string,
422 ) => {
423 toastManager.update(
424 toastId,
425 stackedThreadToast({
426 type,
427 title,
428 description,
429 actionProps: {
430 children: imageCopied ? "Copied!" : "Copy image",
431 disabled: imageCopied,
432 onClick: copyImage,
433 },
434 data: {
435 additionalActions: [
436 {
437 id: "copy-path",
438 props: {
439 children: pathCopied ? "Copied!" : "Copy path",
440 disabled: pathCopied,
441 onClick: copyPath,
442 },
443 },
444 ],
445 secondaryActionProps: {
446 ...revealAction,
447 },
448 secondaryActionVariant: "outline",
449 },
450 }),
451 );
452 };
453
454 const copyPath = () => {
455 if (!navigator.clipboard?.writeText) {
456 updateScreenshotToast(
457 "error",
458 "Unable to copy screenshot path",
459 "Clipboard API unavailable.",
460 );
461 return;
462 }
463
464 void navigator.clipboard.writeText(artifact.path).then(
465 () => {
466 pathCopied = true;
467 updateScreenshotToast();
468 window.setTimeout(() => {
469 pathCopied = false;
470 updateScreenshotToast();
471 }, 2_000);
472 },
473 (error) => {
474 updateScreenshotToast(
475 "error",
476 "Unable to copy screenshot path",
477 error instanceof Error ? error.message : "An error occurred.",
478 );
479 },
480 );
481 };
482
483 const copyImage = () => {
484 void bridge.copyArtifactToClipboard(artifact.path).then(
485 () => {
486 imageCopied = true;
487 updateScreenshotToast();
488 window.setTimeout(() => {
489 imageCopied = false;
490 updateScreenshotToast();
491 }, 2_000);
492 },
493 (error) => {
494 updateScreenshotToast(
495 "error",
496 "Unable to copy screenshot",
497 error instanceof Error ? error.message : "An error occurred.",
498 );
499 },
500 );
501 };
502
503 toastId = toastManager.add(
504 stackedThreadToast({
505 type: "success",
506 title: "Screenshot saved",
507 actionProps: {
508 children: "Copy image",
509 onClick: copyImage,
510 },
511 data: {
512 additionalActions: [
513 {
514 id: "copy-path",
515 props: {
516 children: "Copy path",
517 onClick: copyPath,
518 },
519 },
520 ],
521 secondaryActionProps: {
522 ...revealAction,
523 },
524 secondaryActionVariant: "outline",
525 },
526 }),
527 );
528 },
529 (error) => {
530 toastManager.add({
531 type: "error",
532 title: "Unable to capture screenshot",
533 description: error instanceof Error ? error.message : "An error occurred.",
534 });
535 },
536 );
537 },
538 [recordingRuntimeTabId, runtimeTabId, tabId, threadRef],
539 );
540
541 const handlePickElement = useCallback(() => {
542 if (!previewBridge || !runtimeTabId) return;
543 if (pickActiveRef.current) {
544 void previewBridge.cancelPickElement(runtimeTabId).catch(() => undefined);
545 return;
546 }
547 // Snapshot whatever the user was focused on (typically the chat
548 // composer textarea or the chrome-row pick button) BEFORE main steals
549 // focus into the guest webContents. We restore it when the pick
550 // resolves so the user's typing context isn't lost — otherwise after
551 // every pick they'd have to click back into the textarea.
552 const previouslyFocused =
553 typeof document !== "undefined" ? (document.activeElement as HTMLElement | null) : null;
554 pickActiveRef.current = true;
555 setPickActive(true);
556 void (async () => {
557 try {
558 const result = await previewBridge.pickElement(runtimeTabId);
559 if (!result) return;
560 const { annotation, submission } = result;
561 addPreviewAnnotation(threadRef, annotation);
562 let screenshotFile: File | null = null;
563 try {
564 screenshotFile = await previewAnnotationScreenshotFile(annotation);
565 } catch {
566 // The structured annotation is still sendable when converting its
567 // optional screenshot into a composer attachment fails.
568 }
569 const image =
570 screenshotFile && annotation.screenshot
571 ? ({
572 type: "image",
573 id: annotation.id,
574 name: screenshotFile.name,
575 mimeType: screenshotFile.type,
576 sizeBytes: screenshotFile.size,
577 previewUrl: annotation.screenshot.dataUrl,
578 file: screenshotFile,
579 } satisfies ComposerImageAttachment)
580 : null;
581 if (image) {
582 addImage(threadRef, image);
583 }
584 if (submission === "send") {
585 onSendAnnotation?.(annotation, image);
586 }
587 } catch {
588 // Picker failed (e.g. webview navigated). Treat as silent cancel.
589 } finally {
590 pickActiveRef.current = false;
591 // Avoid `setState on unmounted component` if the panel/thread closed
592 // while the pick was in flight.
593 if (isMountedRef.current) setPickActive(false);
594 // Best-effort: restore focus to whatever the user had before the
595 // pick stole it into the guest webContents. Skip if the previously-
596 // focused element was unmounted or is no longer focusable.
597 if (
598 previouslyFocused &&
599 previouslyFocused.isConnected &&
600 typeof previouslyFocused.focus === "function"
601 ) {
602 try {
603 previouslyFocused.focus({ preventScroll: true });
604 } catch {
605 // Some elements throw on .focus() (detached iframes, etc.).
606 }
607 }
608 }
609 })();
610 }, [addImage, addPreviewAnnotation, onSendAnnotation, runtimeTabId, threadRef]);
611
612 // If the active tab changes mid-pick (close, thread switch, hot restart),
613 // tell main to tear down the in-flight session AND reset our local toggle
614 // state so the button doesn't get stuck pressed against a stale tab id.
615 useEffect(() => {
616 return () => {
617 if (!pickActiveRef.current) return;
618 pickActiveRef.current = false;
619 if (previewBridge && runtimeTabId) {
620 void previewBridge.cancelPickElement(runtimeTabId).catch(() => undefined);
621 }
622 if (isMountedRef.current) setPickActive(false);
623 };
624 }, [runtimeTabId]);
625
626 // Subscribe only while visible; `toggle-panel` is owned by ChatView's
627 // URL-aware handler regardless of whether the panel is currently mounted.
628 useEffect(() => {
629 if (!visible) return;
630 return subscribePreviewAction((action) => {
631 switch (action) {
632 case "refresh":
633 handleRefresh();
634 return;
635 case "focus-url":
636 setFocusUrlNonce((value) => (value ?? 0) + 1);
637 return;
638 case "zoom-in":
639 handleZoomIn();
640 return;
641 case "zoom-out":
642 handleZoomOut();
643 return;
644 case "reset-zoom":
645 handleResetZoom();
646 return;
647 case "toggle-panel":
648 return;
649 }
650 });
651 }, [handleRefresh, handleResetZoom, handleZoomIn, handleZoomOut, visible]);
652
653 return (
654 <div
655 className="flex min-h-0 flex-1 flex-col bg-background"
656 data-thread-key={scopedThreadKey(threadRef)}
657 >
658 <PreviewChromeRow
659 url={url}
660 loading={loading}
661 loadProgress={loadProgress}
662 canGoBack={canGoBack}
663 canGoForward={canGoForward}
664 refreshDisabled={refreshDisabled}
665 focusUrlNonce={focusUrlNonce}
666 onBack={handleBack}
667 onForward={handleForward}
668 onRefresh={handleRefresh}
669 onSubmit={(next) => void handleSubmitUrl(next)}
670 onOpenInBrowser={tabId ? handleOpenInBrowser : undefined}
671 onCapture={previewBridge && tabId ? handleCapture : undefined}
672 captureDisabled={!desktopOverlay || isUnreachable}
673 recording={recordingRuntimeTabId !== null}
674 onPictureInPicture={previewBridge && tabId ? handlePictureInPicture : undefined}
675 pictureInPicture={miniPlayer?.tabId === tabId}
676 pictureInPictureDisabled={!desktopOverlay?.hasWebContents || isUnreachable}
677 onPickElement={previewBridge && tabId ? handlePickElement : undefined}
678 pickActive={pickActive}
679 // Disable when there's no tab (nothing to pick on) OR the page
680 // failed to load (a React overlay covers the webview, so the
681 // user wouldn't be able to actually click anything underneath).
682 pickDisabled={!tabId || isUnreachable}
683 pickDisabledReason={
684 isUnreachable ? "Page didn't load — pick unavailable until the page renders" : undefined
685 }
686 trailingActions={
687 previewBridge ? (
688 <PreviewMoreMenu
689 tabId={runtimeTabId}
690 hasWebContents={desktopOverlay?.hasWebContents ?? false}
691 zoomFactor={desktopOverlay?.zoomFactor ?? 1}
692 colorScheme={desktopOverlay?.colorScheme ?? "system"}
693 deviceToolbarVisible={viewport._tag !== "fill"}
694 onToggleDeviceToolbar={handleToggleDeviceToolbar}
695 nativePictureInPicture={desktopOverlay?.pictureInPicture ?? false}
696 onNativePictureInPicture={handleNativePictureInPicture}
697 />
698 ) : null
699 }
700 />
701
702 <div className="relative min-h-0 flex-1 overflow-hidden">
703 {runtimeTabId && snapshot && !showEmptyState ? (
704 <BrowserSurfaceSlot
705 key={runtimeTabId}
706 tabId={runtimeTabId}
707 visible={visible && !isUnreachable}
708 className="absolute inset-0 h-full w-full"
709 />
710 ) : null}
711 {showEmptyState ? (
712 <PreviewEmptyState
713 environmentId={threadRef.environmentId}
714 configuredUrls={configuredUrls}
715 recentlySeenUrls={previewState.recentlySeenUrls}
716 recentEntries={recentHistoryEntries}
717 onRemoveRecent={(url) => removeUrlForThread(threadRef, url)}
718 onOpenUrl={(next) => void handleOpenServerUrl(next)}
719 />
720 ) : null}
721 {snapshot && desktopOverlay ? (
722 <ZoomIndicator zoomFactor={desktopOverlay.zoomFactor} />
723 ) : null}
724 {runtimeTabId && desktopOverlay && !showEmptyState && !isUnreachable ? (
725 <AgentBrowserCursor
726 tabId={runtimeTabId}
727 zoomFactor={desktopOverlay.zoomFactor}
728 controller={controller}
729 />
730 ) : null}
731 {controller !== "none" ? (
732 <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">
733 {controller === "agent" ? "Agent controlling browser" : "Human control"}
734 </div>
735 ) : null}
736 {navStatus._tag === "LoadFailed" ? (
737 <div className="absolute inset-0 z-10 bg-background">
738 <PreviewUnreachable
739 url={navStatus.url}
740 code={navStatus.code}
741 description={navStatus.description}
742 onReload={handleRefresh}
743 />
744 </div>
745 ) : null}
746 </div>
747 </div>
748 );
749}