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