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