Open History to see the last commit
1import {
2 createPreviewFramePainter,
3 createPreviewStreamClient,
4 previewStreamControlLabel,
5 previewStreamModifiers,
6 type PreviewStreamClient,
7 type PreviewStreamControl,
8 type PreviewStreamDownload,
9 type PreviewStreamFileChooser,
10 uploadPreviewStreamFiles,
11 type PreviewStreamInput,
12 type PreviewStreamMouseButton,
13 type PreviewStreamPointer,
14 type PreviewStreamViewport,
15 previewStreamHostSetupMessage,
16} from "@t3tools/client-runtime/preview/server-browser-stream";
17import type {
18 EnvironmentId,
19 PreviewStreamHostSetup,
20 PreviewViewportSetting,
21} from "@t3tools/contracts";
22import {
23 type FormEvent,
24 type KeyboardEvent,
25 type PointerEvent,
26 type Ref,
27 useEffect,
28 useEffectEvent,
29 useImperativeHandle,
30 useRef,
31 useState,
32} from "react";
33
34import { AgentCursorMark } from "~/components/preview/AgentBrowserCursor";
35import { CommandBlock } from "~/components/CommandBlock";
36import { Button } from "~/components/ui/button";
37import { Input } from "~/components/ui/input";
38import { toastManager } from "~/components/ui/toast";
39import { cn } from "~/lib/utils";
40import { refreshPreviewStreamAccess, usePreviewStreamAccess } from "~/state/previewStream";
41import { observeResize } from "~/lib/observeResize";
42
43export interface ServerBrowserHandle {
44 readonly navigate: (url: string) => void;
45 readonly history: (delta: -1 | 1) => void;
46 readonly reload: (options?: { readonly ignoreCache?: boolean }) => void;
47 readonly viewport: (setting: PreviewViewportSetting) => void;
48 readonly canvas: () => HTMLCanvasElement | null;
49}
50
51const RESIZE_THROTTLE_MS = 150;
52// Reuse nearby probes when a slow link would return the tap's answer after it ends.
53const PROBE_REUSE_PX = 24;
54const PROBE_REUSE_MS = 10_000;
55// Android keyboards report Backspace as text deletion, so keep a deletable sentinel.
56const INPUT_SENTINEL = "\u200b";
57const BACKSPACE = { key: "Backspace", code: "Backspace", keyCode: 8 } as const;
58const DELETE = { key: "Delete", code: "Delete", keyCode: 46 } as const;
59const MAX_UNAUTHORIZED_REFUSALS = 3;
60const TAP_SLOP_PX = 8;
61const MULTI_CLICK_MS = 500;
62const MULTI_CLICK_SLOP_PX = 4;
63const WHEEL_LINE_PX = 16;
64
65type MouseInput = Extract<PreviewStreamInput, { type: "mouse" }>;
66type WheelInput = Extract<PreviewStreamInput, { type: "wheel" }>;
67
68interface PagePoint {
69 readonly x: number;
70 readonly y: number;
71 readonly scale: number;
72}
73
74interface TouchGesture {
75 readonly pointerId: number;
76 readonly startX: number;
77 readonly startY: number;
78 lastX: number;
79 lastY: number;
80 panning: boolean;
81}
82
83interface TouchProbe {
84 readonly x: number;
85 readonly y: number;
86 editable: boolean | null;
87 answered: boolean;
88 tapped: boolean;
89}
90
91const buttonOf = (button: number): PreviewStreamMouseButton =>
92 button === 0 ? "left" : button === 1 ? "middle" : button === 2 ? "right" : "none";
93
94const pressedButtonOf = (buttons: number): PreviewStreamMouseButton =>
95 buttons & 1 ? "left" : buttons & 2 ? "right" : buttons & 4 ? "middle" : "none";
96
97/** Browsers may refuse a write that arrives after the key press; a toast button is a fresh gesture. */
98async function copyPageText(text: string) {
99 try {
100 await navigator.clipboard.writeText(text);
101 } catch {
102 const id = toastManager.add({
103 type: "info",
104 title: "The page copied text",
105 actionProps: {
106 children: "Copy",
107 onClick: () => {
108 toastManager.close(id);
109 void navigator.clipboard.writeText(text).catch(() => undefined);
110 },
111 },
112 });
113 }
114}
115
116function offerDownload(download: PreviewStreamDownload) {
117 const id = toastManager.add({
118 type: "info",
119 title: `Downloaded ${download.fileName}`,
120 actionProps: {
121 children: "Save",
122 onClick: () => {
123 toastManager.close(id);
124 const anchor = document.createElement("a");
125 anchor.href = download.url;
126 anchor.download = download.fileName;
127 anchor.click();
128 },
129 },
130 });
131}
132
133export function ServerBrowserSurface(props: {
134 readonly environmentId: EnvironmentId;
135 readonly threadId: string;
136 readonly tabId: string;
137 readonly visible: boolean;
138 readonly followSize?: boolean;
139 readonly controlPosition?: "top" | "bottom";
140 readonly onFirstFrame?: () => void;
141 readonly onViewport?: (viewport: PreviewStreamViewport) => void;
142 readonly onControl?: (control: PreviewStreamControl | null) => void;
143 readonly onPopup?: (tabId: string) => void;
144 readonly className?: string;
145 readonly pdfUrl?: string | null;
146 readonly ref?: Ref<ServerBrowserHandle>;
147}) {
148 const {
149 environmentId,
150 threadId,
151 tabId,
152 visible,
153 followSize = true,
154 controlPosition = "top",
155 onFirstFrame,
156 onViewport,
157 onControl,
158 onPopup,
159 className,
160 pdfUrl = null,
161 ref,
162 } = props;
163 const canvasRef = useRef<HTMLCanvasElement | null>(null);
164 const inputRef = useRef<HTMLTextAreaElement | null>(null);
165 const keySentRef = useRef(false);
166 const clientRef = useRef<PreviewStreamClient | null>(null);
167 const viewportRef = useRef<PreviewStreamViewport | null>(null);
168 const sizeRef = useRef<{ width: number; height: number } | null>(null);
169 const hasFrameRef = useRef(false);
170 const controlRef = useRef<PreviewStreamControl | null>(null);
171 const [control, setControl] = useState<PreviewStreamControl | null>(null);
172 const [promptText, setPromptText] = useState("");
173 const [fileChooser, setFileChooser] = useState<PreviewStreamFileChooser | null>(null);
174 const [agentCursor, setAgentCursor] = useState<AgentCursorPlacement | null>(null);
175 const fileInputRef = useRef<HTMLInputElement | null>(null);
176 const answerFileChooser = (files: ReadonlyArray<File>) => {
177 const chooser = fileChooser;
178 if (!chooser) return;
179 setFileChooser(null);
180 void uploadPreviewStreamFiles(chooser, files).catch((cause: unknown) =>
181 toastManager.add({
182 type: "error",
183 title: "Could not send the files to the page",
184 description: cause instanceof Error ? cause.message : undefined,
185 }),
186 );
187 };
188 const unauthorizedRef = useRef(0);
189 const [accessDenied, setAccessDenied] = useState(false);
190 const access = usePreviewStreamAccess(environmentId, { retry: visible && !accessDenied });
191 const [hostSetup, setHostSetup] = useState<PreviewStreamHostSetup | null>(null);
192 const pendingMoveRef = useRef<MouseInput | null>(null);
193 const pendingWheelRef = useRef<WheelInput | null>(null);
194 const inputFrameRef = useRef<number | null>(null);
195 const mouseButtonsRef = useRef(0);
196 const mouseClicksRef = useRef({ left: 1, middle: 1, right: 1, none: 1 });
197 const lastClickRef = useRef<{
198 button: PreviewStreamMouseButton;
199 time: number;
200 x: number;
201 y: number;
202 count: number;
203 } | null>(null);
204 const touchRef = useRef<TouchGesture | null>(null);
205 const probeRef = useRef<TouchProbe | null>(null);
206 const lastProbeRef = useRef<{ x: number; y: number; editable: boolean; at: number } | null>(null);
207 const firstFrame = useEffectEvent(() => onFirstFrame?.());
208 const viewportChanged = useEffectEvent((viewport: PreviewStreamViewport) =>
209 onViewport?.(viewport),
210 );
211 const controlChanged = useEffectEvent((next: PreviewStreamControl | null) => onControl?.(next));
212 const popupOpened = useEffectEvent((popupTabId: string) => onPopup?.(popupTabId));
213 const [cap, setCap] = useState<{ width: number; height: number } | null>(null);
214
215 // Keep clearInput stable: a new identity reconnects the stream.
216 const send = (input: PreviewStreamInput) => {
217 clientRef.current?.send(input);
218 };
219
220 const clearInput = () => {
221 if (inputFrameRef.current !== null) cancelAnimationFrame(inputFrameRef.current);
222 inputFrameRef.current = null;
223 pendingMoveRef.current = pendingWheelRef.current = null;
224 mouseButtonsRef.current = 0;
225 mouseClicksRef.current = { left: 1, middle: 1, right: 1, none: 1 };
226 lastClickRef.current = null;
227 touchRef.current = probeRef.current = lastProbeRef.current = null;
228 keySentRef.current = false;
229 if (inputRef.current) inputRef.current.value = INPUT_SENTINEL;
230 inputRef.current?.blur();
231 };
232
233 const flushInput = () => {
234 if (inputFrameRef.current !== null) cancelAnimationFrame(inputFrameRef.current);
235 inputFrameRef.current = null;
236 const move = pendingMoveRef.current;
237 const wheel = pendingWheelRef.current;
238 pendingMoveRef.current = null;
239 pendingWheelRef.current = null;
240 if (move) send(move);
241 if (wheel) send(wheel);
242 };
243
244 const scheduleFlush = () => {
245 if (inputFrameRef.current === null) inputFrameRef.current = requestAnimationFrame(flushInput);
246 };
247
248 const queueWheel = (point: PagePoint, deltaX: number, deltaY: number, modifiers: number) => {
249 const pending = pendingWheelRef.current;
250 pendingWheelRef.current = {
251 type: "wheel",
252 x: point.x,
253 y: point.y,
254 deltaX: (pending?.deltaX ?? 0) + deltaX,
255 deltaY: (pending?.deltaY ?? 0) + deltaY,
256 modifiers,
257 };
258 scheduleFlush();
259 };
260
261 const pagePoint = (clientX: number, clientY: number, clamp: boolean): PagePoint | null => {
262 const canvas = canvasRef.current;
263 const viewport = viewportRef.current;
264 if (!canvas || !viewport || !hasFrameRef.current || controlRef.current?.controller !== "you")
265 return null;
266 const rect = canvas.getBoundingClientRect();
267 const fit = Math.min(rect.width / canvas.width, rect.height / canvas.height);
268 const width = canvas.width * fit;
269 const height = canvas.height * fit;
270 if (!(width > 0 && height > 0)) return null;
271 const scale = viewport.width / width;
272 const x = (clientX - rect.left - (rect.width - width) / 2) * scale;
273 const y = (clientY - rect.top - (rect.height - height) / 2) * (viewport.height / height);
274 const inside = x >= 0 && y >= 0 && x <= viewport.width && y <= viewport.height;
275 if (!inside && !clamp) return null;
276 return {
277 x: Math.min(Math.max(x, 0), viewport.width),
278 y: Math.min(Math.max(y, 0), viewport.height),
279 scale,
280 };
281 };
282
283 const countClick = (button: PreviewStreamMouseButton, x: number, y: number, time: number) => {
284 const last = lastClickRef.current;
285 const count =
286 last &&
287 last.button === button &&
288 time - last.time < MULTI_CLICK_MS &&
289 Math.hypot(x - last.x, y - last.y) < MULTI_CLICK_SLOP_PX
290 ? last.count + 1
291 : 1;
292 lastClickRef.current = { button, time, x, y, count };
293 return count;
294 };
295
296 const focusInput = () => inputRef.current?.focus({ preventScroll: true });
297
298 useImperativeHandle(
299 ref,
300 () => ({
301 navigate: (url) => send({ type: "navigate", url }),
302 history: (delta) => send({ type: "history", delta }),
303 reload: (options) =>
304 send({ type: "reload", ...(options?.ignoreCache ? { ignoreCache: true } : {}) }),
305 viewport: (setting) => send({ type: "viewport", setting }),
306 canvas: () => (!pdfUrl && hasFrameRef.current ? canvasRef.current : null),
307 }),
308 [pdfUrl, send],
309 );
310
311 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes the canvas container's size, sends resizes to the stream and grows the frame cap
312 useEffect(() => {
313 const element = canvasRef.current?.parentElement;
314 if (!element) return;
315 let timer: ReturnType<typeof setTimeout> | null = null;
316 let capTimer: ReturnType<typeof setTimeout> | null = null;
317 const growCap = () => {
318 capTimer = null;
319 const size = sizeRef.current;
320 if (!size) return;
321 const ratio = window.devicePixelRatio || 1;
322 const width = Math.round(size.width * ratio);
323 const height = Math.round(size.height * ratio);
324 setCap((current) =>
325 current !== null && current.width >= width && current.height >= height
326 ? current
327 : {
328 width: Math.max(width, current?.width ?? 0),
329 height: Math.max(height, current?.height ?? 0),
330 },
331 );
332 };
333 const measure = () => {
334 timer = null;
335 const rect = element.getBoundingClientRect();
336 if (rect.width < 1 || rect.height < 1) return;
337 const size = { width: Math.round(rect.width), height: Math.round(rect.height) };
338 const previous = sizeRef.current;
339 if (previous?.width === size.width && previous.height === size.height) return;
340 sizeRef.current = size;
341 if (followSize) clientRef.current?.send({ type: "resize", ...size });
342 // Growing the cap reconnects the stream; wait until resizing settles.
343 if (capTimer !== null) clearTimeout(capTimer);
344 capTimer = setTimeout(growCap, previous === null ? 0 : RESIZE_THROTTLE_MS * 2);
345 };
346 const stopObserving = observeResize(element, () => {
347 if (timer !== null) return;
348 timer = setTimeout(measure, sizeRef.current === null ? 0 : RESIZE_THROTTLE_MS);
349 });
350 return () => {
351 stopObserving();
352 if (timer !== null) clearTimeout(timer);
353 if (capTimer !== null) clearTimeout(capTimer);
354 };
355 }, [followSize]);
356
357 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens the preview stream client and paints its frames onto the canvas while visible
358 useEffect(() => {
359 const canvas = canvasRef.current;
360 if (!visible || accessDenied || hostSetup || !access || !cap || !canvas) return;
361 let refreshTimer: ReturnType<typeof setTimeout> | null = null;
362 const painter = createPreviewFramePainter(canvas, () => {
363 if (hasFrameRef.current) return;
364 hasFrameRef.current = true;
365 firstFrame();
366 });
367 const client = createPreviewStreamClient(
368 { access, threadId, tabId, maxWidth: cap.width, maxHeight: cap.height },
369 {
370 onFrame: (jpeg) => {
371 unauthorizedRef.current = 0;
372 painter.paint(jpeg);
373 },
374 onProbe: (result) => {
375 if (controlRef.current?.controller !== "you") return;
376 lastProbeRef.current = { ...result, at: performance.now() };
377 const probe = probeRef.current;
378 if (!probe || probe.x !== result.x || probe.y !== result.y) return;
379 probe.editable = result.editable;
380 probe.answered = true;
381 if (!probe.tapped) return;
382 probeRef.current = null;
383 if (result.editable) inputRef.current?.focus({ preventScroll: true });
384 else inputRef.current?.blur();
385 },
386 onPointer: (pointer) => {
387 const placed = placeAgentCursor(pointer, canvasRef.current, viewportRef.current);
388 if (placed) setAgentCursor(placed);
389 },
390 onClipboard: (text) => void copyPageText(text),
391 onDownload: offerDownload,
392 onPopup: popupOpened,
393 onFileChooser: setFileChooser,
394 onViewport: (viewport) => {
395 viewportRef.current = viewport;
396 viewportChanged(viewport);
397 },
398 onControl: (next) => {
399 const previous = controlRef.current;
400 controlRef.current = next;
401 setControl(next);
402 controlChanged(next);
403 if (
404 next.dialog?.message !== previous?.dialog?.message ||
405 next.dialog?.defaultValue !== previous?.dialog?.defaultValue
406 )
407 setPromptText(next.dialog?.defaultValue ?? "");
408 if (next.controller !== "you") {
409 clearInput();
410 } else if (previous?.controller !== "you") {
411 const size = sizeRef.current;
412 if (followSize && size) client.send({ type: "resize", ...size });
413 }
414 },
415 onConnectedChange: (connected) => {
416 if (connected) return;
417 setFileChooser(null);
418 controlRef.current = null;
419 setControl(null);
420 controlChanged(null);
421 clearInput();
422 },
423 onHostSetup: setHostSetup,
424 onUnauthorized: () => {
425 const refusals = ++unauthorizedRef.current;
426 if (refusals >= MAX_UNAUTHORIZED_REFUSALS) {
427 inputRef.current?.blur();
428 setAccessDenied(true);
429 return;
430 }
431 refreshTimer = setTimeout(
432 () => refreshPreviewStreamAccess(environmentId),
433 refusals === 1 ? 0 : 1_000 * 2 ** (refusals - 1),
434 );
435 },
436 },
437 );
438 clientRef.current = client;
439 return () => {
440 painter.stop();
441 if (refreshTimer !== null) clearTimeout(refreshTimer);
442 client.stop();
443 if (clientRef.current === client) clientRef.current = null;
444 controlRef.current = null;
445 setControl(null);
446 controlChanged(null);
447 clearInput();
448 };
449 }, [
450 access,
451 accessDenied,
452 cap,
453 clearInput,
454 environmentId,
455 followSize,
456 hostSetup,
457 tabId,
458 threadId,
459 visible,
460 ]);
461
462 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers a non-passive wheel listener on the canvas so it can stop the panel scrolling
463 useEffect(() => {
464 const canvas = canvasRef.current;
465 if (!canvas) return;
466 // Registered natively: React's wheel listener is passive and cannot stop the panel scrolling.
467 const onWheel = (event: WheelEvent) => {
468 const point = pagePoint(event.clientX, event.clientY, false);
469 if (!point) return;
470 event.preventDefault();
471 const unit =
472 event.deltaMode === WheelEvent.DOM_DELTA_LINE
473 ? WHEEL_LINE_PX
474 : event.deltaMode === WheelEvent.DOM_DELTA_PAGE
475 ? (viewportRef.current?.height ?? 0)
476 : 1;
477 queueWheel(point, event.deltaX * unit, event.deltaY * unit, previewStreamModifiers(event));
478 };
479 canvas.addEventListener("wheel", onWheel, { passive: false });
480 return () => canvas.removeEventListener("wheel", onWheel);
481 }, [pagePoint, queueWheel]);
482
483 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the pending input animation frame when the component unmounts
484 useEffect(
485 () => () => {
486 if (inputFrameRef.current !== null) cancelAnimationFrame(inputFrameRef.current);
487 },
488 [],
489 );
490
491 const handlePointer = (event: PointerEvent<HTMLCanvasElement>) => {
492 if (controlRef.current?.controller !== "you") return;
493 const { type, pointerId, clientX, clientY } = event;
494 const cancelled = type === "pointercancel";
495 const touch = touchRef.current;
496 if (cancelled && touch?.pointerId === pointerId) {
497 touchRef.current = probeRef.current = null;
498 return;
499 }
500 if (event.pointerType === "touch" && !cancelled) {
501 const point = pagePoint(clientX, clientY, type === "pointermove");
502 if (type === "pointerdown") {
503 if (!event.isPrimary) return;
504 touchRef.current = {
505 pointerId,
506 startX: clientX,
507 startY: clientY,
508 lastX: clientX,
509 lastY: clientY,
510 panning: false,
511 };
512 const last = lastProbeRef.current;
513 const reusable =
514 point &&
515 last &&
516 performance.now() - last.at < PROBE_REUSE_MS &&
517 Math.hypot(point.x - last.x, point.y - last.y) < PROBE_REUSE_PX;
518 probeRef.current = point
519 ? {
520 x: point.x,
521 y: point.y,
522 editable: reusable ? last.editable : null,
523 answered: false,
524 tapped: false,
525 }
526 : null;
527 if (point) send({ type: "probe", x: point.x, y: point.y });
528 return;
529 }
530 if (!touch || touch.pointerId !== pointerId) return;
531 if (type === "pointermove") {
532 if (
533 !touch.panning &&
534 Math.hypot(clientX - touch.startX, clientY - touch.startY) < TAP_SLOP_PX
535 )
536 return;
537 touch.panning = true;
538 if (point)
539 queueWheel(
540 point,
541 (touch.lastX - clientX) * point.scale,
542 (touch.lastY - clientY) * point.scale,
543 0,
544 );
545 touch.lastX = clientX;
546 touch.lastY = clientY;
547 return;
548 }
549 touchRef.current = null;
550 const probe = probeRef.current;
551 if (touch.panning) {
552 probeRef.current = null;
553 return;
554 }
555 if (!point) return;
556 // iOS requires focus during the tap; late probe replies only raise Android's keyboard.
557 if (probe?.editable === true) focusInput();
558 else if (probe?.editable === false) inputRef.current?.blur();
559 if (probe && !probe.answered) probe.tapped = true;
560 else probeRef.current = null;
561 flushInput();
562 const clickCount = countClick("left", clientX, clientY, event.timeStamp);
563 const at = { x: point.x, y: point.y, modifiers: 0 };
564 send({ type: "mouse", action: "move", ...at, button: "none", buttons: 0, clickCount: 0 });
565 send({ type: "mouse", action: "down", ...at, button: "left", buttons: 1, clickCount });
566 send({ type: "mouse", action: "up", ...at, button: "left", buttons: 0, clickCount });
567 return;
568 }
569 const previous = mouseButtonsRef.current;
570 if ((cancelled || type === "pointerup") && previous === 0) return;
571 if (cancelled || type === "pointerup")
572 mouseButtonsRef.current = cancelled ? 0 : event.buttons & 7;
573 const point = pagePoint(
574 clientX,
575 clientY,
576 type !== "pointerdown" &&
577 (cancelled || type === "pointerup" || previous !== 0 || event.buttons !== 0),
578 );
579 if (!point) return;
580 const at = { x: point.x, y: point.y, modifiers: previewStreamModifiers(event) };
581 const mouse = (action: "down" | "up", button: PreviewStreamMouseButton, buttons: number) => {
582 if (action === "down")
583 mouseClicksRef.current[button] = countClick(button, clientX, clientY, event.timeStamp);
584 send({
585 type: "mouse",
586 action,
587 ...at,
588 button,
589 buttons,
590 clickCount: mouseClicksRef.current[button],
591 });
592 };
593 if (type === "pointerdown") {
594 focusInput();
595 event.currentTarget.setPointerCapture(pointerId);
596 flushInput();
597 mouseButtonsRef.current = event.buttons & 7;
598 mouse("down", buttonOf(event.button), event.buttons);
599 } else if (type === "pointerup") {
600 flushInput();
601 mouse("up", buttonOf(event.button), event.buttons);
602 } else {
603 // Chords arrive as pointermove. Cancellation releases every held button.
604 const next = cancelled ? 0 : event.buttons & 7;
605 const changed = previous ^ next;
606 if (previous !== 0 && changed !== 0) {
607 flushInput();
608 let buttons = previous;
609 for (const bit of [1, 2, 4]) {
610 if (!(changed & bit)) continue;
611 buttons ^= bit;
612 mouse(next & bit ? "down" : "up", pressedButtonOf(bit), buttons);
613 }
614 mouseButtonsRef.current = next;
615 }
616 if (cancelled) return;
617 pendingMoveRef.current = {
618 type: "mouse",
619 action: "move",
620 ...at,
621 button: pressedButtonOf(event.buttons),
622 buttons: event.buttons,
623 clickCount: 0,
624 };
625 scheduleFlush();
626 }
627 };
628
629 const resetInput = (textarea: HTMLTextAreaElement) => {
630 keySentRef.current = false;
631 textarea.value = INPUT_SENTINEL;
632 textarea.setSelectionRange(INPUT_SENTINEL.length, INPUT_SENTINEL.length);
633 };
634
635 const sendKeyPress = (key: typeof BACKSPACE | typeof DELETE) => {
636 send({ type: "key", action: "down", ...key, modifiers: 0 });
637 send({ type: "key", action: "up", ...key, modifiers: 0 });
638 };
639
640 const handleKey = (action: "down" | "up", event: KeyboardEvent<HTMLTextAreaElement>) => {
641 if (controlRef.current?.controller !== "you") return;
642 keySentRef.current = false;
643 if (
644 event.nativeEvent.isComposing ||
645 event.keyCode === 229 ||
646 event.key === "Process" ||
647 event.key === "Unidentified"
648 ) {
649 return;
650 }
651 if (event.key === "Escape" && event.shiftKey) {
652 event.preventDefault();
653 event.stopPropagation();
654 if (action === "down") event.currentTarget.blur();
655 return;
656 }
657 const shortcut = event.ctrlKey || event.metaKey;
658 if (shortcut && event.key.toLowerCase() === "v") return;
659 if (event.shiftKey && event.key === "Insert") return;
660 // Enter carries "\r" like Puppeteer's key table, so forms submit and textareas break lines.
661 const text = shortcut
662 ? undefined
663 : [...event.key].length === 1
664 ? event.key
665 : event.key === "Enter"
666 ? "\r"
667 : undefined;
668 send({
669 type: "key",
670 action,
671 key: event.key,
672 code: event.code,
673 keyCode: event.keyCode,
674 ...(action === "down" && text !== undefined ? { text } : {}),
675 modifiers: previewStreamModifiers(event),
676 });
677 // Some Android keyboards edit the textarea even when keydown is prevented.
678 keySentRef.current =
679 action === "down" &&
680 !shortcut &&
681 (text !== undefined || event.key === "Backspace" || event.key === "Delete");
682 if (shortcut) return;
683 event.preventDefault();
684 event.stopPropagation();
685 };
686
687 const handleInput = (event: FormEvent<HTMLTextAreaElement>) => {
688 const native = event.nativeEvent;
689 if (native instanceof InputEvent && native.isComposing) return;
690 const textarea = event.currentTarget;
691 const inputType = native instanceof InputEvent ? native.inputType : "";
692 if (keySentRef.current) keySentRef.current = false;
693 else if (inputType === "deleteContentBackward") sendKeyPress(BACKSPACE);
694 else if (inputType === "deleteContentForward") sendKeyPress(DELETE);
695 else {
696 const text = textarea.value.replace(/^\u200b/, "");
697 if (text) send({ type: "text", text });
698 }
699 resetInput(textarea);
700 };
701
702 return (
703 <div
704 className={cn("relative flex flex-col overflow-hidden", className)}
705 data-server-browser-surface={tabId}
706 >
707 <div
708 className={cn(
709 "visible relative z-20 flex shrink-0 items-center justify-between gap-2 border-border bg-background px-2 py-1",
710 controlPosition === "bottom" ? "order-last border-t" : "border-b",
711 )}
712 >
713 <span role="status" className="text-xs text-muted-foreground">
714 {previewStreamControlLabel(control)}
715 </span>
716 {control?.canOperate ? (
717 <Button
718 variant="outline"
719 size="xs"
720 disabled={control.controller === "another-viewer"}
721 onClick={() =>
722 send({ type: control.controller === "you" ? "releaseControl" : "takeControl" })
723 }
724 >
725 {control.controller === "you" ? "Release control" : "Take control"}
726 </Button>
727 ) : null}
728 </div>
729 <div className="relative min-h-0 flex-1">
730 {pdfUrl ? (
731 <embed
732 src={pdfUrl}
733 type="application/pdf"
734 title="PDF document"
735 className="absolute inset-0 z-10 size-full border-0"
736 />
737 ) : null}
738 <canvas
739 ref={canvasRef}
740 className="block size-full touch-none object-contain"
741 onPointerDown={handlePointer}
742 onPointerMove={handlePointer}
743 onPointerUp={handlePointer}
744 onPointerCancel={handlePointer}
745 onMouseDown={(event) => event.preventDefault()}
746 onContextMenu={(event) => event.preventDefault()}
747 />
748 {!pdfUrl && agentCursor && control?.controller !== "you" ? (
749 <AgentCursorMark
750 {...agentCursor}
751 controller={control?.controller === "agent" ? "agent" : "none"}
752 />
753 ) : null}
754 {/* Pin top-left to avoid focus scrolling; 16px prevents iOS focus zoom. */}
755 <textarea
756 ref={inputRef}
757 aria-label="Browser page"
758 aria-description="Press Shift+Escape to leave the browser page."
759 autoCapitalize="off"
760 autoComplete="off"
761 autoCorrect="off"
762 spellCheck={false}
763 disabled={pdfUrl !== null || control?.controller !== "you"}
764 defaultValue={INPUT_SENTINEL}
765 onFocus={(event) => resetInput(event.currentTarget)}
766 className="sr-only top-0 left-0 text-base"
767 onKeyDown={(event) => handleKey("down", event)}
768 onKeyUp={(event) => handleKey("up", event)}
769 onInput={handleInput}
770 onCompositionEnd={(event) => {
771 const text = event.data.replace(/^\u200b/, "");
772 if (text) send({ type: "text", text });
773 resetInput(event.currentTarget);
774 }}
775 // Keep the sentinel off the clipboard.
776 onCopy={(event) => event.preventDefault()}
777 onCut={(event) => event.preventDefault()}
778 onPaste={(event) => {
779 event.preventDefault();
780 const text = event.clipboardData.getData("text/plain");
781 if (text) send({ type: "text", text });
782 }}
783 />
784 {fileChooser && control?.controller === "you" ? (
785 <div
786 className="absolute inset-x-2 top-2 z-10 flex flex-col gap-2 rounded-lg border border-border bg-background p-3 shadow-lg"
787 role="dialog"
788 aria-label="Choose files for the page"
789 >
790 <p className="text-sm">
791 The page asks for {fileChooser.multiple ? "files" : "a file"}.
792 </p>
793 <input
794 ref={fileInputRef}
795 type="file"
796 className="hidden"
797 multiple={fileChooser.multiple}
798 accept={fileChooser.accept}
799 onChange={(event) => {
800 const files = [...(event.currentTarget.files ?? [])];
801 event.currentTarget.value = "";
802 if (files.length > 0) answerFileChooser(files);
803 }}
804 />
805 <div className="flex justify-end gap-2">
806 <Button variant="outline" size="sm" onClick={() => answerFileChooser([])}>
807 Cancel
808 </Button>
809 <Button size="sm" onClick={() => fileInputRef.current?.click()}>
810 Choose {fileChooser.multiple ? "files" : "file"}
811 </Button>
812 </div>
813 </div>
814 ) : null}
815 {control?.dialog ? (
816 <div
817 className="absolute inset-x-2 top-2 z-10 flex flex-col gap-2 rounded-lg border border-border bg-background p-3 shadow-lg"
818 role="dialog"
819 aria-label="Browser dialog"
820 >
821 <p className="break-words text-sm">{control.dialog.message}</p>
822 {control.controller === "you" ? (
823 <>
824 {control.dialog.type === "prompt" ? (
825 <Input
826 aria-label="Dialog response"
827 value={promptText}
828 onChange={(event) => setPromptText(event.target.value)}
829 />
830 ) : null}
831 <div className="flex justify-end gap-2">
832 <Button
833 variant="outline"
834 size="sm"
835 onClick={() => send({ type: "dialog", accept: false })}
836 >
837 Dismiss
838 </Button>
839 <Button
840 size="sm"
841 onClick={() =>
842 send({
843 type: "dialog",
844 accept: true,
845 ...(control.dialog?.type === "prompt" ? { promptText } : {}),
846 })
847 }
848 >
849 Accept
850 </Button>
851 </div>
852 </>
853 ) : (
854 <p className="text-xs text-muted-foreground">Take control to respond.</p>
855 )}
856 </div>
857 ) : null}
858 </div>
859 {visible && hostSetup ? (
860 <div className="visible absolute inset-0 z-20 flex flex-col items-center justify-center gap-3 bg-background p-4 text-center">
861 <p role="alert" className="max-w-sm text-sm text-muted-foreground">
862 {previewStreamHostSetupMessage(hostSetup)}
863 </p>
864 <CommandBlock command={hostSetup.command} className="w-full max-w-md text-left" />
865 <Button variant="outline" size="sm" onClick={() => setHostSetup(null)}>
866 Try again
867 </Button>
868 </div>
869 ) : null}
870 {visible && accessDenied ? (
871 // The page can be invisible beneath an empty or unreachable state; reconnect must remain reachable.
872 <div className="visible absolute inset-0 z-20 flex flex-col items-center justify-center gap-2 bg-background p-3 text-center">
873 <p role="alert" className="text-xs text-muted-foreground">
874 Browser connection was refused.
875 </p>
876 <Button
877 variant="outline"
878 size="sm"
879 onClick={() => {
880 unauthorizedRef.current = 0;
881 setAccessDenied(false);
882 refreshPreviewStreamAccess(environmentId);
883 }}
884 >
885 Reconnect
886 </Button>
887 </div>
888 ) : null}
889 </div>
890 );
891}
892
893interface AgentCursorPlacement {
894 readonly phase: PreviewStreamPointer["phase"];
895 readonly sequence: number;
896 readonly left: number;
897 readonly top: number;
898}
899
900function placeAgentCursor(
901 pointer: PreviewStreamPointer,
902 canvas: HTMLCanvasElement | null,
903 viewport: PreviewStreamViewport | null,
904): AgentCursorPlacement | null {
905 if (!canvas || !viewport || canvas.width < 1 || canvas.height < 1) return null;
906 const box = { width: canvas.clientWidth, height: canvas.clientHeight };
907 const fit = Math.min(box.width / canvas.width, box.height / canvas.height);
908 const width = canvas.width * fit;
909 const height = canvas.height * fit;
910 return {
911 phase: pointer.phase,
912 sequence: pointer.sequence,
913 left: (box.width - width) / 2 + (pointer.x * width) / viewport.width,
914 top: (box.height - height) / 2 + (pointer.y * height) / viewport.height,
915 };
916}