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

PreviewView.tsx

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