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