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

ServerBrowserSurface.tsx

922 lines32.8 KB

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