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