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

PreviewView.tsx

1,160 lines43.3 KB

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