Open History to see the last commit
1"use client";
2
3import { scopedThreadKey } from "@t3tools/client-runtime/environment";
4import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5import {
6 FILL_PREVIEW_VIEWPORT,
7 type PreviewViewportSetting,
8 type ScopedThreadRef,
9} from "@t3tools/contracts";
10import { normalizePreviewUrl } from "@t3tools/shared/preview";
11import { useCallback, useEffect, useRef, useState } from "react";
12
13import { useComposerDraftStore } from "~/composerDraftStore";
14import { previewAnnotationScreenshotFile } from "~/lib/previewAnnotation";
15import { ensureLocalApi } from "~/localApi";
16import {
17 rememberPreviewUrl,
18 updatePreviewServerSnapshot,
19 useThreadPreviewState,
20} from "~/previewStateStore";
21import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
22import { useEnvironment, useEnvironmentHttpBaseUrl } from "~/state/environments";
23import { previewEnvironment } from "~/state/preview";
24import { useAtomCommand } from "~/state/use-atom-command";
25
26import { previewBridge } from "./previewBridge";
27import { subscribePreviewAction } from "./previewActionBus";
28import { openPreviewSession } from "./openPreviewSession";
29import { PreviewChromeRow } from "./PreviewChromeRow";
30import { formatPreviewUrl } from "./previewUrlPresentation";
31import { PreviewEmptyState } from "./PreviewEmptyState";
32import { PreviewMoreMenu } from "./PreviewMoreMenu";
33import {
34 commitBrowserViewportChange,
35 subscribeBrowserViewportChange,
36} from "~/browser/browserViewportActions";
37import { resolveResponsiveBrowserViewportSize } from "~/browser/browserViewportLayout";
38import { PreviewUnreachable } from "./PreviewUnreachable";
39import { revealInFileExplorerLabel } from "./fileExplorerLabel";
40import { shouldShowPreviewEmptyState } from "./previewEmptyStateLogic";
41import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot";
42import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
43import { useLoadingProgress } from "./useLoadingProgress";
44import { usePreviewSession } from "./usePreviewSession";
45import { ZoomIndicator } from "./ZoomIndicator";
46import { AgentBrowserCursor } from "./AgentBrowserCursor";
47import {
48 startBrowserRecording,
49 stopBrowserRecording,
50 useActiveBrowserRecordingTabId,
51} from "~/browser/browserRecording";
52import { stackedThreadToast, toastManager } from "~/components/ui/toast";
53
54interface Props {
55 threadRef: ScopedThreadRef;
56 tabId?: string | null;
57 configuredUrls?: ReadonlyArray<string> | undefined;
58 visible: boolean;
59}
60
61const localApi = typeof window === "undefined" ? null : ensureLocalApi();
62
63/**
64 * Single-tab preview surface: chrome row on top, one webview below, empty
65 * state when no session exists for the thread.
66 */
67export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls, visible }: Props) {
68 const [focusUrlNonce, setFocusUrlNonce] = useState<number | undefined>(undefined);
69 const [pickActive, setPickActive] = useState(false);
70 const activeRecordingTabId = useActiveBrowserRecordingTabId();
71 const pickActiveRef = useRef(false);
72 const isMountedRef = useRef(true);
73 const previewState = useThreadPreviewState(threadRef);
74 const addPreviewAnnotation = useComposerDraftStore((store) => store.addPreviewAnnotation);
75 const addImage = useComposerDraftStore((store) => store.addImage);
76 const environment = useEnvironment(threadRef.environmentId);
77 const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(threadRef.environmentId);
78 const open = useAtomCommand(previewEnvironment.open);
79 const resize = useAtomCommand(previewEnvironment.resize, "preview viewport resize");
80
81 usePreviewSession(threadRef);
82
83 useEffect(() => {
84 isMountedRef.current = true;
85 return () => {
86 isMountedRef.current = false;
87 };
88 }, []);
89
90 const tabId = requestedTabId ?? previewState.activeTabId;
91 const snapshot = tabId ? (previewState.sessions[tabId] ?? null) : null;
92 const desktopOverlay = tabId ? (previewState.desktopByTabId[tabId] ?? null) : null;
93 const navStatus = snapshot?.navStatus ?? { _tag: "Idle" as const };
94 const url = navStatus._tag === "Idle" ? "" : navStatus.url;
95 const loading = desktopOverlay?.loading ?? navStatus._tag === "Loading";
96 const canGoBack = desktopOverlay?.canGoBack ?? snapshot?.canGoBack ?? false;
97 const canGoForward = desktopOverlay?.canGoForward ?? snapshot?.canGoForward ?? false;
98 const refreshDisabled = navStatus._tag === "Idle";
99 const isUnreachable = navStatus._tag === "LoadFailed";
100 const showEmptyState = shouldShowPreviewEmptyState(snapshot);
101 const controller = desktopOverlay?.controller ?? "none";
102 const loadProgress = useLoadingProgress(loading);
103 const displayUrl =
104 url && environment && environmentHttpBaseUrl
105 ? (formatPreviewUrl({
106 url,
107 environmentLabel: environment.label,
108 environmentHttpBaseUrl,
109 }) ?? undefined)
110 : undefined;
111 const viewport = snapshot?.viewport ?? FILL_PREVIEW_VIEWPORT;
112 const panelRect = useBrowserSurfaceStore((state) =>
113 tabId ? (state.byTabId[tabId]?.rect ?? null) : null,
114 );
115
116 const navigateToResolvedUrl = useCallback(
117 async (resolvedUrl: string) => {
118 if (tabId && previewBridge) {
119 // Drive the webview imperatively; `usePreviewBridge` mirrors the
120 // resolved URL back to the server so other clients stay in sync.
121 await previewBridge.navigate(tabId, resolvedUrl);
122 rememberPreviewUrl(threadRef, resolvedUrl);
123 } else {
124 await openPreviewSession({
125 openPreview: open,
126 threadRef,
127 url: resolvedUrl,
128 });
129 }
130 },
131 [open, tabId, threadRef],
132 );
133
134 const handleSubmitUrl = useCallback(
135 async (next: string) => {
136 try {
137 await navigateToResolvedUrl(normalizePreviewUrl(next));
138 } catch {
139 // Server-side `failed` event renders the unreachable view.
140 }
141 },
142 [navigateToResolvedUrl],
143 );
144
145 const handleOpenServerUrl = useCallback(
146 async (next: string) => {
147 try {
148 await navigateToResolvedUrl(resolveDiscoveredServerUrl(threadRef.environmentId, next));
149 } catch {
150 // Server-side `failed` event renders the unreachable view.
151 }
152 },
153 [navigateToResolvedUrl, threadRef.environmentId],
154 );
155
156 const handleRefresh = useCallback(() => {
157 if (previewBridge && tabId) void previewBridge.refresh(tabId);
158 }, [tabId]);
159
160 const handleZoomIn = useCallback(() => {
161 if (previewBridge && tabId) void previewBridge.zoomIn(tabId);
162 }, [tabId]);
163
164 const handleZoomOut = useCallback(() => {
165 if (previewBridge && tabId) void previewBridge.zoomOut(tabId);
166 }, [tabId]);
167
168 const handleResetZoom = useCallback(() => {
169 if (previewBridge && tabId) void previewBridge.resetZoom(tabId);
170 }, [tabId]);
171
172 const handleViewportChange = useCallback(
173 async (nextViewport: PreviewViewportSetting) => {
174 if (!tabId) return;
175 const result = await resize({
176 environmentId: threadRef.environmentId,
177 input: {
178 threadId: threadRef.threadId,
179 tabId,
180 viewport: nextViewport,
181 },
182 });
183 if (result._tag === "Failure") {
184 const error = squashAtomCommandFailure(result);
185 toastManager.add({
186 type: "error",
187 title: "Unable to resize browser viewport",
188 description: error instanceof Error ? error.message : "An error occurred.",
189 });
190 throw error;
191 }
192 updatePreviewServerSnapshot(threadRef, result.value);
193 },
194 [resize, tabId, threadRef],
195 );
196
197 const handleToggleDeviceToolbar = () => {
198 if (!tabId) return;
199 if (viewport._tag !== "fill") {
200 void commitBrowserViewportChange(tabId, FILL_PREVIEW_VIEWPORT).catch(() => undefined);
201 return;
202 }
203
204 const responsiveSize = panelRect
205 ? resolveResponsiveBrowserViewportSize(panelRect, desktopOverlay?.zoomFactor)
206 : { width: 1024, height: 768 };
207 void commitBrowserViewportChange(tabId, { _tag: "freeform", ...responsiveSize }).catch(
208 () => undefined,
209 );
210 };
211
212 useEffect(() => {
213 if (!tabId) return;
214 return subscribeBrowserViewportChange(tabId, handleViewportChange);
215 }, [handleViewportChange, tabId]);
216
217 const handleBack = useCallback(() => {
218 if (previewBridge && tabId) void previewBridge.goBack(tabId);
219 }, [tabId]);
220
221 const handleForward = useCallback(() => {
222 if (previewBridge && tabId) void previewBridge.goForward(tabId);
223 }, [tabId]);
224
225 const handleOpenInBrowser = useCallback(() => {
226 if (!localApi || !url) return;
227 void localApi.shell.openExternal(url).catch(() => undefined);
228 }, [url]);
229
230 const handleCapture = useCallback(
231 (record: boolean) => {
232 if (!previewBridge || !tabId) return;
233 const bridge = previewBridge;
234 const recordingThisTab = activeRecordingTabId === tabId;
235 if (recordingThisTab) {
236 void stopBrowserRecording(tabId).then(
237 (artifact) => {
238 if (!artifact) return;
239 let pathCopied = false;
240 let toastId: ReturnType<typeof toastManager.add>;
241
242 const copyPath = () => {
243 if (!navigator.clipboard?.writeText) {
244 toastManager.update(
245 toastId,
246 stackedThreadToast({
247 type: "error",
248 title: "Unable to copy recording path",
249 description: "Clipboard API unavailable.",
250 actionProps: revealAction,
251 }),
252 );
253 return;
254 }
255
256 void navigator.clipboard.writeText(artifact.path).then(
257 () => {
258 pathCopied = true;
259 updateRecordingToast();
260 window.setTimeout(() => {
261 pathCopied = false;
262 updateRecordingToast();
263 }, 2_000);
264 },
265 (error) => {
266 toastManager.update(
267 toastId,
268 stackedThreadToast({
269 type: "error",
270 title: "Unable to copy recording path",
271 description: error instanceof Error ? error.message : "An error occurred.",
272 actionProps: revealAction,
273 }),
274 );
275 },
276 );
277 };
278
279 const revealAction = {
280 children: revealInFileExplorerLabel(navigator.platform),
281 onClick: () => void bridge.revealArtifact(artifact.path),
282 };
283 const updateRecordingToast = () => {
284 toastManager.update(
285 toastId,
286 stackedThreadToast({
287 type: "success",
288 title: "Recording saved",
289 actionProps: revealAction,
290 data: {
291 secondaryActionProps: {
292 children: pathCopied ? "Copied!" : "Copy path",
293 disabled: pathCopied,
294 onClick: copyPath,
295 },
296 secondaryActionVariant: "outline",
297 },
298 }),
299 );
300 };
301
302 toastId = toastManager.add(
303 stackedThreadToast({
304 type: "success",
305 title: "Recording saved",
306 actionProps: revealAction,
307 data: {
308 secondaryActionProps: {
309 children: "Copy path",
310 onClick: copyPath,
311 },
312 secondaryActionVariant: "outline",
313 },
314 }),
315 );
316 },
317 (error) => {
318 toastManager.add({
319 type: "error",
320 title: "Unable to stop recording",
321 description: error instanceof Error ? error.message : "An error occurred.",
322 });
323 },
324 );
325 return;
326 }
327 if (record) {
328 if (activeRecordingTabId !== null) {
329 toastManager.add({
330 type: "warning",
331 title: "Another preview is recording",
332 description: "Stop the active recording before starting a new one.",
333 });
334 return;
335 }
336 void startBrowserRecording(tabId).catch((error) => {
337 toastManager.add({
338 type: "error",
339 title: "Unable to start recording",
340 description: error instanceof Error ? error.message : "An error occurred.",
341 });
342 });
343 return;
344 }
345 void bridge.captureScreenshot(tabId).then(
346 (artifact) => {
347 const revealAction = {
348 children: revealInFileExplorerLabel(navigator.platform),
349 onClick: () => void bridge.revealArtifact(artifact.path),
350 };
351 let pathCopied = false;
352 let imageCopied = false;
353 let toastId: ReturnType<typeof toastManager.add>;
354
355 const updateScreenshotToast = (
356 type: "success" | "error" = "success",
357 title = "Screenshot saved",
358 description?: string,
359 ) => {
360 toastManager.update(
361 toastId,
362 stackedThreadToast({
363 type,
364 title,
365 description,
366 actionProps: {
367 children: imageCopied ? "Copied!" : "Copy image",
368 disabled: imageCopied,
369 onClick: copyImage,
370 },
371 data: {
372 additionalActions: [
373 {
374 id: "copy-path",
375 props: {
376 children: pathCopied ? "Copied!" : "Copy path",
377 disabled: pathCopied,
378 onClick: copyPath,
379 },
380 },
381 ],
382 secondaryActionProps: {
383 ...revealAction,
384 },
385 secondaryActionVariant: "outline",
386 },
387 }),
388 );
389 };
390
391 const copyPath = () => {
392 if (!navigator.clipboard?.writeText) {
393 updateScreenshotToast(
394 "error",
395 "Unable to copy screenshot path",
396 "Clipboard API unavailable.",
397 );
398 return;
399 }
400
401 void navigator.clipboard.writeText(artifact.path).then(
402 () => {
403 pathCopied = true;
404 updateScreenshotToast();
405 window.setTimeout(() => {
406 pathCopied = false;
407 updateScreenshotToast();
408 }, 2_000);
409 },
410 (error) => {
411 updateScreenshotToast(
412 "error",
413 "Unable to copy screenshot path",
414 error instanceof Error ? error.message : "An error occurred.",
415 );
416 },
417 );
418 };
419
420 const copyImage = () => {
421 void bridge.copyArtifactToClipboard(artifact.path).then(
422 () => {
423 imageCopied = true;
424 updateScreenshotToast();
425 window.setTimeout(() => {
426 imageCopied = false;
427 updateScreenshotToast();
428 }, 2_000);
429 },
430 (error) => {
431 updateScreenshotToast(
432 "error",
433 "Unable to copy screenshot",
434 error instanceof Error ? error.message : "An error occurred.",
435 );
436 },
437 );
438 };
439
440 toastId = toastManager.add(
441 stackedThreadToast({
442 type: "success",
443 title: "Screenshot saved",
444 actionProps: {
445 children: "Copy image",
446 onClick: copyImage,
447 },
448 data: {
449 additionalActions: [
450 {
451 id: "copy-path",
452 props: {
453 children: "Copy path",
454 onClick: copyPath,
455 },
456 },
457 ],
458 secondaryActionProps: {
459 ...revealAction,
460 },
461 secondaryActionVariant: "outline",
462 },
463 }),
464 );
465 },
466 (error) => {
467 toastManager.add({
468 type: "error",
469 title: "Unable to capture screenshot",
470 description: error instanceof Error ? error.message : "An error occurred.",
471 });
472 },
473 );
474 },
475 [activeRecordingTabId, tabId],
476 );
477
478 const handlePickElement = useCallback(() => {
479 if (!previewBridge || !tabId) return;
480 if (pickActiveRef.current) {
481 void previewBridge.cancelPickElement(tabId).catch(() => undefined);
482 return;
483 }
484 // Snapshot whatever the user was focused on (typically the chat
485 // composer textarea or the chrome-row pick button) BEFORE main steals
486 // focus into the guest webContents. We restore it when the pick
487 // resolves so the user's typing context isn't lost — otherwise after
488 // every pick they'd have to click back into the textarea.
489 const previouslyFocused =
490 typeof document !== "undefined" ? (document.activeElement as HTMLElement | null) : null;
491 pickActiveRef.current = true;
492 setPickActive(true);
493 void (async () => {
494 try {
495 const annotation = await previewBridge.pickElement(tabId);
496 if (!annotation) return;
497 addPreviewAnnotation(threadRef, annotation);
498 const screenshotFile = await previewAnnotationScreenshotFile(annotation);
499 if (screenshotFile && annotation.screenshot) {
500 addImage(threadRef, {
501 type: "image",
502 id: annotation.id,
503 name: screenshotFile.name,
504 mimeType: screenshotFile.type,
505 sizeBytes: screenshotFile.size,
506 previewUrl: annotation.screenshot.dataUrl,
507 file: screenshotFile,
508 });
509 }
510 } catch {
511 // Picker failed (e.g. webview navigated). Treat as silent cancel.
512 } finally {
513 pickActiveRef.current = false;
514 // Avoid `setState on unmounted component` if the panel/thread closed
515 // while the pick was in flight.
516 if (isMountedRef.current) setPickActive(false);
517 // Best-effort: restore focus to whatever the user had before the
518 // pick stole it into the guest webContents. Skip if the previously-
519 // focused element was unmounted or is no longer focusable.
520 if (
521 previouslyFocused &&
522 previouslyFocused.isConnected &&
523 typeof previouslyFocused.focus === "function"
524 ) {
525 try {
526 previouslyFocused.focus({ preventScroll: true });
527 } catch {
528 // Some elements throw on .focus() (detached iframes, etc.).
529 }
530 }
531 }
532 })();
533 }, [addImage, addPreviewAnnotation, tabId, threadRef]);
534
535 // If the active tab changes mid-pick (close, thread switch, hot restart),
536 // tell main to tear down the in-flight session AND reset our local toggle
537 // state so the button doesn't get stuck pressed against a stale tab id.
538 useEffect(() => {
539 return () => {
540 if (!pickActiveRef.current) return;
541 pickActiveRef.current = false;
542 if (previewBridge && tabId) {
543 void previewBridge.cancelPickElement(tabId).catch(() => undefined);
544 }
545 if (isMountedRef.current) setPickActive(false);
546 };
547 }, [tabId]);
548
549 // Subscribe only while visible; `toggle-panel` is owned by ChatView's
550 // URL-aware handler regardless of whether the panel is currently mounted.
551 useEffect(() => {
552 if (!visible) return;
553 return subscribePreviewAction((action) => {
554 switch (action) {
555 case "refresh":
556 handleRefresh();
557 return;
558 case "focus-url":
559 setFocusUrlNonce((value) => (value ?? 0) + 1);
560 return;
561 case "zoom-in":
562 handleZoomIn();
563 return;
564 case "zoom-out":
565 handleZoomOut();
566 return;
567 case "reset-zoom":
568 handleResetZoom();
569 return;
570 case "toggle-panel":
571 return;
572 }
573 });
574 }, [handleRefresh, handleResetZoom, handleZoomIn, handleZoomOut, visible]);
575
576 return (
577 <div
578 className="flex min-h-0 flex-1 flex-col bg-background"
579 data-thread-key={scopedThreadKey(threadRef)}
580 >
581 <PreviewChromeRow
582 url={url}
583 displayUrl={displayUrl}
584 loading={loading}
585 loadProgress={loadProgress}
586 canGoBack={canGoBack}
587 canGoForward={canGoForward}
588 refreshDisabled={refreshDisabled}
589 focusUrlNonce={focusUrlNonce}
590 onBack={handleBack}
591 onForward={handleForward}
592 onRefresh={handleRefresh}
593 onSubmit={(next) => void handleSubmitUrl(next)}
594 onOpenInBrowser={tabId ? handleOpenInBrowser : undefined}
595 onCapture={previewBridge && tabId ? handleCapture : undefined}
596 captureDisabled={!desktopOverlay || isUnreachable}
597 recording={tabId !== null && activeRecordingTabId === tabId}
598 onPickElement={previewBridge && tabId ? handlePickElement : undefined}
599 pickActive={pickActive}
600 // Disable when there's no tab (nothing to pick on) OR the page
601 // failed to load (a React overlay covers the webview, so the
602 // user wouldn't be able to actually click anything underneath).
603 pickDisabled={!tabId || isUnreachable}
604 pickDisabledReason={
605 isUnreachable ? "Page didn't load — pick unavailable until the page renders" : undefined
606 }
607 trailingActions={
608 previewBridge ? (
609 <PreviewMoreMenu
610 tabId={tabId}
611 hasWebContents={desktopOverlay !== null}
612 zoomFactor={desktopOverlay?.zoomFactor ?? 1}
613 deviceToolbarVisible={viewport._tag !== "fill"}
614 onToggleDeviceToolbar={handleToggleDeviceToolbar}
615 />
616 ) : null
617 }
618 />
619
620 <div className="relative min-h-0 flex-1 overflow-hidden">
621 {tabId && snapshot && !showEmptyState ? (
622 <BrowserSurfaceSlot
623 key={tabId}
624 tabId={tabId}
625 visible={visible && !isUnreachable}
626 className="absolute inset-0 h-full w-full"
627 />
628 ) : null}
629 {showEmptyState ? (
630 <PreviewEmptyState
631 environmentId={threadRef.environmentId}
632 configuredUrls={configuredUrls}
633 recentlySeenUrls={previewState.recentlySeenUrls}
634 onOpenUrl={(next) => void handleOpenServerUrl(next)}
635 />
636 ) : null}
637 {snapshot && desktopOverlay ? (
638 <ZoomIndicator zoomFactor={desktopOverlay.zoomFactor} />
639 ) : null}
640 {tabId && desktopOverlay && !showEmptyState && !isUnreachable ? (
641 <AgentBrowserCursor
642 tabId={tabId}
643 zoomFactor={desktopOverlay.zoomFactor}
644 controller={controller}
645 />
646 ) : null}
647 {controller !== "none" ? (
648 <div className="pointer-events-none absolute left-3 top-3 z-40 rounded-full border border-border/70 bg-background/90 px-2.5 py-1 text-[11px] font-medium shadow-sm backdrop-blur">
649 {controller === "agent" ? "Agent controlling browser" : "Human control"}
650 </div>
651 ) : null}
652 {navStatus._tag === "LoadFailed" ? (
653 <div className="absolute inset-0 z-10 bg-background">
654 <PreviewUnreachable
655 url={navStatus.url}
656 code={navStatus.code}
657 description={navStatus.description}
658 onReload={handleRefresh}
659 />
660 </div>
661 ) : null}
662 </div>
663 </div>
664 );
665}