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

PreviewView.tsx

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