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

PreviewView.tsx

1,030 lines38.2 KB

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