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