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

PreviewView.tsx

580 lines20.7 KB

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