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