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

PreviewView.tsx

1,021 lines39.8 KB

1"use client";
2​
3import { scopedThreadKey } from "@t3tools/client-runtime/environment";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import {
9 DEFAULT_BROWSER_PROFILE_ID,
10 FILL_PREVIEW_VIEWPORT,
11 type PreviewAnnotationPayload,
12 type PreviewViewportSetting,
13 type ScopedThreadRef,
14 DEFAULT_PREVIEW_ZOOM_FACTOR,
15 PREVIEW_ZOOM_LEVELS,
16 type PreviewAdjustInput,
17} from "@t3tools/contracts";
18import { normalizePreviewUrl } from "@t3tools/shared/preview";
19import { useCallback, useEffect, useRef, useState } from "react";
20​
21import {
22 BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT,
23 recordVisitForThread,
24 removeUrlForThread,
25 setTitleForThreadUrl,
26 useThreadRecentHistory,
27} from "~/browserHistoryStore";
28import { type ComposerImageAttachment, useComposerDraftStore } from "~/composerDraftStore";
29import { capturePreviewAnnotationScreenshot } from "~/lib/previewAnnotation";
30import { ensureLocalApi } from "~/localApi";
31import {
32 rememberPreviewUrl,
33 updatePreviewServerSnapshot,
34 useThreadPreviewState,
35} from "~/previewStateStore";
36import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
37import { useEnvironmentHttpBaseUrl } from "~/state/environments";
38import { previewEnvironment } from "~/state/preview";
39import { useAtomCommand } from "~/state/use-atom-command";
40import {
41 browserMiniPlayerSource,
42 selectThreadPreviewMiniPlayerTabId,
43 usePreviewMiniPlayerStore,
44} from "~/previewMiniPlayerStore";
45import { useRightPanelStore } from "~/rightPanelStore";
46​
47import { previewBridge } from "./previewBridge";
48import { subscribePreviewAction } from "./previewActionBus";
49import { openPreviewSession } from "./openPreviewSession";
50import { PreviewChromeRow } from "./PreviewChromeRow";
51import { PreviewEmptyState } from "./PreviewEmptyState";
52import { PreviewMoreMenu, type PreviewMoreMenuActions } from "./PreviewMoreMenu";
53import {
54 commitBrowserViewportChange,
55 subscribeBrowserViewportChange,
56} from "~/browser/browserViewportActions";
57import { browserResponsiveViewportForToggle, useBrowserDefaults } from "~/browser/browserDefaults";
58import { BrowserDeviceToolbar } from "~/browser/BrowserDeviceToolbar";
59import { BROWSER_DEVICE_TOOLBAR_HEIGHT } from "~/browser/browserViewportLayout";
60import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
61import { BrowserSettingsReadError } from "~/browser/openFileInPreview";
62import { PreviewUnreachable } from "./PreviewUnreachable";
63import { revealInFileExplorerLabel } from "./fileExplorerLabel";
64import { shouldShowPreviewEmptyState } from "./previewEmptyStateLogic";
65import { Badge } from "~/components/ui/badge";
66import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot";
67import { useRendersServerTabNatively } from "~/browser/previewRuntime";
68import { ServerBrowserSurface, type ServerBrowserHandle } from "~/browser/ServerBrowserSurface";
69import { cn } from "~/lib/utils";
70import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
71import { usePreviewSession } from "./usePreviewSession";
72import { ZoomIndicator } from "./ZoomIndicator";
73import { AgentBrowserCursor } from "./AgentBrowserCursor";
74import {
75 findActiveBrowserRecordingRuntimeTabId,
76 isBrowserRecordingStartCancelledError,
77 startBrowserRecording,
78 stopBrowserRecording,
79 useActiveBrowserRecordingTabIds,
80} from "~/browser/browserRecording";
81import { stackedThreadToast, toastManager } from "~/components/ui/toast";
82import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
83​
84interface Props {
85 threadRef: ScopedThreadRef;
86 tabId?: string | null;
87 configuredUrls?: ReadonlyArray<string> | undefined;
88 visible: boolean;
89 onSendAnnotation?: (
90 annotation: PreviewAnnotationPayload,
91 image: ComposerImageAttachment | null,
92 ) => void;
94​
95function previewProfileName(
96 profiles: ReadonlyArray<{ readonly id: string; readonly name: string }>,
97 profileId: string,
98): string {
99 return profiles.find((profile) => profile.id === profileId)?.name ?? "Removed profile";
101​
102const localApi = typeof window === "undefined" ? null : ensureLocalApi();
103​
104/**
105 * Single-tab preview surface: chrome row on top, one webview below, empty
106 * state when no session exists for the thread.
107 */
108export function PreviewView({
109 threadRef,
110 tabId: requestedTabId,
111 configuredUrls,
112 visible,
113 onSendAnnotation,
114}: Props) {
115 const [focusUrlNonce, setFocusUrlNonce] = useState<number | undefined>(undefined);
116 const [pickActive, setPickActive] = useState(false);
117 const activeRecordingTabIds = useActiveBrowserRecordingTabIds();
118 const pickActiveRef = useRef(false);
119 const isMountedRef = useRef(true);
120 // Kept in sync so the title effect can depend on the stable thread key
121 // instead of the thread object, which is recreated on every update.
122 const threadRefRef = useRef(threadRef);
123 threadRefRef.current = threadRef;
124 const previewState = useThreadPreviewState(threadRef);
125 const recentHistoryEntries = useThreadRecentHistory(
126 threadRef,
127 BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT,
128 );
129 const miniPlayerTabId = usePreviewMiniPlayerStore((state) =>
130 selectThreadPreviewMiniPlayerTabId(state.byThreadKey, threadRef),
131 );
132 const addPreviewAnnotation = useComposerDraftStore((store) => store.addPreviewAnnotation);
133 const addImage = useComposerDraftStore((store) => store.addImage);
134 const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(threadRef.environmentId);
135 const environmentHostname = environmentHttpBaseUrl
136 ? new URL(environmentHttpBaseUrl).hostname
137 : null;
138 const open = useAtomCommand(previewEnvironment.open);
139 const resize = useAtomCommand(previewEnvironment.resize, "preview viewport resize");
140 const adjust = useAtomCommand(previewEnvironment.adjust, "preview appearance or zoom");
141​
142 usePreviewSession(threadRef);
143​
144 useEffect(() => {
145 isMountedRef.current = true;
146 return () => {
147 isMountedRef.current = false;
148 };
149 }, []);
150​
151 const tabId = requestedTabId ?? previewState.activeTabId;
152 const runtimeTabId = tabId
153 ? previewRuntimeTabId(threadRef, previewState.serverEpoch, tabId)
154 : null;
155 const recordingRuntimeTabId =
156 tabId && runtimeTabId
157 ? activeRecordingTabIds.has(runtimeTabId)
158 ? runtimeTabId
159 : findActiveBrowserRecordingRuntimeTabId(threadRef, tabId)
160 : null;
161 const snapshot = tabId ? (previewState.sessions[tabId] ?? null) : null;
162 // Server tabs run in the environment's browser and stream to any client, except the
163 // desktop app's own server's tabs, which render here natively while the server drives them.
164 const nativeServerTab = useRendersServerTabNatively(threadRef.environmentId, snapshot);
165 const isServerTab = snapshot?.runtime === "server" && !nativeServerTab;
166 /** The server owns this tab's appearance, zoom, and size, whoever renders it. */
167 const serverOwnsRendering = snapshot?.runtime === "server";
168 const serverSurfaceRef = useRef<ServerBrowserHandle | null>(null);
169 const [serverAspectRatioLocked, setServerAspectRatioLocked] = useState(false);
170 const serverBodyRef = useRef<HTMLDivElement | null>(null);
171 const [serverToolbarWidth, setServerToolbarWidth] = useState(0);
172 // The streamed tab's device toolbar spans the panel; only measured while it shows.
173 const serverToolbarShown =
174 snapshot?.runtime === "server" && (snapshot.viewport ?? FILL_PREVIEW_VIEWPORT)._tag !== "fill";
175 useEffect(() => {
176 const element = serverBodyRef.current;
177 if (!element || !serverToolbarShown) return;
178 const observer = new ResizeObserver(([entry]) =>
179 setServerToolbarWidth(Math.max(1, Math.round(entry?.contentRect.width ?? 0))),
180 );
181 observer.observe(element);
182 return () => observer.disconnect();
183 }, [serverToolbarShown]);
184 const [serverControlledTabId, setServerControlledTabId] = useState<string | null>(null);
185 const serverInputDisabled = isServerTab && serverControlledTabId !== runtimeTabId;
186 const [serverFrameTabId, setServerFrameTabId] = useState<string | null>(null);
187 const desktopOverlay = tabId ? (previewState.desktopByTabId[tabId] ?? null) : null;
188 const navStatus = snapshot?.navStatus ?? { _tag: "Idle" as const };
189 const url = navStatus._tag === "Idle" ? "" : navStatus.url;
190 const loading = desktopOverlay?.loading ?? navStatus._tag === "Loading";
191 const canGoBack = desktopOverlay?.canGoBack ?? snapshot?.canGoBack ?? false;
192 const canGoForward = desktopOverlay?.canGoForward ?? snapshot?.canGoForward ?? false;
193 const refreshDisabled = navStatus._tag === "Idle";
194 const isUnreachable = navStatus._tag === "LoadFailed";
195 const showEmptyState = shouldShowPreviewEmptyState(snapshot);
196 const serverStreamPending =
197 isServerTab && !showEmptyState && !isUnreachable && serverFrameTabId !== runtimeTabId;
198 const controller = desktopOverlay?.controller ?? "none";
199 const viewport = snapshot?.viewport ?? FILL_PREVIEW_VIEWPORT;
200 const browserDefaults = useBrowserDefaults();
201 // A tab created before profiles existed carries no profile of its own. It
202 // runs in the built-in `default` partition — the scope the browser used
203 // before profiles — not in whatever profile is configured as the default
204 // now, so that is what its label names and its clear actions target.
205 // Passing the snapshot's raw `undefined` through would reach the IPC layer
206 // as "every profile".
207 const activeProfileId = snapshot?.profileId ?? DEFAULT_BROWSER_PROFILE_ID;
208 const activeProfileName = previewProfileName(browserDefaults.profiles, activeProfileId);
209 const panelRect = useBrowserSurfaceStore((state) =>
210 runtimeTabId ? (state.byTabId[runtimeTabId]?.rect ?? null) : null,
211 );
212​
213 const navUrl = navStatus._tag === "Success" ? navStatus.url : null;
214 const navTitle = navStatus._tag === "Success" ? navStatus.title : null;
215 const latestHistoryUrl = recentHistoryEntries[0]?.url;
216 const threadKey = scopedThreadKey(threadRef);
217 useEffect(() => {
218 if (!navUrl || !navTitle || !latestHistoryUrl) return;
219 // Agent-driven pages only enrich an existing requested URL.
220 setTitleForThreadUrl(threadRefRef.current, navUrl, navTitle, environmentHostname);
221 // threadKey stands in for threadRef, whose identity churns on every thread update.
222 }, [environmentHostname, latestHistoryUrl, navTitle, navUrl, threadKey]);
223​
224 const navigateToResolvedUrl = useCallback(
225 async (resolvedUrl: string) => {
226 if (isServerTab && serverSurfaceRef.current) {
227 if (serverInputDisabled) return false;
228 serverSurfaceRef.current.navigate(resolvedUrl);
229 rememberPreviewUrl(threadRef, resolvedUrl);
230 return true;
231 }
232 if (runtimeTabId && previewBridge) {
233 // The bridge mirrors the resolved URL back to the server.
234 await previewBridge.navigate(runtimeTabId, resolvedUrl);
235 rememberPreviewUrl(threadRef, resolvedUrl);
236 return true;
237 }
238 const result = await openPreviewSession({ openPreview: open, threadRef, url: resolvedUrl });
239 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
240 const error = squashAtomCommandFailure(result);
241 if (error instanceof BrowserSettingsReadError) {
242 toastManager.add({
243 type: "error",
244 title: "Unable to open browser",
245 description: error.message,
246 });
247 }
248 }
249 return result._tag === "Success";
250 },
251 [isServerTab, open, runtimeTabId, serverInputDisabled, threadRef],
252 );
253​
254 const handleSubmitUrl = useCallback(
255 async (next: string) => {
256 try {
257 const normalized = normalizePreviewUrl(next);
258 if (await navigateToResolvedUrl(normalized)) {
259 recordVisitForThread(threadRef, normalized);
260 }
261 } catch {
262 // Server-side `failed` event renders the unreachable view.
263 }
264 },
265 [navigateToResolvedUrl, threadRef],
266 );
267​
268 const handleOpenServerUrl = useCallback(
269 async (next: string) => {
270 try {
271 // A server tab's browser runs on the environment, where loopback is already right.
272 const resolved =
273 isServerTab || !previewBridge
274 ? normalizePreviewUrl(next)
275 : resolveDiscoveredServerUrl(threadRef.environmentId, next);
276 if (await navigateToResolvedUrl(resolved)) {
277 recordVisitForThread(threadRef, next);
278 }
279 } catch {
280 // Server-side `failed` event renders the unreachable view.
281 }
282 },
283 [isServerTab, navigateToResolvedUrl, threadRef],
284 );
285​
286 const handleRefresh = useCallback(() => {
287 if (isServerTab) serverSurfaceRef.current?.reload();
288 else if (previewBridge && runtimeTabId) void previewBridge.refresh(runtimeTabId);
289 }, [isServerTab, runtimeTabId]);
290​
291 /** Appearance and zoom of a server tab, through the server for every client. */
292 const adjustServerTab = useCallback(
293 async (change: Omit<PreviewAdjustInput, "threadId" | "tabId">) => {
294 if (!tabId) return;
295 const result = await adjust({
296 environmentId: threadRef.environmentId,
297 input: { threadId: threadRef.threadId, tabId, ...change },
298 });
299 if (result._tag === "Failure") {
300 const error = squashAtomCommandFailure(result);
301 toastManager.add({
302 type: "error",
303 title: "Unable to change the browser tab",
304 description: error instanceof Error ? error.message : "An error occurred.",
305 });
306 return;
307 }
308 updatePreviewServerSnapshot(threadRef, result.value);
309 },
310 [adjust, tabId, threadRef],
311 );
312​
313 const serverZoomFactor = snapshot?.zoomFactor ?? DEFAULT_PREVIEW_ZOOM_FACTOR;
314 const stepServerZoom = useCallback(
315 (direction: -1 | 0 | 1) => {
316 const index = PREVIEW_ZOOM_LEVELS.indexOf(serverZoomFactor);
317 const next =
318 direction === 0
319 ? DEFAULT_PREVIEW_ZOOM_FACTOR
320 : PREVIEW_ZOOM_LEVELS[
321 Math.min(
322 Math.max((index < 0 ? 7 : index) + direction, 0),
323 PREVIEW_ZOOM_LEVELS.length - 1,
324 )
325 ]!;
326 if (next !== serverZoomFactor) void adjustServerTab({ zoomFactor: next });
327 },
328 [adjustServerTab, serverZoomFactor],
329 );
330​
331 const handleZoomIn = useCallback(() => {
332 if (serverOwnsRendering) stepServerZoom(1);
333 else if (previewBridge && runtimeTabId) void previewBridge.zoomIn(runtimeTabId);
334 }, [runtimeTabId, serverOwnsRendering, stepServerZoom]);
335​
336 const handleZoomOut = useCallback(() => {
337 if (serverOwnsRendering) stepServerZoom(-1);
338 else if (previewBridge && runtimeTabId) void previewBridge.zoomOut(runtimeTabId);
339 }, [runtimeTabId, serverOwnsRendering, stepServerZoom]);
340​
341 const handleResetZoom = useCallback(() => {
342 if (serverOwnsRendering) stepServerZoom(0);
343 else if (previewBridge && runtimeTabId) void previewBridge.resetZoom(runtimeTabId);
344 }, [runtimeTabId, serverOwnsRendering, stepServerZoom]);
345​
346 const handleViewportChange = useCallback(
347 async (nextViewport: PreviewViewportSetting) => {
348 if (!tabId) return;
349 const result = await resize({
350 environmentId: threadRef.environmentId,
351 input: {
352 threadId: threadRef.threadId,
353 tabId,
354 viewport: nextViewport,
355 },
356 });
357 if (result._tag === "Failure") {
358 const error = squashAtomCommandFailure(result);
359 toastManager.add({
360 type: "error",
361 title: "Unable to resize browser viewport",
362 description: error instanceof Error ? error.message : "An error occurred.",
363 });
364 throw error;
365 }
366 updatePreviewServerSnapshot(threadRef, result.value);
367 },
368 [resize, tabId, threadRef],
369 );
370​
371 const handleToggleDeviceToolbar = () => {
372 if (!runtimeTabId) return;
373 if (viewport._tag !== "fill") {
374 void commitBrowserViewportChange(runtimeTabId, FILL_PREVIEW_VIEWPORT).catch(() => undefined);
375 return;
376 }
377​
378 void commitBrowserViewportChange(
379 runtimeTabId,
380 browserResponsiveViewportForToggle({
381 defaults: browserDefaults,
382 panelRect,
383 zoomFactor: serverOwnsRendering ? serverZoomFactor : desktopOverlay?.zoomFactor,
384 }),
385 ).catch(() => undefined);
386 };
387​
388 useEffect(() => {
389 if (!runtimeTabId) return;
390 return subscribeBrowserViewportChange(runtimeTabId, handleViewportChange);
391 }, [handleViewportChange, runtimeTabId]);
392​
393 const handleBack = useCallback(() => {
394 if (isServerTab) serverSurfaceRef.current?.history(-1);
395 else if (previewBridge && runtimeTabId) void previewBridge.goBack(runtimeTabId);
396 }, [isServerTab, runtimeTabId]);
397​
398 const handleForward = useCallback(() => {
399 if (isServerTab) serverSurfaceRef.current?.history(1);
400 else if (previewBridge && runtimeTabId) void previewBridge.goForward(runtimeTabId);
401 }, [isServerTab, runtimeTabId]);
402​
403 const handleOpenInBrowser = useCallback(() => {
404 if (!localApi || !url) return;
405 void localApi.shell.openExternal(url).catch(() => undefined);
406 }, [url]);
407​
408 const handlePictureInPicture = useCallback(() => {
409 if (!tabId) return;
410 if (miniPlayerTabId === tabId) {
411 usePreviewMiniPlayerStore.getState().close(threadRef);
412 return;
413 }
414 usePreviewMiniPlayerStore.getState().open(threadRef, browserMiniPlayerSource(tabId));
415 useRightPanelStore.getState().close(threadRef);
416 }, [miniPlayerTabId, tabId, threadRef]);
417​
418 /**
419 * The menu's actions. A server tab, streamed or rendered natively here, runs
420 * them through its environment, so every client and agent sees one state.
421 * Opening DevTools and a separate window need the desktop's own page.
422 */
423 const desktopCall = (op: ((tabId: string) => Promise<void>) | undefined) => () => {
424 if (op && runtimeTabId) void op(runtimeTabId).catch(() => undefined);
425 };
426 const moreMenuActions: PreviewMoreMenuActions | null = serverOwnsRendering
427 ? {
428 hardReload: () => void adjustServerTab({ hardReload: true }),
429 setColorScheme: (colorScheme) => void adjustServerTab({ colorScheme }),
430 zoomIn: handleZoomIn,
431 zoomOut: handleZoomOut,
432 resetZoom: handleResetZoom,
433 clearCookies: () => void adjustServerTab({ clear: "cookies" }),
434 clearCache: () => void adjustServerTab({ clear: "cache" }),
435 ...(nativeServerTab && previewBridge
436 ? {
437 openDevTools: desktopCall(previewBridge.openDevTools),
438 toggleNativePictureInPicture: () => handleNativePictureInPicture(),
439 }
440 : {}),
441 }
442 : previewBridge
443 ? {
444 hardReload: desktopCall(previewBridge.hardReload),
445 setColorScheme: (colorScheme) => {
446 if (runtimeTabId)
447 void previewBridge?.setColorScheme(runtimeTabId, colorScheme).catch(() => undefined);
448 },
449 zoomIn: handleZoomIn,
450 zoomOut: handleZoomOut,
451 resetZoom: handleResetZoom,
452 clearCookies: () =>
453 void previewBridge
454 ?.clearCookies(threadRef.environmentId, activeProfileId)
455 .catch(() => undefined),
456 clearCache: () =>
457 void previewBridge
458 ?.clearCache(threadRef.environmentId, activeProfileId)
459 .catch(() => undefined),
460 openDevTools: desktopCall(previewBridge.openDevTools),
461 toggleNativePictureInPicture: () => handleNativePictureInPicture(),
462 }
463 : null;
464​
465 const handleNativePictureInPicture = useCallback(() => {
466 if (!previewBridge || !runtimeTabId) return;
467 const operation = desktopOverlay?.pictureInPicture
468 ? previewBridge.pictureInPicture.close
469 : previewBridge.pictureInPicture.open;
470 void operation(runtimeTabId).catch((error) => {
471 toastManager.add({
472 type: "error",
473 title: "Unable to update popped-out preview",
474 description: error instanceof Error ? error.message : "An error occurred.",
475 });
476 });
477 }, [desktopOverlay?.pictureInPicture, runtimeTabId]);
478​
479 const handleCapture = useCallback(
480 (record: boolean) => {
481 if (!previewBridge || !runtimeTabId || !tabId) return;
482 const bridge = previewBridge;
483 if (recordingRuntimeTabId) {
484 void stopBrowserRecording(recordingRuntimeTabId).then(
485 (artifact) => {
486 if (!artifact) return;
487 let pathCopied = false;
488 let toastId: ReturnType<typeof toastManager.add>;
489​
490 const copyPath = () => {
491 if (!navigator.clipboard?.writeText) {
492 toastManager.update(
493 toastId,
494 stackedThreadToast({
495 type: "error",
496 title: "Unable to copy recording path",
497 description: "Clipboard API unavailable.",
498 actionProps: revealAction,
499 }),
500 );
501 return;
502 }
503​
504 void navigator.clipboard.writeText(artifact.path).then(
505 () => {
506 pathCopied = true;
507 updateRecordingToast();
508 window.setTimeout(() => {
509 pathCopied = false;
510 updateRecordingToast();
511 }, 2_000);
512 },
513 (error) => {
514 toastManager.update(
515 toastId,
516 stackedThreadToast({
517 type: "error",
518 title: "Unable to copy recording path",
519 description: error instanceof Error ? error.message : "An error occurred.",
520 actionProps: revealAction,
521 }),
522 );
523 },
524 );
525 };
526​
527 const revealAction = {
528 children: revealInFileExplorerLabel(navigator.platform),
529 onClick: () => void bridge.revealArtifact(artifact.path),
530 };
531 const updateRecordingToast = () => {
532 toastManager.update(
533 toastId,
534 stackedThreadToast({
535 type: "success",
536 title: "Recording saved",
537 actionProps: revealAction,
538 data: {
539 secondaryActionProps: {
540 children: pathCopied ? "Copied!" : "Copy path",
541 disabled: pathCopied,
542 onClick: copyPath,
543 },
544 secondaryActionVariant: "outline",
545 },
546 }),
547 );
548 };
549​
550 toastId = toastManager.add(
551 stackedThreadToast({
552 type: "success",
553 title: "Recording saved",
554 actionProps: revealAction,
555 data: {
556 secondaryActionProps: {
557 children: "Copy path",
558 onClick: copyPath,
559 },
560 secondaryActionVariant: "outline",
561 },
562 }),
563 );
564 },
565 (error) => {
566 toastManager.add({
567 type: "error",
568 title: "Unable to stop recording",
569 description: error instanceof Error ? error.message : "An error occurred.",
570 });
571 },
572 );
573 return;
574 }
575 if (record) {
576 void startBrowserRecording(runtimeTabId, threadRef, tabId).catch((error) => {
577 const description = error instanceof Error ? error.message : "An error occurred.";
578 if (isBrowserRecordingStartCancelledError(error)) return;
579 toastManager.add({
580 type: "error",
581 title: "Unable to start recording",
582 description,
583 });
584 });
585 return;
586 }
587 void bridge.captureScreenshot(runtimeTabId).then(
588 (artifact) => {
589 const revealAction = {
590 children: revealInFileExplorerLabel(navigator.platform),
591 onClick: () => void bridge.revealArtifact(artifact.path),
592 };
593 let pathCopied = false;
594 let imageCopied = false;
595 let toastId: ReturnType<typeof toastManager.add>;
596​
597 const updateScreenshotToast = (
598 type: "success" | "error" = "success",
599 title = "Screenshot saved",
600 description?: string,
601 ) => {
602 toastManager.update(
603 toastId,
604 stackedThreadToast({
605 type,
606 title,
607 description,
608 actionProps: {
609 children: imageCopied ? "Copied!" : "Copy image",
610 disabled: imageCopied,
611 onClick: copyImage,
612 },
613 data: {
614 additionalActions: [
615 {
616 id: "copy-path",
617 props: {
618 children: pathCopied ? "Copied!" : "Copy path",
619 disabled: pathCopied,
620 onClick: copyPath,
621 },
622 },
623 ],
624 secondaryActionProps: {
625 ...revealAction,
626 },
627 secondaryActionVariant: "outline",
628 },
629 }),
630 );
631 };
632​
633 const copyPath = () => {
634 if (!navigator.clipboard?.writeText) {
635 updateScreenshotToast(
636 "error",
637 "Unable to copy screenshot path",
638 "Clipboard API unavailable.",
639 );
640 return;
641 }
642​
643 void navigator.clipboard.writeText(artifact.path).then(
644 () => {
645 pathCopied = true;
646 updateScreenshotToast();
647 window.setTimeout(() => {
648 pathCopied = false;
649 updateScreenshotToast();
650 }, 2_000);
651 },
652 (error) => {
653 updateScreenshotToast(
654 "error",
655 "Unable to copy screenshot path",
656 error instanceof Error ? error.message : "An error occurred.",
657 );
658 },
659 );
660 };
661​
662 const copyImage = () => {
663 void bridge.copyArtifactToClipboard(artifact.path).then(
664 () => {
665 imageCopied = true;
666 updateScreenshotToast();
667 window.setTimeout(() => {
668 imageCopied = false;
669 updateScreenshotToast();
670 }, 2_000);
671 },
672 (error) => {
673 updateScreenshotToast(
674 "error",
675 "Unable to copy screenshot",
676 error instanceof Error ? error.message : "An error occurred.",
677 );
678 },
679 );
680 };
681​
682 toastId = toastManager.add(
683 stackedThreadToast({
684 type: "success",
685 title: "Screenshot saved",
686 actionProps: {
687 children: "Copy image",
688 onClick: copyImage,
689 },
690 data: {
691 additionalActions: [
692 {
693 id: "copy-path",
694 props: {
695 children: "Copy path",
696 onClick: copyPath,
697 },
698 },
699 ],
700 secondaryActionProps: {
701 ...revealAction,
702 },
703 secondaryActionVariant: "outline",
704 },
705 }),
706 );
707 },
708 (error) => {
709 toastManager.add({
710 type: "error",
711 title: "Unable to capture screenshot",
712 description: error instanceof Error ? error.message : "An error occurred.",
713 });
714 },
715 );
716 },
717 [recordingRuntimeTabId, runtimeTabId, tabId, threadRef],
718 );
719​
720 const handlePickElement = useCallback(() => {
721 if (!previewBridge || !runtimeTabId) return;
722 if (pickActiveRef.current) {
723 void previewBridge.cancelPickElement(runtimeTabId).catch(() => undefined);
724 return;
725 }
726 // Snapshot whatever the user was focused on (typically the chat
727 // composer textarea or the chrome-row pick button) BEFORE main steals
728 // focus into the guest webContents. We restore it when the pick
729 // resolves so the user's typing context isn't lost — otherwise after
730 // every pick they'd have to click back into the textarea.
731 const previouslyFocused =
732 typeof document !== "undefined" ? (document.activeElement as HTMLElement | null) : null;
733 pickActiveRef.current = true;
734 setPickActive(true);
735 void (async () => {
736 try {
737 const result = await previewBridge.pickElement(runtimeTabId);
738 if (!result) return;
739 const { annotation: picked, submission, screenshotFailed = false } = result;
740 // The structured annotation is still sendable when its optional crop
741 // stalls or fails, so tell the user what they lost and keep going
742 // instead of holding the composer for an attachment that never lands.
743 // The stored copy drops the screenshot on failure, otherwise the prompt
744 // would tell the agent a crop is attached when none was sent.
745 const capture = capturePreviewAnnotationScreenshot(picked);
746 // Main reports a crop that failed or timed out on its side; the local
747 // conversion can fail too. Either way the user should hear about it.
748 const cropDropped = screenshotFailed || capture.status === "failed";
749 const annotation = capture.status === "failed" ? { ...picked, screenshot: null } : picked;
750 addPreviewAnnotation(threadRef, annotation);
751 if (cropDropped) {
752 toastManager.add(
753 stackedThreadToast({
754 type: "error",
755 title: "Could not capture the picked element",
756 // The send path reports its own outcome, so only say what this
757 // handler knows: the crop was dropped.
758 description: "The annotation was kept without the screenshot.",
759 }),
760 );
761 }
762 const screenshotFile = capture.status === "captured" ? capture.file : null;
763 const image =
764 screenshotFile && annotation.screenshot
765 ? ({
766 type: "image",
767 id: annotation.id,
768 name: screenshotFile.name,
769 mimeType: screenshotFile.type,
770 sizeBytes: screenshotFile.size,
771 previewUrl: annotation.screenshot.dataUrl,
772 file: screenshotFile,
773 } satisfies ComposerImageAttachment)
774 : null;
775 if (image) {
776 addImage(threadRef, image);
777 }
778 if (submission === "send") {
779 onSendAnnotation?.(annotation, image);
780 }
781 } catch {
782 // Picker failed (e.g. webview navigated). Treat as silent cancel.
783 } finally {
784 pickActiveRef.current = false;
785 // Avoid `setState on unmounted component` if the panel/thread closed
786 // while the pick was in flight.
787 if (isMountedRef.current) setPickActive(false);
788 // Best-effort: restore focus to whatever the user had before the
789 // pick stole it into the guest webContents. Skip if the previously-
790 // focused element was unmounted or is no longer focusable.
791 if (
792 previouslyFocused &&
793 previouslyFocused.isConnected &&
794 typeof previouslyFocused.focus === "function"
795 ) {
796 try {
797 previouslyFocused.focus({ preventScroll: true });
798 } catch {
799 // Some elements throw on .focus() (detached iframes, etc.).
800 }
801 }
802 }
803 })();
804 }, [addImage, addPreviewAnnotation, onSendAnnotation, runtimeTabId, threadRef]);
805​
806 // If the active tab changes mid-pick (close, thread switch, hot restart),
807 // tell main to tear down the in-flight session AND reset our local toggle
808 // state so the button doesn't get stuck pressed against a stale tab id.
809 useEffect(() => {
810 return () => {
811 if (!pickActiveRef.current) return;
812 pickActiveRef.current = false;
813 if (previewBridge && runtimeTabId) {
814 void previewBridge.cancelPickElement(runtimeTabId).catch(() => undefined);
815 }
816 if (isMountedRef.current) setPickActive(false);
817 };
818 }, [runtimeTabId]);
819​
820 // Subscribe only while visible; `toggle-panel` is owned by ChatView's
821 // URL-aware handler regardless of whether the panel is currently mounted.
822 useEffect(() => {
823 if (!visible) return;
824 return subscribePreviewAction((action) => {
825 switch (action) {
826 case "refresh":
827 handleRefresh();
828 return;
829 case "focus-url":
830 setFocusUrlNonce((value) => (value ?? 0) + 1);
831 return;
832 case "zoom-in":
833 handleZoomIn();
834 return;
835 case "zoom-out":
836 handleZoomOut();
837 return;
838 case "reset-zoom":
839 handleResetZoom();
840 return;
841 case "toggle-panel":
842 return;
843 }
844 });
845 }, [handleRefresh, handleResetZoom, handleZoomIn, handleZoomOut, visible]);
846​
847 return (
848 <div
849 className="flex min-h-0 flex-1 flex-col bg-background"
850 data-thread-key={scopedThreadKey(threadRef)}
851 >
852 <PreviewChromeRow
853 url={url}
854 loading={loading || serverStreamPending}
855 canGoBack={canGoBack && !serverInputDisabled}
856 canGoForward={canGoForward && !serverInputDisabled}
857 refreshDisabled={refreshDisabled || serverInputDisabled}
858 inputDisabled={serverInputDisabled}
859 focusUrlNonce={focusUrlNonce}
860 onBack={handleBack}
861 onForward={handleForward}
862 onRefresh={handleRefresh}
863 onSubmit={(next) => void handleSubmitUrl(next)}
864 onOpenInBrowser={tabId ? handleOpenInBrowser : undefined}
865 // Capture, annotation, and the more menu drive the desktop webview, so
866 // server tabs leave them out. Floating works for both.
867 onCapture={previewBridge && tabId && !isServerTab ? handleCapture : undefined}
868 captureDisabled={!desktopOverlay || isUnreachable}
869 recording={recordingRuntimeTabId !== null}
870 onPictureInPicture={
871 tabId && (isServerTab || previewBridge) ? handlePictureInPicture : undefined
872 }
873 pictureInPicture={miniPlayerTabId === tabId}
874 pictureInPictureDisabled={
875 isUnreachable || (!isServerTab && !desktopOverlay?.hasWebContents)
876 }
877 onPickElement={previewBridge && tabId && !isServerTab ? handlePickElement : undefined}
878 pickActive={pickActive}
879 // Disable when there's no tab (nothing to pick on) OR the page
880 // failed to load (a React overlay covers the webview, so the
881 // user wouldn't be able to actually click anything underneath).
882 pickDisabled={!tabId || isUnreachable}
883 pickDisabledReason={
884 isUnreachable ? "Page didn't load — pick unavailable until the page renders" : undefined
885 }
886 leadingActions={
887 // Only when it differs from the default: labelling every tab
888 // "Default" would be noise on the common case, while a tab in
889 // another profile is exactly what needs calling out.
890 activeProfileId !== browserDefaults.profileId ? (
891 // Capped: profile names run to 48 characters, and an unbounded
892 // badge in this row takes its width from the URL input, the only
893 // flexible element in the compact chrome. The cap sits on the
894 // badge and the truncation on an inner span, because `Badge` is an
895 // `inline-flex` with `whitespace-nowrap` — `text-overflow` never
896 // reaches a bare text node inside it, so the name would be cut off
897 // at both ends with no ellipsis.
898 <Tooltip>
899 <TooltipTrigger render={<Badge variant="outline" className="max-w-28 shrink-0" />}>
900 <span className="truncate">{activeProfileName}</span>
901 </TooltipTrigger>
902 <TooltipPopup side="top">{activeProfileName}</TooltipPopup>
903 </Tooltip>
904 ) : null
905 }
906 trailingActions={
907 moreMenuActions ? (
908 <PreviewMoreMenu
909 enabled={
910 runtimeTabId !== null &&
911 (serverOwnsRendering || (desktopOverlay?.hasWebContents ?? false))
912 }
913 actions={moreMenuActions}
914 profileName={activeProfileName}
915 zoomFactor={
916 serverOwnsRendering ? serverZoomFactor : (desktopOverlay?.zoomFactor ?? 1)
917 }
918 colorScheme={
919 serverOwnsRendering
920 ? (snapshot?.colorScheme ?? "system")
921 : (desktopOverlay?.colorScheme ?? "system")
922 }
923 deviceToolbarVisible={viewport._tag !== "fill"}
924 onToggleDeviceToolbar={handleToggleDeviceToolbar}
925 nativePictureInPicture={desktopOverlay?.pictureInPicture ?? false}
926 />
927 ) : null
928 }
929 />
930​
931 <div ref={serverBodyRef} className="relative min-h-0 flex-1 overflow-hidden">
932 {runtimeTabId && snapshot && isServerTab ? (
933 <>
934 {viewport._tag !== "fill" && !showEmptyState && !isUnreachable ? (
935 <div className="absolute inset-x-0 top-0 z-10">
936 <BrowserDeviceToolbar
937 setting={viewport}
938 width={serverToolbarWidth}
939 aspectRatio={serverAspectRatioLocked ? viewport.width / viewport.height : null}
940 onAspectRatioChange={(ratio) => setServerAspectRatioLocked(ratio !== null)}
941 onChange={(setting) => commitBrowserViewportChange(runtimeTabId, setting)}
942 />
943 </div>
944 ) : null}
945 <div
946 className="absolute inset-x-0 bottom-0"
947 style={{ top: viewport._tag !== "fill" ? BROWSER_DEVICE_TOOLBAR_HEIGHT : 0 }}
948 >
949 <ServerBrowserSurface
950 key={runtimeTabId}
951 ref={serverSurfaceRef}
952 environmentId={threadRef.environmentId}
953 threadId={threadRef.threadId}
954 tabId={snapshot.tabId}
955 visible={visible}
956 onFirstFrame={() => setServerFrameTabId(runtimeTabId)}
957 onControl={(control) =>
958 setServerControlledTabId(control?.controller === "you" ? runtimeTabId : null)
959 }
960 // Stays connected under the empty state so a URL picked there reaches the page.
961 className={cn(
962 "absolute inset-0 h-full w-full",
963 (showEmptyState || isUnreachable) && "invisible",
964 )}
965 />
966 </div>
967 </>
968 ) : runtimeTabId && snapshot && !showEmptyState ? (
969 previewBridge ? (
970 <BrowserSurfaceSlot
971 key={runtimeTabId}
972 tabId={runtimeTabId}
973 visible={visible && !isUnreachable}
974 className="absolute inset-0 h-full w-full"
975 />
976 ) : (
977 <div className="flex h-full items-center justify-center p-8 text-center">
978 <p className="max-w-sm text-sm text-muted-foreground">
979 This tab is open in the T3 Code desktop app.
980 </p>
981 </div>
982 )
983 ) : null}
984 {showEmptyState ? (
985 <PreviewEmptyState
986 threadRef={threadRef}
987 environmentId={threadRef.environmentId}
988 configuredUrls={configuredUrls}
989 recentEntries={recentHistoryEntries}
990 onRemoveRecent={(url) => removeUrlForThread(threadRef, url)}
991 onOpenUrl={(next) => void handleOpenServerUrl(next)}
992 />
993 ) : null}
994 {snapshot && desktopOverlay ? (
995 <ZoomIndicator zoomFactor={desktopOverlay.zoomFactor} />
996 ) : null}
997 {runtimeTabId &&
998 desktopOverlay &&
999 !showEmptyState &&
1000 !isUnreachable &&
1001 !activeRecordingTabIds.has(runtimeTabId) ? (
1002 <AgentBrowserCursor
1003 tabId={runtimeTabId}
1004 zoomFactor={desktopOverlay.zoomFactor}
1005 controller={controller}
1006 />
1007 ) : null}
1008 {navStatus._tag === "LoadFailed" ? (
1009 <div className="absolute inset-0 z-10 bg-background">
1010 <PreviewUnreachable
1011 url={navStatus.url}
1012 code={navStatus.code}
1013 description={navStatus.description}
1014 onReload={handleRefresh}
1015 />
1016 </div>
1017 ) : null}
1018 </div>
1019 </div>
1020 );