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

PreviewView.tsx

808 lines30.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 { capturePreviewAnnotationScreenshot } 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: picked, submission, screenshotFailed = false } = result;
583 // The structured annotation is still sendable when its optional crop
584 // stalls or fails, so tell the user what they lost and keep going
585 // instead of holding the composer for an attachment that never lands.
586 // The stored copy drops the screenshot on failure, otherwise the prompt
587 // would tell the agent a crop is attached when none was sent.
588 const capture = await capturePreviewAnnotationScreenshot(picked);
589 // Main reports a crop that failed or timed out on its side; the local
590 // conversion can fail too. Either way the user should hear about it.
591 const cropDropped = screenshotFailed || capture.status === "failed";
592 const annotation = capture.status === "failed" ? { ...picked, screenshot: null } : picked;
593 addPreviewAnnotation(threadRef, annotation);
594 if (cropDropped) {
595 toastManager.add(
596 stackedThreadToast({
597 type: "error",
598 title: "Could not capture the picked element",
599 // The send path reports its own outcome, so only say what this
600 // handler knows: the crop was dropped.
601 description: "The annotation was kept without the screenshot.",
602 }),
603 );
604 }
605 const screenshotFile = capture.status === "captured" ? capture.file : null;
606 const image =
607 screenshotFile && annotation.screenshot
608 ? ({
609 type: "image",
610 id: annotation.id,
611 name: screenshotFile.name,
612 mimeType: screenshotFile.type,
613 sizeBytes: screenshotFile.size,
614 previewUrl: annotation.screenshot.dataUrl,
615 file: screenshotFile,
616 } satisfies ComposerImageAttachment)
617 : null;
618 if (image) {
619 addImage(threadRef, image);
620 }
621 if (submission === "send") {
622 onSendAnnotation?.(annotation, image);
623 }
624 } catch {
625 // Picker failed (e.g. webview navigated). Treat as silent cancel.
626 } finally {
627 pickActiveRef.current = false;
628 // Avoid `setState on unmounted component` if the panel/thread closed
629 // while the pick was in flight.
630 if (isMountedRef.current) setPickActive(false);
631 // Best-effort: restore focus to whatever the user had before the
632 // pick stole it into the guest webContents. Skip if the previously-
633 // focused element was unmounted or is no longer focusable.
634 if (
635 previouslyFocused &&
636 previouslyFocused.isConnected &&
637 typeof previouslyFocused.focus === "function"
638 ) {
639 try {
640 previouslyFocused.focus({ preventScroll: true });
641 } catch {
642 // Some elements throw on .focus() (detached iframes, etc.).
643 }
644 }
645 }
646 })();
647 }, [addImage, addPreviewAnnotation, onSendAnnotation, runtimeTabId, threadRef]);
648​
649 // If the active tab changes mid-pick (close, thread switch, hot restart),
650 // tell main to tear down the in-flight session AND reset our local toggle
651 // state so the button doesn't get stuck pressed against a stale tab id.
652 useEffect(() => {
653 return () => {
654 if (!pickActiveRef.current) return;
655 pickActiveRef.current = false;
656 if (previewBridge && runtimeTabId) {
657 void previewBridge.cancelPickElement(runtimeTabId).catch(() => undefined);
658 }
659 if (isMountedRef.current) setPickActive(false);
660 };
661 }, [runtimeTabId]);
662​
663 // Subscribe only while visible; `toggle-panel` is owned by ChatView's
664 // URL-aware handler regardless of whether the panel is currently mounted.
665 useEffect(() => {
666 if (!visible) return;
667 return subscribePreviewAction((action) => {
668 switch (action) {
669 case "refresh":
670 handleRefresh();
671 return;
672 case "focus-url":
673 setFocusUrlNonce((value) => (value ?? 0) + 1);
674 return;
675 case "zoom-in":
676 handleZoomIn();
677 return;
678 case "zoom-out":
679 handleZoomOut();
680 return;
681 case "reset-zoom":
682 handleResetZoom();
683 return;
684 case "toggle-panel":
685 return;
686 }
687 });
688 }, [handleRefresh, handleResetZoom, handleZoomIn, handleZoomOut, visible]);
689​
690 return (
691 <div
692 className="flex min-h-0 flex-1 flex-col bg-background"
693 data-thread-key={scopedThreadKey(threadRef)}
694 >
695 <PreviewChromeRow
696 url={url}
697 loading={loading}
698 canGoBack={canGoBack}
699 canGoForward={canGoForward}
700 refreshDisabled={refreshDisabled}
701 focusUrlNonce={focusUrlNonce}
702 onBack={handleBack}
703 onForward={handleForward}
704 onRefresh={handleRefresh}
705 onSubmit={(next) => void handleSubmitUrl(next)}
706 onOpenInBrowser={tabId ? handleOpenInBrowser : undefined}
707 onCapture={previewBridge && tabId ? handleCapture : undefined}
708 captureDisabled={!desktopOverlay || isUnreachable}
709 recording={recordingRuntimeTabId !== null}
710 onPictureInPicture={previewBridge && tabId ? handlePictureInPicture : undefined}
711 pictureInPicture={miniPlayer?.tabId === tabId}
712 pictureInPictureDisabled={!desktopOverlay?.hasWebContents || isUnreachable}
713 onPickElement={previewBridge && tabId ? handlePickElement : undefined}
714 pickActive={pickActive}
715 // Disable when there's no tab (nothing to pick on) OR the page
716 // failed to load (a React overlay covers the webview, so the
717 // user wouldn't be able to actually click anything underneath).
718 pickDisabled={!tabId || isUnreachable}
719 pickDisabledReason={
720 isUnreachable ? "Page didn't load — pick unavailable until the page renders" : undefined
721 }
722 leadingActions={
723 // Only when it differs from the default: labelling every tab
724 // "Default" would be noise on the common case, while a tab in
725 // another profile is exactly what needs calling out.
726 activeProfileId !== browserDefaults.profileId ? (
727 // Capped: profile names run to 48 characters, and an unbounded
728 // badge in this row takes its width from the URL input, the only
729 // flexible element in the compact chrome. The cap sits on the
730 // badge and the truncation on an inner span, because `Badge` is an
731 // `inline-flex` with `whitespace-nowrap` — `text-overflow` never
732 // reaches a bare text node inside it, so the name would be cut off
733 // at both ends with no ellipsis.
734 <Tooltip>
735 <TooltipTrigger render={<Badge variant="outline" className="max-w-28 shrink-0" />}>
736 <span className="truncate">{activeProfileName}</span>
737 </TooltipTrigger>
738 <TooltipPopup side="top">{activeProfileName}</TooltipPopup>
739 </Tooltip>
740 ) : null
741 }
742 trailingActions={
743 previewBridge ? (
744 <PreviewMoreMenu
745 environmentId={threadRef.environmentId}
746 profileId={activeProfileId}
747 profileName={activeProfileName}
748 tabId={runtimeTabId}
749 hasWebContents={desktopOverlay?.hasWebContents ?? false}
750 zoomFactor={desktopOverlay?.zoomFactor ?? 1}
751 colorScheme={desktopOverlay?.colorScheme ?? "system"}
752 deviceToolbarVisible={viewport._tag !== "fill"}
753 onToggleDeviceToolbar={handleToggleDeviceToolbar}
754 nativePictureInPicture={desktopOverlay?.pictureInPicture ?? false}
755 onNativePictureInPicture={handleNativePictureInPicture}
756 />
757 ) : null
758 }
759 />
760​
761 <div className="relative min-h-0 flex-1 overflow-hidden">
762 {runtimeTabId && snapshot && !showEmptyState ? (
763 <BrowserSurfaceSlot
764 key={runtimeTabId}
765 tabId={runtimeTabId}
766 visible={visible && !isUnreachable}
767 className="absolute inset-0 h-full w-full"
768 />
769 ) : null}
770 {showEmptyState ? (
771 <PreviewEmptyState
772 threadRef={threadRef}
773 environmentId={threadRef.environmentId}
774 configuredUrls={configuredUrls}
775 recentEntries={recentHistoryEntries}
776 onRemoveRecent={(url) => removeUrlForThread(threadRef, url)}
777 onOpenUrl={(next) => void handleOpenServerUrl(next)}
778 />
779 ) : null}
780 {snapshot && desktopOverlay ? (
781 <ZoomIndicator zoomFactor={desktopOverlay.zoomFactor} />
782 ) : null}
783 {runtimeTabId && desktopOverlay && !showEmptyState && !isUnreachable ? (
784 <AgentBrowserCursor
785 tabId={runtimeTabId}
786 zoomFactor={desktopOverlay.zoomFactor}
787 controller={controller}
788 />
789 ) : null}
790 {controller !== "none" ? (
791 <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">
792 {controller === "agent" ? "Agent controlling browser" : "Human control"}
793 </div>
794 ) : null}
795 {navStatus._tag === "LoadFailed" ? (
796 <div className="absolute inset-0 z-10 bg-background">
797 <PreviewUnreachable
798 url={navStatus.url}
799 code={navStatus.code}
800 description={navStatus.description}
801 onReload={handleRefresh}
802 />
803 </div>
804 ) : null}
805 </div>
806 </div>
807 );