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

PreviewView.tsx

1,155 lines45.5 KB

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