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

PreviewView.tsx

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