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

PreviewView.tsx

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