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