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

ServerBrowserSurface.tsx

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