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