The best way to control Claude Code, Codex and more from any computer or phone
perf(web): the browser preview view compiles with the React Compiler (#20476)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 16, 2026 at 18:46 UTC
e96db6f0c36bd38a079843fa316d2cca0b11306d
2 files changed
+405
-416
apps/web/reactCompiledFiles.ts
+1
@@ -51,4 +51,5 @@ export const REACT_COMPILED_FILES = [
51
"apps/web/src/hooks/useTheme.ts",
52
"apps/web/src/hooks/useSettings.ts",
53
"apps/web/src/components/chat/QueuedRunsControl.tsx",
54
+ "apps/web/src/components/preview/PreviewView.tsx",
55
] as const;
apps/web/src/components/preview/PreviewView.tsx
+404
-416
@@ -1,6 +1,7 @@
1
"use client";
2
3
-import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3
+import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
4
+import { settlePromise } from "@t3tools/client-runtime/state/runtime";
5
import { previewStreamDownloadUrl } from "@t3tools/client-runtime/preview/server-browser-stream";
6
import {
7
isAtomCommandInterrupted,
@@ -18,7 +19,7 @@ import {
19
type PreviewAdjustInput,
20
} from "@t3tools/contracts";
21
import { normalizePreviewUrl, resolveAddressBarInput } from "@t3tools/shared/preview";
21
-import { useCallback, useEffect, useRef, useState } from "react";
22
+import { useEffect, useEffectEvent, useRef, useState } from "react";
23
24
import {
25
BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT,
@@ -152,10 +153,6 @@ export function PreviewView({
153
const activeRecordingTabIds = useActiveBrowserRecordingTabIds();
154
const pickActiveRef = useRef<{ cancelled: boolean } | null>(null);
155
const isMountedRef = useRef(true);
155
- // Kept in sync so the title effect can depend on the stable thread key
156
- // instead of the thread object, which is recreated on every update.
157
- const threadRefRef = useRef(threadRef);
158
- threadRefRef.current = threadRef;
156
const previewState = useThreadPreviewState(threadRef);
157
const recentHistoryEntries = useThreadRecentHistory(
158
threadRef,
@@ -242,151 +239,139 @@ export function PreviewView({
239
const navUrl = navStatus._tag === "Success" ? navStatus.url : null;
240
const navTitle = navStatus._tag === "Success" ? navStatus.title : null;
241
const latestHistoryUrl = recentHistoryEntries[0]?.url;
245
- const threadKey = scopedThreadKey(threadRef);
242
+ // Keyed on the ids rather than threadRef, which is recreated on every update.
243
+ const { environmentId: threadEnvironmentId, threadId } = threadRef;
244
useEffect(() => {
245
if (!navUrl || !navTitle || !latestHistoryUrl) return;
248
- setTitleForThreadUrl(threadRefRef.current, navUrl, navTitle, environmentHostname);
249
- }, [environmentHostname, latestHistoryUrl, navTitle, navUrl, threadKey]);
246
+ setTitleForThreadUrl(
247
+ scopeThreadRef(threadEnvironmentId, threadId),
248
+ navUrl,
249
+ navTitle,
250
+ environmentHostname,
251
+ );
252
+ }, [environmentHostname, latestHistoryUrl, navTitle, navUrl, threadEnvironmentId, threadId]);
253
251
- const navigateToResolvedUrl = useCallback(
252
- async (resolvedUrl: string) => {
253
- if (isServerTab && serverSurfaceRef.current) {
254
- if (serverInputDisabled) return false;
255
- serverSurfaceRef.current.navigate(resolvedUrl);
256
- rememberPreviewUrl(threadRef, resolvedUrl);
257
- return true;
258
- }
259
- if (runtimeTabId && previewBridge) {
260
- await previewBridge.navigate(runtimeTabId, resolvedUrl);
261
- rememberPreviewUrl(threadRef, resolvedUrl);
262
- return true;
263
- }
264
- const result = await openPreviewSession({ openPreview: open, threadRef, url: resolvedUrl });
265
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
266
- const error = squashAtomCommandFailure(result);
267
- if (error instanceof BrowserSettingsReadError) {
268
- toastManager.add({
269
- type: "error",
270
- title: "Unable to open browser",
271
- description: error.message,
272
- });
273
- }
254
+ const navigateToResolvedUrl = async (resolvedUrl: string) => {
255
+ if (isServerTab && serverSurfaceRef.current) {
256
+ if (serverInputDisabled) return false;
257
+ serverSurfaceRef.current.navigate(resolvedUrl);
258
+ rememberPreviewUrl(threadRef, resolvedUrl);
259
+ return true;
260
+ }
261
+ if (runtimeTabId && previewBridge) {
262
+ await previewBridge.navigate(runtimeTabId, resolvedUrl);
263
+ rememberPreviewUrl(threadRef, resolvedUrl);
264
+ return true;
265
+ }
266
+ const result = await openPreviewSession({ openPreview: open, threadRef, url: resolvedUrl });
267
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
268
+ const error = squashAtomCommandFailure(result);
269
+ if (error instanceof BrowserSettingsReadError) {
270
+ toastManager.add({
271
+ type: "error",
272
+ title: "Unable to open browser",
273
+ description: error.message,
274
+ });
275
}
275
- return result._tag === "Success";
276
- },
277
- [isServerTab, open, runtimeTabId, serverInputDisabled, threadRef],
278
- );
276
+ }
277
+ return result._tag === "Success";
278
+ };
279
280
- const handleSubmitUrl = useCallback(
281
- async (next: string) => {
282
- try {
283
- const resolved = resolveAddressBarInput(next);
284
- if (await navigateToResolvedUrl(resolved)) {
285
- recordVisitForThread(threadRef, resolved);
286
- }
287
- } catch {}
288
- },
289
- [navigateToResolvedUrl, threadRef],
290
- );
280
+ const handleSubmitUrl = async (next: string) => {
281
+ try {
282
+ const resolved = resolveAddressBarInput(next);
283
+ if (await navigateToResolvedUrl(resolved)) {
284
+ recordVisitForThread(threadRef, resolved);
285
+ }
286
+ } catch {}
287
+ };
288
292
- const handleOpenServerUrl = useCallback(
293
- async (next: string) => {
294
- try {
295
- const resolved =
296
- isServerTab || !previewBridge
297
- ? normalizePreviewUrl(next)
298
- : resolveDiscoveredServerUrl(threadRef.environmentId, next);
299
- if (await navigateToResolvedUrl(resolved)) {
300
- recordVisitForThread(threadRef, next);
301
- }
302
- } catch {}
303
- },
304
- [isServerTab, navigateToResolvedUrl, threadRef],
305
- );
289
+ const handleOpenServerUrl = async (next: string) => {
290
+ try {
291
+ const resolved =
292
+ isServerTab || !previewBridge
293
+ ? normalizePreviewUrl(next)
294
+ : resolveDiscoveredServerUrl(threadRef.environmentId, next);
295
+ if (await navigateToResolvedUrl(resolved)) {
296
+ recordVisitForThread(threadRef, next);
297
+ }
298
+ } catch {}
299
+ };
300
307
- const handleRefresh = useCallback(() => {
301
+ const handleRefresh = () => {
302
if (isServerTab) serverSurfaceRef.current?.reload();
303
else if (previewBridge && runtimeTabId) void previewBridge.refresh(runtimeTabId);
310
- }, [isServerTab, runtimeTabId]);
304
+ };
305
312
- const adjustServerTab = useCallback(
313
- async (change: Omit<PreviewAdjustInput, "threadId" | "tabId">) => {
314
- if (!tabId) return;
315
- const result = await adjust({
316
- environmentId: threadRef.environmentId,
317
- input: { threadId: threadRef.threadId, tabId, ...change },
306
+ const adjustServerTab = async (change: Omit<PreviewAdjustInput, "threadId" | "tabId">) => {
307
+ if (!tabId) return;
308
+ const result = await adjust({
309
+ environmentId: threadRef.environmentId,
310
+ input: { threadId: threadRef.threadId, tabId, ...change },
311
+ });
312
+ if (result._tag === "Failure") {
313
+ const error = squashAtomCommandFailure(result);
314
+ toastManager.add({
315
+ type: "error",
316
+ title: "Unable to change the browser tab",
317
+ description: error instanceof Error ? error.message : "An error occurred.",
318
});
319
- if (result._tag === "Failure") {
320
- const error = squashAtomCommandFailure(result);
321
- toastManager.add({
322
- type: "error",
323
- title: "Unable to change the browser tab",
324
- description: error instanceof Error ? error.message : "An error occurred.",
325
- });
326
- return;
327
- }
328
- updatePreviewServerSnapshot(threadRef, result.value);
329
- },
330
- [adjust, tabId, threadRef],
331
- );
319
+ return;
320
+ }
321
+ updatePreviewServerSnapshot(threadRef, result.value);
322
+ };
323
324
const serverZoomFactor = snapshot?.zoomFactor ?? DEFAULT_PREVIEW_ZOOM_FACTOR;
334
- const stepServerZoom = useCallback(
335
- (direction: -1 | 0 | 1) => {
336
- const index = PREVIEW_ZOOM_LEVELS.indexOf(serverZoomFactor);
337
- const next =
338
- direction === 0
339
- ? DEFAULT_PREVIEW_ZOOM_FACTOR
340
- : PREVIEW_ZOOM_LEVELS[
341
- Math.min(
342
- Math.max((index < 0 ? 7 : index) + direction, 0),
343
- PREVIEW_ZOOM_LEVELS.length - 1,
344
- )
345
- ]!;
346
- if (next !== serverZoomFactor) void adjustServerTab({ zoomFactor: next });
347
- },
348
- [adjustServerTab, serverZoomFactor],
349
- );
325
+ const stepServerZoom = (direction: -1 | 0 | 1) => {
326
+ const index = PREVIEW_ZOOM_LEVELS.indexOf(serverZoomFactor);
327
+ const next =
328
+ direction === 0
329
+ ? DEFAULT_PREVIEW_ZOOM_FACTOR
330
+ : PREVIEW_ZOOM_LEVELS[
331
+ Math.min(
332
+ Math.max((index < 0 ? 7 : index) + direction, 0),
333
+ PREVIEW_ZOOM_LEVELS.length - 1,
334
+ )
335
+ ]!;
336
+ if (next !== serverZoomFactor) void adjustServerTab({ zoomFactor: next });
337
+ };
338
351
- const handleZoomIn = useCallback(() => {
339
+ const handleZoomIn = () => {
340
if (serverOwnsRendering) stepServerZoom(1);
341
else if (previewBridge && runtimeTabId) void previewBridge.zoomIn(runtimeTabId);
354
- }, [runtimeTabId, serverOwnsRendering, stepServerZoom]);
342
+ };
343
356
- const handleZoomOut = useCallback(() => {
344
+ const handleZoomOut = () => {
345
if (serverOwnsRendering) stepServerZoom(-1);
346
else if (previewBridge && runtimeTabId) void previewBridge.zoomOut(runtimeTabId);
359
- }, [runtimeTabId, serverOwnsRendering, stepServerZoom]);
347
+ };
348
361
- const handleResetZoom = useCallback(() => {
349
+ const handleResetZoom = () => {
350
if (serverOwnsRendering) stepServerZoom(0);
351
else if (previewBridge && runtimeTabId) void previewBridge.resetZoom(runtimeTabId);
364
- }, [runtimeTabId, serverOwnsRendering, stepServerZoom]);
352
+ };
353
366
- const handleViewportChange = useCallback(
367
- async (nextViewport: PreviewViewportSetting) => {
368
- if (!tabId) return;
369
- const result = await resize({
370
- environmentId: threadRef.environmentId,
371
- input: {
372
- threadId: threadRef.threadId,
373
- tabId,
374
- viewport: nextViewport,
375
- },
354
+ const handleViewportChange = async (nextViewport: PreviewViewportSetting) => {
355
+ if (!tabId) return;
356
+ const result = await resize({
357
+ environmentId: threadRef.environmentId,
358
+ input: {
359
+ threadId: threadRef.threadId,
360
+ tabId,
361
+ viewport: nextViewport,
362
+ },
363
+ });
364
+ if (result._tag === "Failure") {
365
+ const error = squashAtomCommandFailure(result);
366
+ toastManager.add({
367
+ type: "error",
368
+ title: "Unable to resize browser viewport",
369
+ description: error instanceof Error ? error.message : "An error occurred.",
370
});
377
- if (result._tag === "Failure") {
378
- const error = squashAtomCommandFailure(result);
379
- toastManager.add({
380
- type: "error",
381
- title: "Unable to resize browser viewport",
382
- description: error instanceof Error ? error.message : "An error occurred.",
383
- });
384
- throw error;
385
- }
386
- updatePreviewServerSnapshot(threadRef, result.value);
387
- },
388
- [resize, tabId, threadRef],
389
- );
371
+ throw error;
372
+ }
373
+ updatePreviewServerSnapshot(threadRef, result.value);
374
+ };
375
376
const handleToggleDeviceToolbar = () => {
377
if (!runtimeTabId) return;
@@ -405,25 +390,28 @@ export function PreviewView({
390
).catch(() => undefined);
391
};
392
393
+ const onViewportChange = useEffectEvent(handleViewportChange);
394
useEffect(() => {
395
if (!runtimeTabId) return;
410
- return subscribeBrowserViewportChange(runtimeTabId, handleViewportChange);
411
- }, [handleViewportChange, runtimeTabId]);
396
+ return subscribeBrowserViewportChange(runtimeTabId, (nextViewport) =>
397
+ onViewportChange(nextViewport),
398
+ );
399
+ }, [runtimeTabId]);
400
413
- const handleBack = useCallback(() => {
401
+ const handleBack = () => {
402
if (isServerTab) serverSurfaceRef.current?.history(-1);
403
else if (previewBridge && runtimeTabId) void previewBridge.goBack(runtimeTabId);
416
- }, [isServerTab, runtimeTabId]);
404
+ };
405
418
- const handleForward = useCallback(() => {
406
+ const handleForward = () => {
407
if (isServerTab) serverSurfaceRef.current?.history(1);
408
else if (previewBridge && runtimeTabId) void previewBridge.goForward(runtimeTabId);
421
- }, [isServerTab, runtimeTabId]);
409
+ };
410
423
- const handleOpenInBrowser = useCallback(() => {
411
+ const handleOpenInBrowser = () => {
412
if (!localApi || !url) return;
413
void localApi.shell.openExternal(url).catch(() => undefined);
426
- }, [url]);
414
+ };
415
416
const moveTarget = alternatePreviewRuntime(
417
threadRef.environmentId,
@@ -433,7 +421,7 @@ export function PreviewView({
421
);
422
const moveLabel =
423
moveTarget === "server" ? `Open in ${environmentLabel}'s browser` : "Open on this computer";
436
- const handleMoveTab = useCallback(async () => {
424
+ const handleMoveTab = async () => {
425
if (!moveTarget || !tabId || !snapshot) return;
426
const result = await openPreviewSession({
427
openPreview: open,
@@ -462,9 +450,9 @@ export function PreviewView({
450
}
451
useRightPanelStore.getState().openBrowser(threadRef, result.value.tabId);
452
await closePreviewSession({ closePreview, snapshot, tabId, threadRef });
465
- }, [closePreview, moveTarget, open, snapshot, tabId, threadRef, url, viewport]);
453
+ };
454
467
- const handlePictureInPicture = useCallback(() => {
455
+ const handlePictureInPicture = () => {
456
if (!tabId) return;
457
if (miniPlayerTabId === tabId) {
458
usePreviewMiniPlayerStore.getState().close(threadRef);
@@ -472,7 +460,7 @@ export function PreviewView({
460
}
461
usePreviewMiniPlayerStore.getState().open(threadRef, browserMiniPlayerSource(tabId));
462
useRightPanelStore.getState().close(threadRef);
475
- }, [miniPlayerTabId, tabId, threadRef]);
463
+ };
464
465
const desktopCall = (op: ((tabId: string) => Promise<void>) | undefined) => () => {
466
if (op && runtimeTabId) void op(runtimeTabId).catch(() => undefined);
@@ -516,7 +504,7 @@ export function PreviewView({
504
}
505
: null;
506
519
- const handleNativePictureInPicture = useCallback(() => {
507
+ const handleNativePictureInPicture = () => {
508
if (!previewBridge || !runtimeTabId) return;
509
const operation = desktopOverlay?.pictureInPicture
510
? previewBridge.pictureInPicture.close
@@ -528,168 +516,28 @@ export function PreviewView({
516
description: error instanceof Error ? error.message : "An error occurred.",
517
});
518
});
531
- }, [desktopOverlay?.pictureInPicture, runtimeTabId]);
532
-
533
- const handleCapture = useCallback(
534
- (record: boolean) => {
535
- if (!previewBridge || !runtimeTabId || !tabId) return;
536
- const bridge = previewBridge;
537
- if (recordingRuntimeTabId) {
538
- void stopBrowserRecording(recordingRuntimeTabId).then(
539
- (artifact) => {
540
- if (!artifact) return;
541
- let pathCopied = false;
542
- let toastId: ReturnType<typeof toastManager.add>;
543
-
544
- const copyPath = () => {
545
- if (!navigator.clipboard?.writeText) {
546
- toastManager.update(
547
- toastId,
548
- stackedThreadToast({
549
- type: "error",
550
- title: "Unable to copy recording path",
551
- description: "Clipboard API unavailable.",
552
- actionProps: revealAction,
553
- }),
554
- );
555
- return;
556
- }
557
-
558
- void navigator.clipboard.writeText(artifact.path).then(
559
- () => {
560
- pathCopied = true;
561
- updateRecordingToast();
562
- window.setTimeout(() => {
563
- pathCopied = false;
564
- updateRecordingToast();
565
- }, 2_000);
566
- },
567
- (error) => {
568
- toastManager.update(
569
- toastId,
570
- stackedThreadToast({
571
- type: "error",
572
- title: "Unable to copy recording path",
573
- description: error instanceof Error ? error.message : "An error occurred.",
574
- actionProps: revealAction,
575
- }),
576
- );
577
- },
578
- );
579
- };
580
-
581
- const revealAction = {
582
- children: revealInFileExplorerLabel(navigator.platform),
583
- onClick: () => void bridge.revealArtifact(artifact.path),
584
- };
585
- const updateRecordingToast = () => {
586
- toastManager.update(
587
- toastId,
588
- stackedThreadToast({
589
- type: "success",
590
- title: "Recording saved",
591
- actionProps: revealAction,
592
- data: {
593
- secondaryActionProps: {
594
- children: pathCopied ? "Copied!" : "Copy path",
595
- disabled: pathCopied,
596
- onClick: copyPath,
597
- },
598
- secondaryActionVariant: "outline",
599
- },
600
- }),
601
- );
602
- };
519
+ };
520
604
- toastId = toastManager.add(
605
- stackedThreadToast({
606
- type: "success",
607
- title: "Recording saved",
608
- actionProps: revealAction,
609
- data: {
610
- secondaryActionProps: {
611
- children: "Copy path",
612
- onClick: copyPath,
613
- },
614
- secondaryActionVariant: "outline",
615
- },
616
- }),
617
- );
618
- },
619
- (error) => {
620
- toastManager.add({
621
- type: "error",
622
- title: "Unable to stop recording",
623
- description: error instanceof Error ? error.message : "An error occurred.",
624
- });
625
- },
626
- );
627
- return;
628
- }
629
- if (record) {
630
- void startBrowserRecording(runtimeTabId, threadRef, tabId).catch((error) => {
631
- const description = error instanceof Error ? error.message : "An error occurred.";
632
- if (isBrowserRecordingStartCancelledError(error)) return;
633
- toastManager.add({
634
- type: "error",
635
- title: "Unable to start recording",
636
- description,
637
- });
638
- });
639
- return;
640
- }
641
- void bridge.captureScreenshot(runtimeTabId).then(
521
+ const handleCapture = (record: boolean) => {
522
+ if (!previewBridge || !runtimeTabId || !tabId) return;
523
+ const bridge = previewBridge;
524
+ if (recordingRuntimeTabId) {
525
+ void stopBrowserRecording(recordingRuntimeTabId).then(
526
(artifact) => {
643
- const revealAction = {
644
- children: revealInFileExplorerLabel(navigator.platform),
645
- onClick: () => void bridge.revealArtifact(artifact.path),
646
- };
527
+ if (!artifact) return;
528
let pathCopied = false;
648
- let imageCopied = false;
529
let toastId: ReturnType<typeof toastManager.add>;
530
651
- const updateScreenshotToast = (
652
- type: "success" | "error" = "success",
653
- title = "Screenshot saved",
654
- description?: string,
655
- ) => {
656
- toastManager.update(
657
- toastId,
658
- stackedThreadToast({
659
- type,
660
- title,
661
- description,
662
- actionProps: {
663
- children: imageCopied ? "Copied!" : "Copy image",
664
- disabled: imageCopied,
665
- onClick: copyImage,
666
- },
667
- data: {
668
- additionalActions: [
669
- {
670
- id: "copy-path",
671
- props: {
672
- children: pathCopied ? "Copied!" : "Copy path",
673
- disabled: pathCopied,
674
- onClick: copyPath,
675
- },
676
- },
677
- ],
678
- secondaryActionProps: {
679
- ...revealAction,
680
- },
681
- secondaryActionVariant: "outline",
682
- },
683
- }),
684
- );
685
- };
686
-
531
const copyPath = () => {
532
if (!navigator.clipboard?.writeText) {
689
- updateScreenshotToast(
690
- "error",
691
- "Unable to copy screenshot path",
692
- "Clipboard API unavailable.",
533
+ toastManager.update(
534
+ toastId,
535
+ stackedThreadToast({
536
+ type: "error",
537
+ title: "Unable to copy recording path",
538
+ description: "Clipboard API unavailable.",
539
+ actionProps: revealAction,
540
+ }),
541
);
542
return;
543
}
@@ -697,48 +545,110 @@ export function PreviewView({
545
void navigator.clipboard.writeText(artifact.path).then(
546
() => {
547
pathCopied = true;
700
- updateScreenshotToast();
548
+ updateRecordingToast();
549
window.setTimeout(() => {
550
pathCopied = false;
703
- updateScreenshotToast();
551
+ updateRecordingToast();
552
}, 2_000);
553
},
554
(error) => {
707
- updateScreenshotToast(
708
- "error",
709
- "Unable to copy screenshot path",
710
- error instanceof Error ? error.message : "An error occurred.",
555
+ toastManager.update(
556
+ toastId,
557
+ stackedThreadToast({
558
+ type: "error",
559
+ title: "Unable to copy recording path",
560
+ description: error instanceof Error ? error.message : "An error occurred.",
561
+ actionProps: revealAction,
562
+ }),
563
);
564
},
565
);
566
};
567
716
- const copyImage = () => {
717
- void bridge.copyArtifactToClipboard(artifact.path).then(
718
- () => {
719
- imageCopied = true;
720
- updateScreenshotToast();
721
- window.setTimeout(() => {
722
- imageCopied = false;
723
- updateScreenshotToast();
724
- }, 2_000);
725
- },
726
- (error) => {
727
- updateScreenshotToast(
728
- "error",
729
- "Unable to copy screenshot",
730
- error instanceof Error ? error.message : "An error occurred.",
731
- );
732
- },
568
+ const revealAction = {
569
+ children: revealInFileExplorerLabel(navigator.platform),
570
+ onClick: () => void bridge.revealArtifact(artifact.path),
571
+ };
572
+ const updateRecordingToast = () => {
573
+ toastManager.update(
574
+ toastId,
575
+ stackedThreadToast({
576
+ type: "success",
577
+ title: "Recording saved",
578
+ actionProps: revealAction,
579
+ data: {
580
+ secondaryActionProps: {
581
+ children: pathCopied ? "Copied!" : "Copy path",
582
+ disabled: pathCopied,
583
+ onClick: copyPath,
584
+ },
585
+ secondaryActionVariant: "outline",
586
+ },
587
+ }),
588
);
589
};
590
591
toastId = toastManager.add(
592
stackedThreadToast({
593
type: "success",
739
- title: "Screenshot saved",
594
+ title: "Recording saved",
595
+ actionProps: revealAction,
596
+ data: {
597
+ secondaryActionProps: {
598
+ children: "Copy path",
599
+ onClick: copyPath,
600
+ },
601
+ secondaryActionVariant: "outline",
602
+ },
603
+ }),
604
+ );
605
+ },
606
+ (error) => {
607
+ toastManager.add({
608
+ type: "error",
609
+ title: "Unable to stop recording",
610
+ description: error instanceof Error ? error.message : "An error occurred.",
611
+ });
612
+ },
613
+ );
614
+ return;
615
+ }
616
+ if (record) {
617
+ void startBrowserRecording(runtimeTabId, threadRef, tabId).catch((error) => {
618
+ const description = error instanceof Error ? error.message : "An error occurred.";
619
+ if (isBrowserRecordingStartCancelledError(error)) return;
620
+ toastManager.add({
621
+ type: "error",
622
+ title: "Unable to start recording",
623
+ description,
624
+ });
625
+ });
626
+ return;
627
+ }
628
+ void bridge.captureScreenshot(runtimeTabId).then(
629
+ (artifact) => {
630
+ const revealAction = {
631
+ children: revealInFileExplorerLabel(navigator.platform),
632
+ onClick: () => void bridge.revealArtifact(artifact.path),
633
+ };
634
+ let pathCopied = false;
635
+ let imageCopied = false;
636
+ let toastId: ReturnType<typeof toastManager.add>;
637
+
638
+ const updateScreenshotToast = (
639
+ type: "success" | "error" = "success",
640
+ title = "Screenshot saved",
641
+ description?: string,
642
+ ) => {
643
+ toastManager.update(
644
+ toastId,
645
+ stackedThreadToast({
646
+ type,
647
+ title,
648
+ description,
649
actionProps: {
741
- children: "Copy image",
650
+ children: imageCopied ? "Copied!" : "Copy image",
651
+ disabled: imageCopied,
652
onClick: copyImage,
653
},
654
data: {
@@ -746,7 +656,8 @@ export function PreviewView({
656
{
657
id: "copy-path",
658
props: {
749
- children: "Copy path",
659
+ children: pathCopied ? "Copied!" : "Copy path",
660
+ disabled: pathCopied,
661
onClick: copyPath,
662
},
663
},
@@ -758,20 +669,94 @@ export function PreviewView({
669
},
670
}),
671
);
761
- },
762
- (error) => {
763
- toastManager.add({
764
- type: "error",
765
- title: "Unable to capture screenshot",
766
- description: error instanceof Error ? error.message : "An error occurred.",
767
- });
768
- },
769
- );
770
- },
771
- [recordingRuntimeTabId, runtimeTabId, tabId, threadRef],
772
- );
672
+ };
673
+
674
+ const copyPath = () => {
675
+ if (!navigator.clipboard?.writeText) {
676
+ updateScreenshotToast(
677
+ "error",
678
+ "Unable to copy screenshot path",
679
+ "Clipboard API unavailable.",
680
+ );
681
+ return;
682
+ }
683
774
- const handlePickElement = useCallback(() => {
684
+ void navigator.clipboard.writeText(artifact.path).then(
685
+ () => {
686
+ pathCopied = true;
687
+ updateScreenshotToast();
688
+ window.setTimeout(() => {
689
+ pathCopied = false;
690
+ updateScreenshotToast();
691
+ }, 2_000);
692
+ },
693
+ (error) => {
694
+ updateScreenshotToast(
695
+ "error",
696
+ "Unable to copy screenshot path",
697
+ error instanceof Error ? error.message : "An error occurred.",
698
+ );
699
+ },
700
+ );
701
+ };
702
+
703
+ const copyImage = () => {
704
+ void bridge.copyArtifactToClipboard(artifact.path).then(
705
+ () => {
706
+ imageCopied = true;
707
+ updateScreenshotToast();
708
+ window.setTimeout(() => {
709
+ imageCopied = false;
710
+ updateScreenshotToast();
711
+ }, 2_000);
712
+ },
713
+ (error) => {
714
+ updateScreenshotToast(
715
+ "error",
716
+ "Unable to copy screenshot",
717
+ error instanceof Error ? error.message : "An error occurred.",
718
+ );
719
+ },
720
+ );
721
+ };
722
+
723
+ toastId = toastManager.add(
724
+ stackedThreadToast({
725
+ type: "success",
726
+ title: "Screenshot saved",
727
+ actionProps: {
728
+ children: "Copy image",
729
+ onClick: copyImage,
730
+ },
731
+ data: {
732
+ additionalActions: [
733
+ {
734
+ id: "copy-path",
735
+ props: {
736
+ children: "Copy path",
737
+ onClick: copyPath,
738
+ },
739
+ },
740
+ ],
741
+ secondaryActionProps: {
742
+ ...revealAction,
743
+ },
744
+ secondaryActionVariant: "outline",
745
+ },
746
+ }),
747
+ );
748
+ },
749
+ (error) => {
750
+ toastManager.add({
751
+ type: "error",
752
+ title: "Unable to capture screenshot",
753
+ description: error instanceof Error ? error.message : "An error occurred.",
754
+ });
755
+ },
756
+ );
757
+ };
758
+
759
+ const handlePickElement = () => {
760
if (!previewBridge || !runtimeTabId) return;
761
if (pickActiveRef.current) {
762
pickActiveRef.current.cancelled = true;
@@ -787,85 +772,85 @@ export function PreviewView({
772
let submitted = false;
773
pickActiveRef.current = pickRequest;
774
setPickActive(true);
790
- void (async () => {
791
- try {
792
- await previewBridge.setAnnotationSendEnabled?.(
793
- runtimeTabId,
794
- Boolean(onSendAnnotation) &&
795
- readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope),
775
+ const finishPick = () => {
776
+ const isCurrentPick = pickActiveRef.current === pickRequest;
777
+ if (isCurrentPick) {
778
+ pickActiveRef.current = null;
779
+ if (isMountedRef.current) setPickActive(false);
780
+ }
781
+ if (
782
+ (isCurrentPick || submitted) &&
783
+ previouslyFocused &&
784
+ previouslyFocused.isConnected &&
785
+ typeof previouslyFocused.focus === "function"
786
+ ) {
787
+ try {
788
+ previouslyFocused.focus({ preventScroll: true });
789
+ } catch {}
790
+ }
791
+ };
792
+ // A failed pick is dropped silently; finishPick still releases the picker.
793
+ const bridge = previewBridge;
794
+ void settlePromise(async () => {
795
+ await bridge.setAnnotationSendEnabled?.(
796
+ runtimeTabId,
797
+ Boolean(onSendAnnotation) &&
798
+ readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope),
799
+ );
800
+ if (pickRequest.cancelled) return;
801
+ const result = await bridge.pickElement(runtimeTabId);
802
+ if (!result || pickRequest.cancelled) return;
803
+ // Nothing that happens after this point (a second picker click, a tab
804
+ // change, unmount) may discard it, so the pick stops being cancellable
805
+ // here rather than in finishPick.
806
+ if (pickActiveRef.current === pickRequest) {
807
+ pickActiveRef.current = null;
808
+ if (isMountedRef.current) setPickActive(false);
809
+ submitted = true;
810
+ }
811
+ const { annotation: picked, submission, screenshotFailed = false } = result;
812
+ // The structured annotation is still sendable when its optional crop
813
+ // stalls or fails, so tell the user what they lost and keep going
814
+ // instead of holding the composer for an attachment that never lands.
815
+ // The stored copy drops the screenshot on failure, otherwise the prompt
816
+ // would tell the agent a crop is attached when none was sent.
817
+ const capture = capturePreviewAnnotationScreenshot(picked);
818
+ const cropDropped = screenshotFailed || capture.status === "failed";
819
+ const annotation = capture.status === "failed" ? { ...picked, screenshot: null } : picked;
820
+ addPreviewAnnotation(threadRef, annotation);
821
+ if (cropDropped) {
822
+ toastManager.add(
823
+ stackedThreadToast({
824
+ type: "error",
825
+ title: "Could not capture the picked element",
826
+ description: "The annotation was kept without the screenshot.",
827
+ }),
828
);
797
- if (pickRequest.cancelled) return;
798
- const result = await previewBridge.pickElement(runtimeTabId);
799
- if (!result || pickRequest.cancelled) return;
800
- // Nothing that happens after this point (a second picker click, a tab
801
- // change, unmount) may discard it, so the pick stops being cancellable
802
- // here rather than in `finally`.
803
- if (pickActiveRef.current === pickRequest) {
804
- pickActiveRef.current = null;
805
- if (isMountedRef.current) setPickActive(false);
806
- submitted = true;
807
- }
808
- const { annotation: picked, submission, screenshotFailed = false } = result;
809
- // The structured annotation is still sendable when its optional crop
810
- // stalls or fails, so tell the user what they lost and keep going
811
- // instead of holding the composer for an attachment that never lands.
812
- // The stored copy drops the screenshot on failure, otherwise the prompt
813
- // would tell the agent a crop is attached when none was sent.
814
- const capture = capturePreviewAnnotationScreenshot(picked);
815
- const cropDropped = screenshotFailed || capture.status === "failed";
816
- const annotation = capture.status === "failed" ? { ...picked, screenshot: null } : picked;
817
- addPreviewAnnotation(threadRef, annotation);
818
- if (cropDropped) {
819
- toastManager.add(
820
- stackedThreadToast({
821
- type: "error",
822
- title: "Could not capture the picked element",
823
- description: "The annotation was kept without the screenshot.",
824
- }),
825
- );
826
- }
827
- const screenshotFile = capture.status === "captured" ? capture.file : null;
828
- const image =
829
- screenshotFile && annotation.screenshot
830
- ? ({
831
- type: "image",
832
- id: annotation.id,
833
- name: screenshotFile.name,
834
- mimeType: screenshotFile.type,
835
- sizeBytes: screenshotFile.size,
836
- previewUrl: annotation.screenshot.dataUrl,
837
- file: screenshotFile,
838
- } satisfies ComposerImageAttachment)
839
- : null;
840
- if (image) {
841
- addImage(threadRef, image);
842
- }
843
- if (
844
- submission === "send" &&
845
- readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)
846
- ) {
847
- onSendAnnotation?.(annotation, image);
848
- }
849
- } catch {
850
- } finally {
851
- const isCurrentPick = pickActiveRef.current === pickRequest;
852
- if (isCurrentPick) {
853
- pickActiveRef.current = null;
854
- if (isMountedRef.current) setPickActive(false);
855
- }
856
- if (
857
- (isCurrentPick || submitted) &&
858
- previouslyFocused &&
859
- previouslyFocused.isConnected &&
860
- typeof previouslyFocused.focus === "function"
861
- ) {
862
- try {
863
- previouslyFocused.focus({ preventScroll: true });
864
- } catch {}
865
- }
829
}
867
- })();
868
- }, [addImage, addPreviewAnnotation, onSendAnnotation, runtimeTabId, threadRef]);
830
+ const screenshotFile = capture.status === "captured" ? capture.file : null;
831
+ const image =
832
+ screenshotFile && annotation.screenshot
833
+ ? ({
834
+ type: "image",
835
+ id: annotation.id,
836
+ name: screenshotFile.name,
837
+ mimeType: screenshotFile.type,
838
+ sizeBytes: screenshotFile.size,
839
+ previewUrl: annotation.screenshot.dataUrl,
840
+ file: screenshotFile,
841
+ } satisfies ComposerImageAttachment)
842
+ : null;
843
+ if (image) {
844
+ addImage(threadRef, image);
845
+ }
846
+ if (
847
+ submission === "send" &&
848
+ readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)
849
+ ) {
850
+ onSendAnnotation?.(annotation, image);
851
+ }
852
+ }).then(finishPick);
853
+ };
854
855
useEffect(() => {
856
if (!pickActive || !previewBridge || !runtimeTabId) return;
@@ -888,9 +873,8 @@ export function PreviewView({
873
874
// Subscribe only while visible; `toggle-panel` is owned by ChatView's
875
// URL-aware handler regardless of whether the panel is currently mounted.
891
- useEffect(() => {
892
- if (!visible) return;
893
- return subscribePreviewAction((action) => {
876
+ const onPreviewAction = useEffectEvent(
877
+ (action: Parameters<Parameters<typeof subscribePreviewAction>[0]>[0]) => {
878
switch (action) {
879
case "refresh":
880
handleRefresh();
@@ -910,8 +894,12 @@ export function PreviewView({
894
case "toggle-panel":
895
return;
896
}
913
- });
914
- }, [handleRefresh, handleResetZoom, handleZoomIn, handleZoomOut, visible]);
897
+ },
898
+ );
899
+ useEffect(() => {
900
+ if (!visible) return;
901
+ return subscribePreviewAction((action) => onPreviewAction(action));
902
+ }, [visible]);
903
904
return (
905
<div