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

PreviewView.tsx

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