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

ServerBrowserSurface.tsx

912 lines32.3 KB

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;
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;
73​
74interface TouchGesture {
75 readonly pointerId: number;
76 readonly startX: number;
77 readonly startY: number;
78 lastX: number;
79 lastY: number;
80 panning: boolean;
82​
83interface TouchProbe {
84 readonly x: number;
85 readonly y: number;
86 editable: boolean | null;
87 answered: boolean;
88 tapped: boolean;
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 }
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 });
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 useEffect(() => {
312 const element = canvasRef.current?.parentElement;
313 if (!element) return;
314 let timer: ReturnType<typeof setTimeout> | null = null;
315 let capTimer: ReturnType<typeof setTimeout> | null = null;
316 const growCap = () => {
317 capTimer = null;
318 const size = sizeRef.current;
319 if (!size) return;
320 const ratio = window.devicePixelRatio || 1;
321 const width = Math.round(size.width * ratio);
322 const height = Math.round(size.height * ratio);
323 setCap((current) =>
324 current !== null && current.width >= width && current.height >= height
325 ? current
326 : {
327 width: Math.max(width, current?.width ?? 0),
328 height: Math.max(height, current?.height ?? 0),
329 },
330 );
331 };
332 const measure = () => {
333 timer = null;
334 const rect = element.getBoundingClientRect();
335 if (rect.width < 1 || rect.height < 1) return;
336 const size = { width: Math.round(rect.width), height: Math.round(rect.height) };
337 const previous = sizeRef.current;
338 if (previous?.width === size.width && previous.height === size.height) return;
339 sizeRef.current = size;
340 if (followSize) clientRef.current?.send({ type: "resize", ...size });
341 // Growing the cap reconnects the stream; wait until resizing settles.
342 if (capTimer !== null) clearTimeout(capTimer);
343 capTimer = setTimeout(growCap, previous === null ? 0 : RESIZE_THROTTLE_MS * 2);
344 };
345 const stopObserving = observeResize(element, () => {
346 if (timer !== null) return;
347 timer = setTimeout(measure, sizeRef.current === null ? 0 : RESIZE_THROTTLE_MS);
348 });
349 return () => {
350 stopObserving();
351 if (timer !== null) clearTimeout(timer);
352 if (capTimer !== null) clearTimeout(capTimer);
353 };
354 }, [followSize]);
355​
356 useEffect(() => {
357 const canvas = canvasRef.current;
358 if (!visible || accessDenied || hostSetup || !access || !cap || !canvas) return;
359 let refreshTimer: ReturnType<typeof setTimeout> | null = null;
360 const painter = createPreviewFramePainter(canvas, () => {
361 if (hasFrameRef.current) return;
362 hasFrameRef.current = true;
363 firstFrame();
364 });
365 const client = createPreviewStreamClient(
366 { access, threadId, tabId, maxWidth: cap.width, maxHeight: cap.height },
367 {
368 onFrame: (jpeg) => {
369 unauthorizedRef.current = 0;
370 painter.paint(jpeg);
371 },
372 onProbe: (result) => {
373 if (controlRef.current?.controller !== "you") return;
374 lastProbeRef.current = { ...result, at: performance.now() };
375 const probe = probeRef.current;
376 if (!probe || probe.x !== result.x || probe.y !== result.y) return;
377 probe.editable = result.editable;
378 probe.answered = true;
379 if (!probe.tapped) return;
380 probeRef.current = null;
381 if (result.editable) inputRef.current?.focus({ preventScroll: true });
382 else inputRef.current?.blur();
383 },
384 onPointer: (pointer) => {
385 const placed = placeAgentCursor(pointer, canvasRef.current, viewportRef.current);
386 if (placed) setAgentCursor(placed);
387 },
388 onClipboard: (text) => void copyPageText(text),
389 onDownload: offerDownload,
390 onPopup: popupOpened,
391 onFileChooser: setFileChooser,
392 onViewport: (viewport) => {
393 viewportRef.current = viewport;
394 viewportChanged(viewport);
395 },
396 onControl: (next) => {
397 const previous = controlRef.current;
398 controlRef.current = next;
399 setControl(next);
400 controlChanged(next);
401 if (
402 next.dialog?.message !== previous?.dialog?.message ||
403 next.dialog?.defaultValue !== previous?.dialog?.defaultValue
404 )
405 setPromptText(next.dialog?.defaultValue ?? "");
406 if (next.controller !== "you") {
407 clearInput();
408 } else if (previous?.controller !== "you") {
409 const size = sizeRef.current;
410 if (followSize && size) client.send({ type: "resize", ...size });
411 }
412 },
413 onConnectedChange: (connected) => {
414 if (connected) return;
415 setFileChooser(null);
416 controlRef.current = null;
417 setControl(null);
418 controlChanged(null);
419 clearInput();
420 },
421 onHostSetup: setHostSetup,
422 onUnauthorized: () => {
423 const refusals = ++unauthorizedRef.current;
424 if (refusals >= MAX_UNAUTHORIZED_REFUSALS) {
425 inputRef.current?.blur();
426 setAccessDenied(true);
427 return;
428 }
429 refreshTimer = setTimeout(
430 () => refreshPreviewStreamAccess(environmentId),
431 refusals === 1 ? 0 : 1_000 * 2 ** (refusals - 1),
432 );
433 },
434 },
435 );
436 clientRef.current = client;
437 return () => {
438 painter.stop();
439 if (refreshTimer !== null) clearTimeout(refreshTimer);
440 client.stop();
441 if (clientRef.current === client) clientRef.current = null;
442 controlRef.current = null;
443 setControl(null);
444 controlChanged(null);
445 clearInput();
446 };
447 }, [
448 access,
449 accessDenied,
450 cap,
451 clearInput,
452 environmentId,
453 followSize,
454 hostSetup,
455 tabId,
456 threadId,
457 visible,
458 ]);
459​
460 useEffect(() => {
461 const canvas = canvasRef.current;
462 if (!canvas) return;
463 // Registered natively: React's wheel listener is passive and cannot stop the panel scrolling.
464 const onWheel = (event: WheelEvent) => {
465 const point = pagePoint(event.clientX, event.clientY, false);
466 if (!point) return;
467 event.preventDefault();
468 const unit =
469 event.deltaMode === WheelEvent.DOM_DELTA_LINE
470 ? WHEEL_LINE_PX
471 : event.deltaMode === WheelEvent.DOM_DELTA_PAGE
472 ? (viewportRef.current?.height ?? 0)
473 : 1;
474 queueWheel(point, event.deltaX * unit, event.deltaY * unit, previewStreamModifiers(event));
475 };
476 canvas.addEventListener("wheel", onWheel, { passive: false });
477 return () => canvas.removeEventListener("wheel", onWheel);
478 }, [pagePoint, queueWheel]);
479​
480 useEffect(
481 () => () => {
482 if (inputFrameRef.current !== null) cancelAnimationFrame(inputFrameRef.current);
483 },
484 [],
485 );
486​
487 const handlePointer = (event: PointerEvent<HTMLCanvasElement>) => {
488 if (controlRef.current?.controller !== "you") return;
489 const { type, pointerId, clientX, clientY } = event;
490 const cancelled = type === "pointercancel";
491 const touch = touchRef.current;
492 if (cancelled && touch?.pointerId === pointerId) {
493 touchRef.current = probeRef.current = null;
494 return;
495 }
496 if (event.pointerType === "touch" && !cancelled) {
497 const point = pagePoint(clientX, clientY, type === "pointermove");
498 if (type === "pointerdown") {
499 if (!event.isPrimary) return;
500 touchRef.current = {
501 pointerId,
502 startX: clientX,
503 startY: clientY,
504 lastX: clientX,
505 lastY: clientY,
506 panning: false,
507 };
508 const last = lastProbeRef.current;
509 const reusable =
510 point &&
511 last &&
512 performance.now() - last.at < PROBE_REUSE_MS &&
513 Math.hypot(point.x - last.x, point.y - last.y) < PROBE_REUSE_PX;
514 probeRef.current = point
515 ? {
516 x: point.x,
517 y: point.y,
518 editable: reusable ? last.editable : null,
519 answered: false,
520 tapped: false,
521 }
522 : null;
523 if (point) send({ type: "probe", x: point.x, y: point.y });
524 return;
525 }
526 if (!touch || touch.pointerId !== pointerId) return;
527 if (type === "pointermove") {
528 if (
529 !touch.panning &&
530 Math.hypot(clientX - touch.startX, clientY - touch.startY) < TAP_SLOP_PX
531 )
532 return;
533 touch.panning = true;
534 if (point)
535 queueWheel(
536 point,
537 (touch.lastX - clientX) * point.scale,
538 (touch.lastY - clientY) * point.scale,
539 0,
540 );
541 touch.lastX = clientX;
542 touch.lastY = clientY;
543 return;
544 }
545 touchRef.current = null;
546 const probe = probeRef.current;
547 if (touch.panning) {
548 probeRef.current = null;
549 return;
550 }
551 if (!point) return;
552 // iOS requires focus during the tap; late probe replies only raise Android's keyboard.
553 if (probe?.editable === true) focusInput();
554 else if (probe?.editable === false) inputRef.current?.blur();
555 if (probe && !probe.answered) probe.tapped = true;
556 else probeRef.current = null;
557 flushInput();
558 const clickCount = countClick("left", clientX, clientY, event.timeStamp);
559 const at = { x: point.x, y: point.y, modifiers: 0 };
560 send({ type: "mouse", action: "move", ...at, button: "none", buttons: 0, clickCount: 0 });
561 send({ type: "mouse", action: "down", ...at, button: "left", buttons: 1, clickCount });
562 send({ type: "mouse", action: "up", ...at, button: "left", buttons: 0, clickCount });
563 return;
564 }
565 const previous = mouseButtonsRef.current;
566 if ((cancelled || type === "pointerup") && previous === 0) return;
567 if (cancelled || type === "pointerup")
568 mouseButtonsRef.current = cancelled ? 0 : event.buttons & 7;
569 const point = pagePoint(
570 clientX,
571 clientY,
572 type !== "pointerdown" &&
573 (cancelled || type === "pointerup" || previous !== 0 || event.buttons !== 0),
574 );
575 if (!point) return;
576 const at = { x: point.x, y: point.y, modifiers: previewStreamModifiers(event) };
577 const mouse = (action: "down" | "up", button: PreviewStreamMouseButton, buttons: number) => {
578 if (action === "down")
579 mouseClicksRef.current[button] = countClick(button, clientX, clientY, event.timeStamp);
580 send({
581 type: "mouse",
582 action,
583 ...at,
584 button,
585 buttons,
586 clickCount: mouseClicksRef.current[button],
587 });
588 };
589 if (type === "pointerdown") {
590 focusInput();
591 event.currentTarget.setPointerCapture(pointerId);
592 flushInput();
593 mouseButtonsRef.current = event.buttons & 7;
594 mouse("down", buttonOf(event.button), event.buttons);
595 } else if (type === "pointerup") {
596 flushInput();
597 mouse("up", buttonOf(event.button), event.buttons);
598 } else {
599 // Chords arrive as pointermove. Cancellation releases every held button.
600 const next = cancelled ? 0 : event.buttons & 7;
601 const changed = previous ^ next;
602 if (previous !== 0 && changed !== 0) {
603 flushInput();
604 let buttons = previous;
605 for (const bit of [1, 2, 4]) {
606 if (!(changed & bit)) continue;
607 buttons ^= bit;
608 mouse(next & bit ? "down" : "up", pressedButtonOf(bit), buttons);
609 }
610 mouseButtonsRef.current = next;
611 }
612 if (cancelled) return;
613 pendingMoveRef.current = {
614 type: "mouse",
615 action: "move",
616 ...at,
617 button: pressedButtonOf(event.buttons),
618 buttons: event.buttons,
619 clickCount: 0,
620 };
621 scheduleFlush();
622 }
623 };
624​
625 const resetInput = (textarea: HTMLTextAreaElement) => {
626 keySentRef.current = false;
627 textarea.value = INPUT_SENTINEL;
628 textarea.setSelectionRange(INPUT_SENTINEL.length, INPUT_SENTINEL.length);
629 };
630​
631 const sendKeyPress = (key: typeof BACKSPACE | typeof DELETE) => {
632 send({ type: "key", action: "down", ...key, modifiers: 0 });
633 send({ type: "key", action: "up", ...key, modifiers: 0 });
634 };
635​
636 const handleKey = (action: "down" | "up", event: KeyboardEvent<HTMLTextAreaElement>) => {
637 if (controlRef.current?.controller !== "you") return;
638 keySentRef.current = false;
639 if (
640 event.nativeEvent.isComposing ||
641 event.keyCode === 229 ||
642 event.key === "Process" ||
643 event.key === "Unidentified"
644 ) {
645 return;
646 }
647 if (event.key === "Escape" && event.shiftKey) {
648 event.preventDefault();
649 event.stopPropagation();
650 if (action === "down") event.currentTarget.blur();
651 return;
652 }
653 const shortcut = event.ctrlKey || event.metaKey;
654 if (shortcut && event.key.toLowerCase() === "v") return;
655 if (event.shiftKey && event.key === "Insert") return;
656 // Enter carries "\r" like Puppeteer's key table, so forms submit and textareas break lines.
657 const text = shortcut
658 ? undefined
659 : [...event.key].length === 1
660 ? event.key
661 : event.key === "Enter"
662 ? "\r"
663 : undefined;
664 send({
665 type: "key",
666 action,
667 key: event.key,
668 code: event.code,
669 keyCode: event.keyCode,
670 ...(action === "down" && text !== undefined ? { text } : {}),
671 modifiers: previewStreamModifiers(event),
672 });
673 // Some Android keyboards edit the textarea even when keydown is prevented.
674 keySentRef.current =
675 action === "down" &&
676 !shortcut &&
677 (text !== undefined || event.key === "Backspace" || event.key === "Delete");
678 if (shortcut) return;
679 event.preventDefault();
680 event.stopPropagation();
681 };
682​
683 const handleInput = (event: FormEvent<HTMLTextAreaElement>) => {
684 const native = event.nativeEvent;
685 if (native instanceof InputEvent && native.isComposing) return;
686 const textarea = event.currentTarget;
687 const inputType = native instanceof InputEvent ? native.inputType : "";
688 if (keySentRef.current) keySentRef.current = false;
689 else if (inputType === "deleteContentBackward") sendKeyPress(BACKSPACE);
690 else if (inputType === "deleteContentForward") sendKeyPress(DELETE);
691 else {
692 const text = textarea.value.replace(/^\u200b/, "");
693 if (text) send({ type: "text", text });
694 }
695 resetInput(textarea);
696 };
697​
698 return (
699 <div
700 className={cn("relative flex flex-col overflow-hidden", className)}
701 data-server-browser-surface={tabId}
702 >
703 <div
704 className={cn(
705 "visible relative z-20 flex shrink-0 items-center justify-between gap-2 border-border bg-background px-2 py-1",
706 controlPosition === "bottom" ? "order-last border-t" : "border-b",
707 )}
708 >
709 <span role="status" className="text-xs text-muted-foreground">
710 {previewStreamControlLabel(control)}
711 </span>
712 {control?.canOperate ? (
713 <Button
714 variant="outline"
715 size="xs"
716 disabled={control.controller === "another-viewer"}
717 onClick={() =>
718 send({ type: control.controller === "you" ? "releaseControl" : "takeControl" })
719 }
720 >
721 {control.controller === "you" ? "Release control" : "Take control"}
722 </Button>
723 ) : null}
724 </div>
725 <div className="relative min-h-0 flex-1">
726 {pdfUrl ? (
727 <embed
728 src={pdfUrl}
729 type="application/pdf"
730 title="PDF document"
731 className="absolute inset-0 z-10 size-full border-0"
732 />
733 ) : null}
734 <canvas
735 ref={canvasRef}
736 className="block size-full touch-none object-contain"
737 onPointerDown={handlePointer}
738 onPointerMove={handlePointer}
739 onPointerUp={handlePointer}
740 onPointerCancel={handlePointer}
741 onMouseDown={(event) => event.preventDefault()}
742 onContextMenu={(event) => event.preventDefault()}
743 />
744 {!pdfUrl && agentCursor && control?.controller !== "you" ? (
745 <AgentCursorMark
746 {...agentCursor}
747 controller={control?.controller === "agent" ? "agent" : "none"}
748 />
749 ) : null}
750 {/* Pin top-left to avoid focus scrolling; 16px prevents iOS focus zoom. */}
751 <textarea
752 ref={inputRef}
753 aria-label="Browser page"
754 aria-description="Press Shift+Escape to leave the browser page."
755 autoCapitalize="off"
756 autoComplete="off"
757 autoCorrect="off"
758 spellCheck={false}
759 disabled={pdfUrl !== null || control?.controller !== "you"}
760 defaultValue={INPUT_SENTINEL}
761 onFocus={(event) => resetInput(event.currentTarget)}
762 className="sr-only top-0 left-0 text-base"
763 onKeyDown={(event) => handleKey("down", event)}
764 onKeyUp={(event) => handleKey("up", event)}
765 onInput={handleInput}
766 onCompositionEnd={(event) => {
767 const text = event.data.replace(/^\u200b/, "");
768 if (text) send({ type: "text", text });
769 resetInput(event.currentTarget);
770 }}
771 // Keep the sentinel off the clipboard.
772 onCopy={(event) => event.preventDefault()}
773 onCut={(event) => event.preventDefault()}
774 onPaste={(event) => {
775 event.preventDefault();
776 const text = event.clipboardData.getData("text/plain");
777 if (text) send({ type: "text", text });
778 }}
779 />
780 {fileChooser && control?.controller === "you" ? (
781 <div
782 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"
783 role="dialog"
784 aria-label="Choose files for the page"
785 >
786 <p className="text-sm">
787 The page asks for {fileChooser.multiple ? "files" : "a file"}.
788 </p>
789 <input
790 ref={fileInputRef}
791 type="file"
792 className="hidden"
793 multiple={fileChooser.multiple}
794 accept={fileChooser.accept}
795 onChange={(event) => {
796 const files = [...(event.currentTarget.files ?? [])];
797 event.currentTarget.value = "";
798 if (files.length > 0) answerFileChooser(files);
799 }}
800 />
801 <div className="flex justify-end gap-2">
802 <Button variant="outline" size="sm" onClick={() => answerFileChooser([])}>
803 Cancel
804 </Button>
805 <Button size="sm" onClick={() => fileInputRef.current?.click()}>
806 Choose {fileChooser.multiple ? "files" : "file"}
807 </Button>
808 </div>
809 </div>
810 ) : null}
811 {control?.dialog ? (
812 <div
813 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"
814 role="dialog"
815 aria-label="Browser dialog"
816 >
817 <p className="break-words text-sm">{control.dialog.message}</p>
818 {control.controller === "you" ? (
819 <>
820 {control.dialog.type === "prompt" ? (
821 <Input
822 aria-label="Dialog response"
823 value={promptText}
824 onChange={(event) => setPromptText(event.target.value)}
825 />
826 ) : null}
827 <div className="flex justify-end gap-2">
828 <Button
829 variant="outline"
830 size="sm"
831 onClick={() => send({ type: "dialog", accept: false })}
832 >
833 Dismiss
834 </Button>
835 <Button
836 size="sm"
837 onClick={() =>
838 send({
839 type: "dialog",
840 accept: true,
841 ...(control.dialog?.type === "prompt" ? { promptText } : {}),
842 })
843 }
844 >
845 Accept
846 </Button>
847 </div>
848 </>
849 ) : (
850 <p className="text-xs text-muted-foreground">Take control to respond.</p>
851 )}
852 </div>
853 ) : null}
854 </div>
855 {visible && hostSetup ? (
856 <div className="visible absolute inset-0 z-20 flex flex-col items-center justify-center gap-3 bg-background p-4 text-center">
857 <p role="alert" className="max-w-sm text-sm text-muted-foreground">
858 {previewStreamHostSetupMessage(hostSetup)}
859 </p>
860 <CommandBlock command={hostSetup.command} className="w-full max-w-md text-left" />
861 <Button variant="outline" size="sm" onClick={() => setHostSetup(null)}>
862 Try again
863 </Button>
864 </div>
865 ) : null}
866 {visible && accessDenied ? (
867 // The page can be invisible beneath an empty or unreachable state; reconnect must remain reachable.
868 <div className="visible absolute inset-0 z-20 flex flex-col items-center justify-center gap-2 bg-background p-3 text-center">
869 <p role="alert" className="text-xs text-muted-foreground">
870 Browser connection was refused.
871 </p>
872 <Button
873 variant="outline"
874 size="sm"
875 onClick={() => {
876 unauthorizedRef.current = 0;
877 setAccessDenied(false);
878 refreshPreviewStreamAccess(environmentId);
879 }}
880 >
881 Reconnect
882 </Button>
883 </div>
884 ) : null}
885 </div>
886 );
888​
889interface AgentCursorPlacement {
890 readonly phase: PreviewStreamPointer["phase"];
891 readonly sequence: number;
892 readonly left: number;
893 readonly top: number;
895​
896function placeAgentCursor(
897 pointer: PreviewStreamPointer,
898 canvas: HTMLCanvasElement | null,
899 viewport: PreviewStreamViewport | null,
900): AgentCursorPlacement | null {
901 if (!canvas || !viewport || canvas.width < 1 || canvas.height < 1) return null;
902 const box = { width: canvas.clientWidth, height: canvas.clientHeight };
903 const fit = Math.min(box.width / canvas.width, box.height / canvas.height);
904 const width = canvas.width * fit;
905 const height = canvas.height * fit;
906 return {
907 phase: pointer.phase,
908 sequence: pointer.sequence,
909 left: (box.width - width) / 2 + (pointer.x * width) / viewport.width,
910 top: (box.height - height) / 2 + (pointer.y * height) / viewport.height,
911 };