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

PreviewView.tsx

1,079 lines39.5 KB

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