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