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

PreviewView.tsx

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