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

PreviewView.tsx

1,079 lines39.7 KB

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