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