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

PreviewView.tsx

1,153 lines44.2 KB

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