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