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