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