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

PreviewView.tsx

793 lines29.5 KB

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