Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Browser takeover v2 frontend: 1:1 stage, full mouse and keyboard, own select and dialog UI (#274)
Oleksandr Ivanchenkof7fbd1d877ae
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex dd6e66fb..c83c3a2f 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -25,6 +25,7 @@ import {captchaStepFor,humanStepsApi,latestOpenStep,+ openStepFor,openStepsByKwant,turnsAwaitingStep,} from './humanSteps';@@ -3124,6 +3125,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({onNavigateVm={handleNavigateVm}vmApprovalsOff={space.approvals === 'off' || kwants.some(approvalsOff)}vmCaptchaStep={captchaStepFor(humanSteps, activeSandboxId)}+ vmHumanStep={openStepFor(humanSteps, activeSandboxId)}+ onVmStepDone={(id) => answerHumanStep(id, 'done')}vmSolveRequest={solveRequest}pinned={pinned}onEditInstructions={diff --git a/frontend/src/browserInput.ts b/frontend/src/browserInput.tsnew file mode 100644index 00000000..b5503b3e--- /dev/null+++ b/frontend/src/browserInput.ts@@ -0,0 +1,465 @@+// Desktop takeover of a bot's browser: turns the person's mouse, wheel and keyboard into the+// stream's protocol v2 messages. Pure functions and small state machines, so all of it is tested+// without a DOM. Coordinates sent to the server are CSS px of the page's viewport.++export interface Size {+ width: number;+ height: number;+}++export interface Rect {+ left: number;+ top: number;+ width: number;+ height: number;+}++/** CDP modifier bits. */+export const MOD = { alt: 1, ctrl: 2, meta: 4, shift: 8 } as const;++/** The remote is Linux or headless Chrome, so a Mac's Cmd shortcuts are sent as Ctrl. */+export function isMacPlatform(nav: { platform?: string; userAgent?: string } | undefined = typeof navigator === 'undefined' ? undefined : navigator): boolean {+ const s = `${nav?.platform ?? ''} ${nav?.userAgent ?? ''}`;+ return /Mac|iPhone|iPad|iPod/i.test(s);+}++// ---------------------------------------------------------------------------------------------+// Viewport size and drawing++export const VIEWPORT_LIMITS = { minWidth: 360, maxWidth: 1920, minHeight: 360, maxHeight: 1200, minDpr: 1, maxDpr: 2 };++const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));++/** The `resize` the stage asks for: its own size in CSS px, inside the server's limits. */+export function resizeFor(stage: Size, devicePixelRatio = 1): { action: 'resize'; width: number; height: number; dpr: number } | null {+ if (!(stage.width > 0) || !(stage.height > 0)) return null;+ const L = VIEWPORT_LIMITS;+ const dpr = Math.round(clamp(Math.min(devicePixelRatio || 1, 2), L.minDpr, L.maxDpr) * 100) / 100;+ return {+ action: 'resize',+ width: clamp(Math.floor(stage.width), L.minWidth, L.maxWidth),+ height: clamp(Math.floor(stage.height), L.minHeight, L.maxHeight),+ dpr,+ };+}++/**+ * What the person sees for a live view error, or null for none. Running off either end of the+ * history is expected (the buttons don't know the history), so it's silent; the rest lose the+ * server's "Protocol error: " prefix.+ */+export function streamErrorText(action: string | undefined, raw: unknown): string | null {+ const text = String(raw ?? '').replace(/^\s*protocol error:\s*/i, '').trim();+ if (action === 'history' && /no page to go/i.test(text)) return null;+ return text || 'Something went wrong in the browser.';+}++/**+ * Whether the page has drifted from the size the stage asked for (a cross-site navigation can+ * drop the override), so the resize should be sent again.+ */+export function sizeDrifted(requested: { width: number; height: number } | null, page: Size): boolean {+ if (!requested || !(page.width > 0) || !(page.height > 0)) return false;+ return Math.abs(page.width - requested.width) > 1 || Math.abs(page.height - requested.height) > 1;+}++/**+ * Where the page image sits in the stage: 1:1 when it fits, scaled down to fit when it doesn't+ * (a resize still on its way, or a stage smaller than the smallest viewport), centred either way.+ */+export function stageLayout(stage: Size, page: Size): { scale: number; left: number; top: number; width: number; height: number } {+ if (!(page.width > 0) || !(page.height > 0) || !(stage.width > 0) || !(stage.height > 0)) {+ return { scale: 1, left: 0, top: 0, width: page.width || 0, height: page.height || 0 };+ }+ const scale = Math.min(1, stage.width / page.width, stage.height / page.height);+ const width = page.width * scale;+ const height = page.height * scale;+ return { scale, left: (stage.width - width) / 2, top: (stage.height - height) / 2, width, height };+}++/** The page point under a client point, given the drawn image's box; null off the page unless clamped. */+export function pagePoint(clientX: number, clientY: number, drawn: Rect, page: Size, clampToEdge = false): { x: number; y: number } | null {+ if (!(drawn.width > 0) || !(drawn.height > 0) || !(page.width > 0) || !(page.height > 0)) return null;+ let x = ((clientX - drawn.left) * page.width) / drawn.width;+ let y = ((clientY - drawn.top) * page.height) / drawn.height;+ if (clampToEdge) {+ x = clamp(x, 0, page.width - 1);+ y = clamp(y, 0, page.height - 1);+ } else if (x < 0 || y < 0 || x >= page.width || y >= page.height) return null;+ return { x: Math.floor(x), y: Math.floor(y) };+}++// ---------------------------------------------------------------------------------------------+// Mouse++export type MouseButtonName = 'left' | 'middle' | 'right' | 'none';++export function buttonName(button: number): MouseButtonName {+ return button === 0 ? 'left' : button === 1 ? 'middle' : button === 2 ? 'right' : 'none';+}++export function mouseModifiers(e: { altKey: boolean; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean }, mac = false): number {+ let m = 0;+ if (e.altKey) m |= MOD.alt;+ if (e.ctrlKey) m |= MOD.ctrl;+ // Cmd-click (open in new tab on a Mac) is Ctrl-click over there+ if (e.metaKey) m |= mac ? MOD.ctrl : MOD.meta;+ if (e.shiftKey) m |= MOD.shift;+ return m;+}++/** Keeps only the newest value and hands it on once per animation frame; flush() sends it now. */+export function createFrameCoalescer<T>(schedule: (fn: () => void) => void, emit: (value: T) => void) {+ let pending: T | null = null;+ let scheduled = false;+ const run = () => {+ scheduled = false;+ if (pending === null) return;+ const v = pending;+ pending = null;+ emit(v);+ };+ return {+ push(value: T) {+ pending = value;+ if (!scheduled) {+ scheduled = true;+ schedule(run);+ }+ },+ /** Sends what's waiting before something that has to come after it (a press, a release). */+ flush() {+ if (pending !== null) run();+ },+ /** Forgets what's waiting (the stage closed). */+ drop() {+ pending = null;+ },+ get pending() {+ return pending;+ },+ };+}++// ---------------------------------------------------------------------------------------------+// Wheel++export const WHEEL_LINE_PX = 40;++/** A wheel event's deltas in CSS px: lines ×40, pages × the viewport's height. */+export function wheelPixels(e: { deltaX: number; deltaY: number; deltaMode: number }, viewportHeight: number): { dx: number; dy: number } {+ const unit = e.deltaMode === 1 ? WHEEL_LINE_PX : e.deltaMode === 2 ? viewportHeight || 800 : 1;+ return { dx: e.deltaX * unit, dy: e.deltaY * unit };+}++export interface WheelMessage {+ action: 'wheel';+ x: number;+ y: number;+ delta_x: number;+ delta_y: number;+ modifiers: number;+}++/**+ * Adds up every wheel step that lands in one animation frame and sends one `wheel` for it.+ * Nothing is dropped: whole pixels go out, the fraction carries over to the next frame.+ */+export function createWheelCoalescer(schedule: (fn: () => void) => void, emit: (msg: WheelMessage) => void) {+ let dx = 0;+ let dy = 0;+ let at = { x: 0, y: 0 };+ let modifiers = 0;+ let scheduled = false;+ const run = () => {+ scheduled = false;+ const sx = Math.trunc(dx);+ const sy = Math.trunc(dy);+ if (sx === 0 && sy === 0) return;+ dx -= sx;+ dy -= sy;+ emit({ action: 'wheel', x: at.x, y: at.y, delta_x: sx, delta_y: sy, modifiers });+ };+ return {+ add(point: { x: number; y: number }, delta: { dx: number; dy: number }, mods = 0) {+ at = point;+ modifiers = mods;+ dx += delta.dx;+ dy += delta.dy;+ if (!scheduled) {+ scheduled = true;+ schedule(run);+ }+ },+ flush() {+ run();+ },+ };+}++// ---------------------------------------------------------------------------------------------+// Keyboard++export interface KeyLike {+ type?: string;+ key: string;+ code: string;+ altKey: boolean;+ ctrlKey: boolean;+ metaKey: boolean;+ shiftKey: boolean;+ repeat?: boolean;+ location?: number;+ isComposing?: boolean;+ keyCode?: number;+}++export interface KeyMessage {+ action: 'key';+ type: 'down' | 'up';+ key: string;+ code: string;+ text?: string;+ modifiers: number;+ location: number;+ auto_repeat: boolean;+}++export type KeyPlan =+ /** Leave it to the browser (composition) and don't send anything. */+ | { kind: 'skip' }+ /** Let the local paste event fire; its text goes as `type`. */+ | { kind: 'paste' }+ | { kind: 'send'; messages: KeyMessage[]; copy?: boolean };++const MODIFIER_KEYS = new Set(['Shift', 'Control', 'Alt', 'Meta', 'OS', 'AltGraph', 'CapsLock', 'Fn', 'FnLock', 'Hyper', 'Super', 'Symbol', 'SymbolLock']);++/** One character (an emoji counts as one): a key that types. */+const printable = (key: string) => key.length > 0 && [...key].length === 1 && key !== '\u0000';++/** Mac editing moves that the Linux remote spells differently. */+function macMove(key: string, meta: boolean, alt: boolean): { key: string; code: string; ctrl: boolean } | null {+ if (meta) {+ if (key === 'ArrowLeft') return { key: 'Home', code: 'Home', ctrl: false };+ if (key === 'ArrowRight') return { key: 'End', code: 'End', ctrl: false };+ if (key === 'ArrowUp') return { key: 'Home', code: 'Home', ctrl: true };+ if (key === 'ArrowDown') return { key: 'End', code: 'End', ctrl: true };+ }+ if (alt && (key === 'ArrowLeft' || key === 'ArrowRight' || key === 'Backspace' || key === 'Delete')) return { key, code: key, ctrl: true };+ return null;+}++/**+ * What a local keydown or keyup sends to the page. Printable keys carry `text` (so keydown,+ * keypress and input all fire there). On a Mac, Cmd shortcuts become Ctrl ones, Cmd+arrows+ * Home/End and Option+arrows word moves; Option's special characters are typed as they are.+ * Cmd or Ctrl+V lets the paste event through; Cmd or Ctrl+C and X also copy the page's selection.+ */+export function planKey(e: KeyLike, mac: boolean): KeyPlan {+ const down = e.type !== 'keyup';+ if (e.isComposing || e.keyCode === 229 || e.key === 'Dead' || e.key === 'Process' || e.key === 'Unidentified') return { kind: 'skip' };+ const shortcut = mac ? e.metaKey : e.ctrlKey;+ const lower = e.key.length === 1 ? e.key.toLowerCase() : '';+ if (down && shortcut && !e.altKey && (e.code === 'KeyV' || lower === 'v')) return { kind: 'paste' };++ let key = e.key;+ let code = e.code;+ let alt = e.altKey;+ let ctrl = e.ctrlKey;+ let meta = e.metaKey;+ let location = e.location ?? 0;++ if (mac) {+ const move = macMove(key, e.metaKey, e.altKey);+ if (move) {+ key = move.key;+ code = move.code;+ ctrl = move.ctrl;+ meta = false;+ alt = false;+ } else if (key === 'Meta') {+ // The Cmd key itself stands in for Control over there+ key = 'Control';+ code = code === 'MetaRight' ? 'ControlRight' : 'ControlLeft';+ ctrl = true;+ meta = false;+ } else if (meta) {+ ctrl = true;+ meta = false;+ }+ // Option+letter is how a Mac types é, ø, ß…: send the character, not an Alt shortcut+ if (alt && !ctrl && printable(key) && !MODIFIER_KEYS.has(key)) alt = false;+ }+ if (!code) {+ // A key with no physical code: only a typed character can still be sent, as text+ if (down && printable(key) && !ctrl && !meta) {+ return { kind: 'send', messages: [{ action: 'key', type: 'down', key, code: '', text: key, modifiers: e.shiftKey ? MOD.shift : 0, location, auto_repeat: !!e.repeat }] };+ }+ return { kind: 'skip' };+ }+ let modifiers = 0;+ if (alt) modifiers |= MOD.alt;+ if (ctrl) modifiers |= MOD.ctrl;+ if (meta) modifiers |= MOD.meta;+ if (e.shiftKey) modifiers |= MOD.shift;++ const msg: KeyMessage = { action: 'key', type: down ? 'down' : 'up', key, code, modifiers, location, auto_repeat: !!e.repeat };+ if (down && printable(key) && !ctrl && !meta && !alt) msg.text = key;+ if (down && key === 'Enter' && !ctrl && !meta && !alt) msg.text = '\r';+ const copy = down && (ctrl || meta) && !alt && (code === 'KeyC' || code === 'KeyX');+ return { kind: 'send', messages: [msg], copy: copy || undefined };+}++/**+ * Keeps the page's idea of which keys are down in step with ours. A Mac never sends keyup for a+ * key pressed while Cmd is down, so those go up straight after their down; anything still down+ * when focus leaves goes up too.+ */+export function createKeyboard(mac: boolean, send: (msg: KeyMessage | { action: 'copy' }) => void) {+ const down = new Map<string, KeyMessage>();+ return {+ /** Returns whether the local default should be prevented (false only for paste and composition). */+ handle(e: KeyLike): boolean {+ const plan = planKey(e, mac);+ if (plan.kind === 'skip') return false;+ if (plan.kind === 'paste') return false;+ for (const m of plan.messages) {+ if (m.type === 'down') {+ send(m);+ const cmdHeld = mac && e.metaKey && e.key !== 'Meta';+ if (cmdHeld) send({ ...m, type: 'up', text: undefined, auto_repeat: false });+ else if (m.code) down.set(m.code, m);+ } else {+ // Up for a key we never sent down (it went up already, or was pressed before focus came)+ if (!down.has(m.code) && !MODIFIER_KEYS.has(m.key)) continue;+ down.delete(m.code);+ send(m);+ }+ }+ if (plan.copy) send({ action: 'copy' });+ return true;+ },+ /** Focus left the page: let go of everything still held. */+ releaseAll() {+ for (const m of down.values()) send({ ...m, type: 'up', text: undefined, auto_repeat: false, modifiers: 0 });+ down.clear();+ },+ held: () => [...down.keys()],+ };+}++/** Text from a paste or the end of an IME composition, in chunks the server accepts (16 KB). */+export function typeMessages(text: string, max = 16 * 1024): Array<{ action: 'type'; text: string }> {+ if (!text) return [];+ const out: Array<{ action: 'type'; text: string }> = [];+ let chunk = '';+ let bytes = 0;+ const enc = new TextEncoder();+ for (const ch of text) {+ const n = enc.encode(ch).length;+ if (bytes + n > max && chunk) {+ out.push({ action: 'type', text: chunk });+ chunk = '';+ bytes = 0;+ }+ chunk += ch;+ bytes += n;+ }+ if (chunk) out.push({ action: 'type', text: chunk });+ return out;+}++// ---------------------------------------------------------------------------------------------+// Popups the screencast can't show++export interface SelectOption {+ label: string;+ value: string;+ disabled: boolean;+ selected: boolean;+}++export interface SelectRequest {+ options: SelectOption[];+ multiple: boolean;+ rect: { x: number; y: number; width: number; height: number };+ /** The field's label on the page, when the server sends one (the phone sheet's title). */+ label?: string;+}++export interface PageDialog {+ kind: 'alert' | 'confirm' | 'prompt' | 'beforeunload';+ message: string;+ default_prompt: string;+}++export function parseSelect(m: unknown): SelectRequest | null {+ const v = m as Record<string, unknown> | null;+ if (!v || !Array.isArray(v.options)) return null;+ const options = v.options.map((o: Record<string, unknown>) => ({+ label: String(o?.label ?? o?.value ?? ''),+ value: String(o?.value ?? ''),+ disabled: !!o?.disabled,+ selected: !!o?.selected,+ }));+ const r = (v.rect ?? {}) as Record<string, unknown>;+ const n = (x: unknown) => (typeof x === 'number' && Number.isFinite(x) ? x : 0);+ const label = typeof v.label === 'string' && v.label.trim() ? v.label.trim().slice(0, 120) : undefined;+ return { options, multiple: !!v.multiple, rect: { x: n(r.x), y: n(r.y), width: n(r.width), height: n(r.height) }, ...(label ? { label } : {}) };+}++export function parseDialog(m: unknown): PageDialog | null {+ const v = m as Record<string, unknown> | null;+ if (!v) return null;+ const kinds = ['alert', 'confirm', 'prompt', 'beforeunload'];+ const kind = (kinds.includes(String(v.kind)) ? v.kind : 'alert') as PageDialog['kind'];+ return { kind, message: String(v.message ?? ''), default_prompt: String(v.default_prompt ?? '') };+}++/** Type-ahead: the first enabled option after `from` (wrapping) whose label starts with `typed`. */+export function matchOption(options: SelectOption[], typed: string, from: number): number {+ const q = typed.toLocaleLowerCase();+ if (!q) return from;+ // Repeating one letter cycles through the options that start with it+ const same = [...q].every((c) => c === q[0]);+ const start = same && q.length > 1 ? from + 1 : q.length === 1 ? from + 1 : from;+ for (let k = 0; k < options.length; k++) {+ const i = (start + k + options.length) % options.length;+ const o = options[i];+ if (o.disabled) continue;+ const label = o.label.trim().toLocaleLowerCase();+ if (same && q.length > 1 ? label.startsWith(q[0]) : label.startsWith(q)) return i;+ }+ return from;+}++/** The next enabled option from `from` going `step` (±1), staying put at the ends. */+export function nextEnabled(options: SelectOption[], from: number, step: 1 | -1): number {+ for (let i = from + step; i >= 0 && i < options.length; i += step) if (!options[i].disabled) return i;+ return from;+}++/** Where the select list goes: under the field, or above it when there's no room below. */+export const POPOVER = { gap: 4, inset: 8, minWidth: 180, maxWidth: 360, flipBelow: 200, maxHeight: 320 } as const;++/**+ * Where a select's list goes in the page area (Mira's spec §4): 4 px under the field, left-aligned,+ * at least 180 and at most 360 wide. It flips above when there's less than 200 px below, and+ * stays 8 px inside the page area.+ */+export function popoverPlacement(anchor: Rect, stage: Size, listHeight: number): { left: number; top: number; width: number; maxHeight: number } {+ const { gap, inset } = POPOVER;+ const width = Math.min(POPOVER.maxWidth, Math.max(anchor.width, POPOVER.minWidth), Math.max(0, stage.width - inset * 2));+ const left = clamp(anchor.left, inset, Math.max(inset, stage.width - inset - width));+ const below = stage.height - inset - (anchor.top + anchor.height + gap);+ const above = anchor.top - gap - inset;+ const want = Math.min(listHeight, POPOVER.maxHeight);+ if (below >= POPOVER.flipBelow || below >= want || below >= above) {+ const maxHeight = Math.max(0, Math.min(POPOVER.maxHeight, below));+ const top = clamp(anchor.top + anchor.height + gap, inset, Math.max(inset, stage.height - inset - Math.min(want, maxHeight)));+ return { left, top, width, maxHeight };+ }+ const maxHeight = Math.max(0, Math.min(POPOVER.maxHeight, above));+ const h = Math.min(want, maxHeight);+ return { left, top: Math.max(inset, anchor.top - gap - h), width, maxHeight };+}diff --git a/frontend/src/components/BrowserControlOverlay.tsx b/frontend/src/components/BrowserControlOverlay.tsxindex 507bd643..20a600b6 100644--- a/frontend/src/components/BrowserControlOverlay.tsx+++ b/frontend/src/components/BrowserControlOverlay.tsx@@ -18,6 +18,8 @@ import {} from '../browserGestures';import { domainOf } from '../humanSteps';import { haptic } from '../haptics';+import type { BrowserStream } from '../useBrowserStream';+import { PageDialogModal, SelectPopover } from './BrowserPopups';/** Sends one gesture to the page: presses, releases, taps and text wait for an ack, moves don't. */export function sendPageInput(send: (payload: Record<string, unknown>, input?: boolean) => void, input: PageInput) {@@ -32,7 +34,9 @@ function ZoomStage({target,onTap,label,+ page = { width: PAGE_W, height: PAGE_H },}: {+ page?: Size;image: string | null;onFrameDone: () => void;send: (input: PageInput) => void;@@ -69,11 +73,13 @@ function ZoomStage({useLayoutEffect(() => {if (!stage.width || !stage.height) return;- if (mode === 'box' && target) setView(zoomToBox(target, stage));- else if (mode === 'fit' || (mode === 'box' && !target)) setView(fitView(stage));- else setView((v) => clampView(v, stage));+ if (mode === 'box' && target) setView(zoomToBox(target, stage, page));+ else if (mode === 'fit' || (mode === 'box' && !target)) setView(fitView(stage, page));+ else setView((v) => clampView(v, stage, page));// eslint-disable-next-line react-hooks/exhaustive-deps- }, [stage.width, stage.height, mode, targetKey]);+ }, [stage.width, stage.height, mode, targetKey, page.width, page.height]);+ const pageRef = useRef(page);+ pageRef.current = page;const sendRef = useRef(send);sendRef.current = send;@@ -82,8 +88,8 @@ function ZoomStage({const tracker = useMemo(() =>createGestureTracker({- toPage: (p) => stageToPage(p.x, p.y, viewRef.current),- toPageClamped: (p) => stageToPageClamped(p.x, p.y, viewRef.current),+ toPage: (p) => stageToPage(p.x, p.y, viewRef.current, pageRef.current),+ toPageClamped: (p) => stageToPageClamped(p.x, p.y, viewRef.current, pageRef.current),send: (input) => {if (input.action === 'click') onTapRef.current?.();sendRef.current(input);@@ -92,9 +98,9 @@ function ZoomStage({get: () => viewRef.current,set: (v) => {setMode('free');- setView(clampView(v, stageSize.current));+ setView(clampView(v, stageSize.current, pageRef.current));},- zoomed: () => viewRef.current.scale > fitView(stageSize.current).scale * 1.02,+ zoomed: () => viewRef.current.scale > fitView(stageSize.current, pageRef.current).scale * 1.02,},now: () => performance.now(),later: (fn, ms) => {@@ -115,7 +121,7 @@ function ZoomStage({ref={stageRef}data-browser-stagearia-label={label}- className="relative flex-1 min-h-0 overflow-hidden bg-black select-none"+ className="relative flex-1 min-h-0 overflow-hidden bg-[#0a0719] select-none"style={{ touchAction: 'none' }}onPointerDown={(e) => {if (e.pointerType === 'mouse' && e.button !== 0) return;@@ -135,7 +141,7 @@ function ZoomStage({onLoad={onFrameDone}onError={onFrameDone}className="absolute left-0 top-0 max-w-none pointer-events-none"- style={{ width: PAGE_W, height: PAGE_H, transformOrigin: '0 0', transform: `translate(${view.tx}px, ${view.ty}px) scale(${view.scale})` }}+ style={{ width: page.width, height: page.height, transformOrigin: '0 0', transform: `translate(${view.tx}px, ${view.ty}px) scale(${view.scale})` }}/>) : (<div className="absolute inset-0 flex items-center justify-center text-zinc-500">@@ -197,6 +203,12 @@ export interface BrowserControlOverlayProps {/** The CAPTCHA closed by itself: say so, then the parent closes this. */solved: boolean;onHandBack: () => void;+ /** The page's viewport size in CSS px (1280×800 unless the desktop stage resized it). */+ page?: Size;+ /** For the page's own <select> lists and alert/confirm/prompt, which the screencast can't show. */+ stream?: Pick<BrowserStream, 'select' | 'dialog' | 'clearSelect' | 'clearDialog'>;+ /** An open sign-in, code or other step for this browser: its Done sits on the status line. */+ step?: { need: string; doneLabel: string; onDone: () => Promise<string | void> | void } | null;}/**@@ -216,8 +228,25 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({captcha,solved,onHandBack,+ page,+ stream,+ step = null,}) => {const keys = useRef<HTMLInputElement>(null);+ const [stepBusy, setStepBusy] = useState(false);+ const [stepError, setStepError] = useState<string | null>(null);+ const answerStep = async () => {+ if (!step || stepBusy) return;+ setStepBusy(true);+ setStepError(null);+ try {+ const err = await step.onDone();+ if (err) setStepError(err);+ else onHandBack();+ } finally {+ setStepBusy(false);+ }+ };const typed = useRef('');const [keyboard, setKeyboard] = useState(false);@@ -256,6 +285,19 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({const domain = domainOf(pageUrl) || pageUrl || 'Browser';const pageInput = useCallback((input: PageInput) => sendPageInput(send, input), [send]);+ // A page dialog dims the page only: Hand back and Done stay usable above it+ const barRef = useRef<HTMLDivElement>(null);+ const [barHeight, setBarHeight] = useState(48);+ useLayoutEffect(() => {+ const el = barRef.current;+ if (!el) return;+ const measure = () => setBarHeight(el.getBoundingClientRect().height);+ measure();+ if (typeof ResizeObserver === 'undefined') return;+ const ro = new ResizeObserver(measure);+ ro.observe(el);+ return () => ro.disconnect();+ }, []);return createPortal(<div@@ -263,12 +305,12 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({aria-modal="true"aria-label={`${botName}'s browser`}data-browser-fullscreen- className="fixed inset-0 z-[70] flex flex-col bg-black text-zinc-100"+ className="fixed inset-0 z-[70] flex flex-col bg-[#0a0719] text-zinc-100"style={{ paddingLeft: 'env(safe-area-inset-left)', paddingRight: 'env(safe-area-inset-right)' }}>- <div className="shrink-0 bg-zinc-950/95 border-b border-zinc-800" style={{ paddingTop: 'env(safe-area-inset-top)' }}>+ <div ref={barRef} className="shrink-0 bg-[#0e0a21] border-b border-white/[0.07]" style={{ paddingTop: 'env(safe-area-inset-top)' }}><div className="h-12 px-2 flex items-center gap-2">- <span className={`shrink-0 w-2 h-2 rounded-full ${busy ? 'bg-cyan-300 animate-pulse motion-reduce:animate-none' : 'bg-cyan-500'}`} aria-hidden="true" />+ <span className={`shrink-0 w-2 h-2 rounded-full bg-control ${busy ? 'animate-pulse motion-reduce:animate-none' : ''}`} aria-hidden="true" /><span className="flex-1 min-w-0 truncate font-mono text-xs text-zinc-300" title={pageUrl}>{domain}</span>@@ -277,7 +319,7 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({onClick={openKeyboard}aria-pressed={keyboard}aria-label="Keyboard"- className="shrink-0 inline-flex items-center justify-center w-11 h-10 rounded-lg text-zinc-300 hover:bg-zinc-800"+ className="shrink-0 inline-flex items-center justify-center w-11 h-11 rounded-lg text-zinc-200 hover:bg-white/[0.06] focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300"><Keyboard size={18} aria-hidden="true" /></button>@@ -287,28 +329,47 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({haptic('tap');onHandBack();}}- className="shrink-0 inline-flex items-center gap-1.5 h-10 px-3 rounded-lg bg-cyan-500 text-zinc-950 text-sm font-semibold"+ data-primary={step ? undefined : true}+ className={`shrink-0 inline-flex items-center gap-1.5 h-11 px-3 rounded-[10px] text-sm font-semibold focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300 ${+ step ? 'bg-[rgb(44_37_82/0.8)] border border-[#3f3868] text-[#ecebfa] hover:bg-[#2c2552]' : 'bg-[#6c58e0] hover:bg-[#5845bd] text-white'+ }`}><Hand size={15} aria-hidden="true" /> Hand back</button></div>- {(solved || captcha || error) && (+ {(solved || captcha || error || stepError) ? (<prole="status"aria-live="polite"- className={`px-3 pb-2 text-xs ${solved ? 'text-emerald-300' : error ? 'text-rose-300' : 'text-amber-200'}`}+ className={`px-3 pb-2 text-xs ${solved ? 'text-[#5eead4]' : error || stepError ? 'text-rose-300' : 'text-[#fcd34d]'}`}>{solved ? (<span className="inline-flex items-center gap-1.5"><CheckCircle2 size={13} aria-hidden="true" /> Solved, {botName} continues</span>- ) : error ? (- error+ ) : error || stepError ? (+ stepError || error) : (<>Solve the puzzle, {botName} continues by itself</>)}</p>- )}+ ) : step ? (+ <div className="min-h-[52px] pl-3 pr-2 pb-2 flex items-center gap-2 text-xs">+ <span role="status" aria-live="polite" className="flex-1 min-w-0 truncate font-semibold text-[#fcd34d]">+ @{botName} {step.need}+ </span>+ <button+ type="button"+ onClick={answerStep}+ disabled={stepBusy}+ data-primary+ className="shrink-0 inline-flex items-center gap-1.5 h-11 px-[14px] rounded-[12px] bg-[#6c58e0] hover:bg-[#5845bd] text-white text-[15px] font-semibold disabled:opacity-60 focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300"+ >+ {stepBusy ? <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <CheckCircle2 size={14} aria-hidden="true" />}+ {step.doneLabel}+ </button>+ </div>+ ) : null}</div><ZoomStage@@ -317,8 +378,36 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({send={pageInput}target={captcha?.target ?? null}label={`${botName}'s page. Tap to click, drag with one finger, pinch to zoom.`}+ page={page}/>+ {stream?.select && (+ <SelectPopover+ request={stream.select}+ anchor={null}+ stage={{ width: 0, height: 0 }}+ onPick={(indexes) => {+ send(stream.select!.multiple ? { action: 'select_option', indexes } : { action: 'select_option', index: indexes[0] }, true);+ stream.clearSelect();+ }}+ onClose={stream.clearSelect}+ />+ )}+ {stream?.dialog && (+ <div className="absolute inset-x-0 bottom-0 z-50" style={{ top: barHeight }} data-dialog-area>+ <PageDialogModal+ key={`${stream.dialog.kind}:${stream.dialog.message}`}+ dialog={stream.dialog}+ host={domain}+ compact+ onAnswer={(accept, text) => {+ send(text !== undefined ? { action: 'dialog', accept, prompt_text: text } : { action: 'dialog', accept }, true);+ stream.clearDialog();+ }}+ />+ </div>+ )}+<div className="shrink-0" style={{ height: 'env(safe-area-inset-bottom)' }} /><inputdiff --git a/frontend/src/components/BrowserPopups.tsx b/frontend/src/components/BrowserPopups.tsxnew file mode 100644index 00000000..b2a536dd--- /dev/null+++ b/frontend/src/components/BrowserPopups.tsx@@ -0,0 +1,318 @@+import React, { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';+import { Check, Globe } from 'lucide-react';+import { PageDialog, Rect, SelectRequest, Size, matchOption, nextEnabled, popoverPlacement } from '../browserInput';++const PAGE_STEP = 8;+const TYPEAHEAD_MS = 500;+const focusRing = 'focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300';+export const PRIMARY_BUTTON = `bg-[#6c58e0] hover:bg-[#5845bd] text-white font-semibold ${focusRing}`;+export const GHOST_BUTTON = `bg-[rgb(44_37_82/0.8)] hover:bg-[#2c2552] border border-[#3f3868] text-zinc-100 ${focusRing}`;++/**+ * A page's <select>, drawn by us: the screencast can't show the native list. Arrows, Home/End,+ * PageUp/Down and type-ahead move; Enter or a click picks; Escape or a click outside closes.+ * `anchor` is the field's box in the page area; null shows a bottom sheet (phones).+ */+export function SelectPopover({+ request,+ anchor,+ stage,+ onPick,+ onClose,+}: {+ request: SelectRequest;+ anchor: Rect | null;+ stage: Size;+ onPick: (indexes: number[]) => void;+ onClose: () => void;+}) {+ const { options, multiple } = request;+ const first = Math.max(0, options.findIndex((o) => o.selected && !o.disabled));+ const [active, setActive] = useState(options[first]?.disabled ? nextEnabled(options, -1, 1) : first);+ const [chosen, setChosen] = useState<Set<number>>(() => new Set(options.flatMap((o, i) => (o.selected ? [i] : []))));+ const listRef = useRef<HTMLUListElement>(null);+ const typed = useRef({ text: '', at: 0 });+ const id = useId();+ const sheet = !anchor;++ useLayoutEffect(() => {+ listRef.current?.focus({ preventScroll: true });+ }, []);+ useEffect(() => {+ listRef.current?.querySelector<HTMLElement>(`[data-index="${active}"]`)?.scrollIntoView({ block: 'nearest' });+ }, [active]);++ const pick = (i: number) => {+ if (options[i]?.disabled) return;+ if (!multiple) return onPick([i]);+ setChosen((s) => {+ const n = new Set(s);+ if (n.has(i)) n.delete(i);+ else n.add(i);+ return n;+ });+ };+ const moveBy = (from: number, n: number) => {+ let a = from;+ for (let k = 0; k < Math.abs(n); k++) a = nextEnabled(options, a, n > 0 ? 1 : -1);+ return a;+ };++ const onKeyDown = (e: React.KeyboardEvent) => {+ e.stopPropagation();+ if (e.key === 'ArrowDown') setActive((a) => nextEnabled(options, a, 1));+ else if (e.key === 'ArrowUp') setActive((a) => nextEnabled(options, a, -1));+ else if (e.key === 'Home') setActive(nextEnabled(options, -1, 1));+ else if (e.key === 'End') setActive(nextEnabled(options, options.length, -1));+ else if (e.key === 'PageDown') setActive((a) => moveBy(a, PAGE_STEP));+ else if (e.key === 'PageUp') setActive((a) => moveBy(a, -PAGE_STEP));+ else if (e.key === 'Enter' || (e.key === ' ' && multiple && !typed.current.text)) {+ if (multiple && e.key === 'Enter') onPick([...chosen].sort((a, b) => a - b));+ else pick(active);+ } else if (e.key === 'Escape' || e.key === 'Tab') onClose();+ else if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {+ const now = e.timeStamp;+ const t = typed.current;+ t.text = now - t.at > TYPEAHEAD_MS ? e.key : t.text + e.key;+ t.at = now;+ setActive((a) => matchOption(options, t.text, a));+ } else return;+ e.preventDefault();+ };++ const place = anchor ? popoverPlacement(anchor, stage, options.length * 32 + 8 + 30) : null;++ const list = (+ <ul+ ref={listRef}+ id={id}+ role="listbox"+ aria-multiselectable={multiple || undefined}+ aria-activedescendant={`${id}-${active}`}+ aria-label={request.label || 'Choose an option'}+ tabIndex={0}+ onKeyDown={onKeyDown}+ className={`flex-1 min-h-0 overflow-y-auto focus:outline-none ${sheet ? 'px-2 py-1' : 'p-1'}`}+ >+ {options.map((o, i) => {+ const on = multiple ? chosen.has(i) : o.selected;+ const isActive = i === active && !o.disabled;+ return (+ <li+ key={i}+ id={`${id}-${i}`}+ data-index={i}+ role="option"+ aria-selected={on}+ aria-disabled={o.disabled || undefined}+ onMouseEnter={() => !o.disabled && setActive(i)}+ onClick={() => pick(i)}+ className={`flex items-center gap-2 pl-2 pr-2.5 rounded-md cursor-default ${sheet ? 'h-12 text-base' : 'h-8 text-sm'} ${+ o.disabled ? 'text-[#6f6898]' : 'text-zinc-100'+ } ${isActive ? 'bg-[#313868] shadow-[inset_2px_0_0_#7cc4ff]' : ''}`}+ >+ <span className="w-4 shrink-0 flex items-center justify-center text-sky-200" aria-hidden="true">+ {multiple ? (+ <span className={`w-3.5 h-3.5 rounded-[3px] border flex items-center justify-center ${on ? 'bg-[#6c58e0] border-[#6c58e0] text-white' : 'border-[#5a5383]'}`}>+ {on && <Check size={11} strokeWidth={3} />}+ </span>+ ) : (+ on && <Check size={14} />+ )}+ </span>+ <span className="truncate">{o.label || ' '}</span>+ </li>+ );+ })}+ </ul>+ );++ if (sheet) {+ return (+ <div+ className="fixed inset-0 z-[80] flex items-end bg-[rgb(5_3_15/0.6)]"+ data-browser-popup+ onPointerDown={(e) => {+ e.stopPropagation();+ if (e.target === e.currentTarget) onClose();+ }}+ onMouseDown={(e) => e.stopPropagation()}+ >+ <SheetBody title={request.label || 'Choose an option'} onClose={onClose}>+ {list}+ {multiple && (+ <div className="shrink-0 flex gap-2 px-3 pt-2">+ <button type="button" onClick={onClose} className={`flex-1 h-11 rounded-[10px] text-sm ${GHOST_BUTTON}`}>+ Cancel+ </button>+ <button type="button" onClick={() => onPick([...chosen].sort((a, b) => a - b))} className={`flex-1 h-11 rounded-[10px] text-sm ${PRIMARY_BUTTON}`}>+ Done+ </button>+ </div>+ )}+ </SheetBody>+ </div>+ );+ }++ return (+ <div+ className="absolute inset-0 z-40"+ data-browser-popup+ onPointerDown={(e) => {+ e.stopPropagation();+ if (e.target === e.currentTarget) onClose();+ }}+ onMouseDown={(e) => e.stopPropagation()}+ onWheel={(e) => e.stopPropagation()}+ >+ <div+ data-select-popover+ className="absolute flex flex-col rounded-[10px] border border-white/[0.14] bg-[#231d4b] shadow-[0_12px_32px_rgb(0_0_0/0.45)] overflow-hidden kw-pop-in"+ style={place ? { left: place.left, top: place.top, width: place.width, maxHeight: place.maxHeight } : undefined}+ >+ {list}+ <div className="shrink-0 hidden lg:flex items-center gap-2 px-2.5 h-[30px] border-t border-white/[0.07] text-[11px] text-zinc-400">+ <span className="flex-1 truncate">+ <Kbd>↑↓</Kbd> move · <Kbd>Enter</Kbd> {multiple ? 'done' : 'pick'} · <Kbd>Esc</Kbd> close+ </span>+ {multiple && (+ <button type="button" onClick={() => onPick([...chosen].sort((a, b) => a - b))} className={`h-6 px-2 rounded-md text-xs ${PRIMARY_BUTTON}`}>+ Done+ </button>+ )}+ </div>+ {multiple && (+ <div className="shrink-0 lg:hidden flex justify-end p-1.5 border-t border-white/[0.07]">+ <button type="button" onClick={() => onPick([...chosen].sort((a, b) => a - b))} className={`h-8 px-3 rounded-[10px] text-sm ${PRIMARY_BUTTON}`}>+ Done+ </button>+ </div>+ )}+ </div>+ </div>+ );+}++const Kbd = ({ children }: { children: React.ReactNode }) => (+ <kbd className="inline-block px-1 rounded bg-[#2c2552] font-sans text-[10px] text-zinc-300">{children}</kbd>+);++/** A bottom sheet with a grabber: swiping it down closes it. */+function SheetBody({ title, onClose, children }: { title: string; onClose: () => void; children: React.ReactNode }) {+ const start = useRef<number | null>(null);+ const [drag, setDrag] = useState(0);+ return (+ <div+ role="dialog"+ aria-label={title}+ data-select-sheet+ className="kw-sheet w-full max-h-[60vh] flex flex-col rounded-t-2xl bg-[#1a1538] border-t border-white/[0.14] shadow-2xl"+ style={{ transform: drag ? `translateY(${drag}px)` : undefined }}+ >+ <div+ className="shrink-0 pt-2 pb-1 touch-none"+ onPointerDown={(e) => {+ start.current = e.clientY;+ e.currentTarget.setPointerCapture?.(e.pointerId);+ }}+ onPointerMove={(e) => start.current !== null && setDrag(Math.max(0, e.clientY - start.current))}+ onPointerUp={() => {+ if (drag > 60) onClose();+ start.current = null;+ setDrag(0);+ }}+ onPointerCancel={() => {+ start.current = null;+ setDrag(0);+ }}+ >+ <div className="mx-auto w-9 h-1 rounded-full bg-[#3f3868]" aria-hidden="true" />+ <p className="px-4 pt-2.5 pb-1 text-[13px] text-[#a39dcc] truncate">{title}</p>+ </div>+ {children}+ </div>+ );+}++/** A page's alert, confirm, prompt or "leave this page?", answered here; the page waits on it. */+export function PageDialogModal({ dialog, host, onAnswer, compact = false }: { dialog: PageDialog; host: string; onAnswer: (accept: boolean, text?: string) => void; /** Phone: the page area is short, so the card sits 16 px down, not 96 */ compact?: boolean }) {+ const [text, setText] = useState(dialog.default_prompt);+ const okRef = useRef<HTMLButtonElement>(null);+ const inputRef = useRef<HTMLInputElement>(null);+ const titleId = useId();+ const messageId = useId();+ const cancellable = dialog.kind !== 'alert';+ const leave = dialog.kind === 'beforeunload';++ useLayoutEffect(() => {+ if (dialog.kind === 'prompt') inputRef.current?.select();+ else okRef.current?.focus({ preventScroll: true });+ }, [dialog.kind]);++ const button = 'h-8 [@media(pointer:coarse)]:h-11 px-3 rounded-[10px] text-[13px] max-sm:flex-1';++ return (+ <div+ className={`absolute inset-0 z-50 flex justify-center items-start px-4 sm:px-0 ${compact ? 'pt-4' : 'pt-24'} bg-[rgb(10_7_25/0.6)]`}+ data-browser-popup+ onPointerDown={(e) => e.stopPropagation()}+ onMouseDown={(e) => e.stopPropagation()}+ onWheel={(e) => e.stopPropagation()}+ >+ <form+ role="alertdialog"+ aria-modal="true"+ aria-labelledby={titleId}+ aria-describedby={dialog.message ? messageId : undefined}+ data-escape-layer+ data-page-dialog+ onSubmit={(e) => {+ e.preventDefault();+ onAnswer(true, dialog.kind === 'prompt' ? text : undefined);+ }}+ onKeyDown={(e) => {+ e.stopPropagation();+ if (e.key === 'Escape') {+ e.preventDefault();+ onAnswer(!cancellable);+ }+ }}+ className="w-full sm:w-[420px] rounded-[14px] border border-white/[0.14] bg-[#1a1538] p-4 shadow-[0_24px_64px_rgb(0_0_0/0.55)] text-zinc-100 kw-pop-in"+ >+ <p id={titleId} className="flex items-center gap-1.5 text-xs text-[#a39dcc] min-w-0">+ <Globe size={14} className="shrink-0" aria-hidden="true" />+ <span className="truncate">+ <span className="font-semibold text-zinc-100">{host}</span> {leave ? 'asks if you want to leave' : 'asks'}+ </span>+ </p>+ {dialog.message && (+ <p id={messageId} className="mt-3 text-[15px] leading-[22px] whitespace-pre-wrap break-words max-h-60 overflow-y-auto">+ {dialog.message}+ </p>+ )}+ {leave && !dialog.message && <p className="mt-3 text-[15px] leading-[22px]">Changes you made may not be saved.</p>}+ {dialog.kind === 'prompt' && (+ <input+ ref={inputRef}+ value={text}+ onChange={(e) => setText(e.target.value)}+ aria-label="Answer"+ className="mt-3 w-full h-9 px-3 rounded-[10px] bg-[#120e26] border border-white/[0.14] text-sm focus:outline-none focus:ring-2 focus:ring-sky-300"+ />+ )}+ <div className="mt-4 flex flex-wrap items-center gap-2">+ <p className="basis-full sm:basis-auto sm:flex-1 text-xs text-zinc-400">The page is paused until you answer.</p>+ {cancellable && (+ <button type="button" onClick={() => onAnswer(false)} className={`${button} ${GHOST_BUTTON}`}>+ {leave ? 'Stay' : 'Cancel'}+ </button>+ )}+ <button ref={okRef} type="submit" className={`${button} ${PRIMARY_BUTTON}`}>+ {leave ? 'Leave' : 'OK'}+ </button>+ </div>+ </form>+ </div>+ );+}diff --git a/frontend/src/components/BrowserTakeoverStage.tsx b/frontend/src/components/BrowserTakeoverStage.tsxnew file mode 100644index 00000000..3e3f12f0--- /dev/null+++ b/frontend/src/components/BrowserTakeoverStage.tsx@@ -0,0 +1,757 @@+import React, { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { ArrowLeft, ArrowRight, Check, Globe, Hand, Keyboard, Loader2, Lock, MousePointerClick, RotateCw } from 'lucide-react';+import {+ Size,+ buttonName,+ createFrameCoalescer,+ createKeyboard,+ createWheelCoalescer,+ isMacPlatform,+ mouseModifiers,+ pagePoint,+ resizeFor,+ sizeDrifted,+ stageLayout,+ typeMessages,+ wheelPixels,+} from '../browserInput';+import { PageInput, Pt, createGestureTracker } from '../browserGestures';+import { domainOf } from '../humanSteps';+import type { BrowserStream } from '../useBrowserStream';+import { BOT_BUSY_TEXT } from '../useBrowserStream';+import { GHOST_BUTTON, PRIMARY_BUTTON, PageDialogModal, SelectPopover } from './BrowserPopups';+import { ModernAvatar } from './ModernAvatar';+import { sendPageInput } from './BrowserControlOverlay';++/** How long the stage waits for its size to settle before asking the page to match it. */+export const RESIZE_DEBOUNCE_MS = 150;+/** How long a page may differ from the asked-for size before the stage asks again, and how often. */+export const SIZE_DRIFT_MS = 600;+const SIZE_RESENDS = 3;+/** "Relaying…" shows only for a discrete action still waiting after this long, so quick ones never flash. */+export const RELAYING_DELAY_MS = 300;++const WIDE_QUERY = '(min-width: 1024px)';+function useWide(): boolean {+ const [wide, setWide] = useState(() => typeof window !== 'undefined' && !!window.matchMedia?.(WIDE_QUERY).matches);+ useEffect(() => {+ const mq = window.matchMedia?.(WIDE_QUERY);+ if (!mq) return;+ const on = () => setWide(mq.matches);+ mq.addEventListener('change', on);+ return () => mq.removeEventListener('change', on);+ }, []);+ return wide;+}++/** The address split for display: host bright, path and query muted. */+export function splitAddress(raw: string): { secure: boolean; host: string; rest: string } {+ try {+ const u = new URL(raw);+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return { secure: false, host: raw, rest: '' };+ const rest = `${u.pathname === '/' && !u.search && !u.hash ? '' : u.pathname}${u.search}${u.hash}`;+ return { secure: u.protocol === 'https:', host: u.host, rest };+ } catch {+ return { secure: false, host: raw, rest: '' };+ }+}++export interface BrowserTakeoverStageProps {+ botName: string;+ pageUrl: string;+ pageTitle?: string;+ stream: BrowserStream;+ /** The page image as a data URL, or null before the first frame. */+ image: string | null;+ /** An open sign-in (or code, or other) step for this browser: answering it also hands back. */+ step?: { doneLabel: string; onDone: () => Promise<string | void> | void } | null;+ /** The bot's avatar sprite, when known. */+ avatarRole?: string;+ /** Opens an address while the bot still has the browser (not used while in control). */+ onNavigate?: (url: string) => void;+ /** A CAPTCHA hint, or that it was solved. */+ notice?: { tone: 'warn' | 'success'; text: string } | null;+ onHandBack: () => void;+ onRetryControl: () => void;+}++const BUTTON_BIT: Record<number, number> = { 0: 1, 1: 4, 2: 2 };++/**+ * Taking over a bot's browser on a computer or tablet: the page fills a large stage over the app,+ * drawn 1:1 with the page resized to match. Mouse, wheel and keyboard go to the page as they are;+ * the top bar keeps the address, history and "Hand back".+ */+export const BrowserTakeoverStage: React.FC<BrowserTakeoverStageProps> = ({ botName, pageUrl, pageTitle, stream, image, step, avatarRole, onNavigate, notice, onHandBack, onRetryControl }) => {+ const { send, controlling, frame, acknowledgeFrame } = stream;+ const stageRef = useRef<HTMLDivElement>(null);+ const imgRef = useRef<HTMLImageElement>(null);+ const sinkRef = useRef<HTMLTextAreaElement>(null);+ const urlRef = useRef<HTMLInputElement>(null);+ const actionRef = useRef<HTMLButtonElement>(null);+ const wide = useWide();+ // Where keystrokes go: the page, or the top bar (then the outline dims and a hint says so)+ const [pageFocused, setPageFocused] = useState(true);+ const [stage, setStage] = useState<Size>({ width: 0, height: 0 });+ const [url, setUrl] = useState(pageUrl);+ const [urlEditing, setUrlEditing] = useState(false);+ const [stepBusy, setStepBusy] = useState(false);+ const [stepError, setStepError] = useState<string | null>(null);+ const mac = useMemo(() => isMacPlatform(), []);++ useEffect(() => {+ if (!urlEditing) setUrl(pageUrl);+ }, [pageUrl, urlEditing]);++ // The page's size in CSS px; the image may carry dpr times as many pixels+ const page: Size = { width: frame?.width || 1280, height: frame?.height || 800 };+ const layout = stageLayout(stage, page);+ const pageRef = useRef(page);+ pageRef.current = page;+ const controllingRef = useRef(controlling);+ controllingRef.current = controlling;+ const sendRef = useRef(send);+ sendRef.current = send;++ // The app behind can't scroll while this is up+ useEffect(() => {+ const html = document.documentElement;+ const before = html.style.overflow;+ html.style.overflow = 'hidden';+ return () => {+ html.style.overflow = before;+ };+ }, []);++ useLayoutEffect(() => {+ const el = stageRef.current;+ if (!el) return;+ const measure = () => setStage({ width: el.clientWidth, height: el.clientHeight });+ measure();+ const ro = new ResizeObserver(measure);+ ro.observe(el);+ return () => ro.disconnect();+ }, []);++ // Ask the page to be exactly the stage's size, once it stops changing+ const lastResize = useRef('');+ const requested = useRef<{ width: number; height: number } | null>(null);+ const resends = useRef(0);+ useEffect(() => {+ if (!controlling) {+ lastResize.current = '';+ requested.current = null;+ resends.current = 0;+ return;+ }+ const msg = resizeFor(stage, window.devicePixelRatio);+ if (!msg) return;+ const key = `${msg.width}x${msg.height}@${msg.dpr}`;+ if (key === lastResize.current) return;+ const t = window.setTimeout(() => {+ lastResize.current = key;+ requested.current = { width: msg.width, height: msg.height };+ resends.current = 0;+ sendRef.current(msg);+ }, lastResize.current ? RESIZE_DEBOUNCE_MS : 0);+ return () => window.clearTimeout(t);+ }, [controlling, stage.width, stage.height]);++ // A cross-site navigation can put the page back to its own size: ask again, a few times at most+ useEffect(() => {+ if (!controlling || !sizeDrifted(requested.current, page)) {+ if (controlling && requested.current) resends.current = 0;+ return;+ }+ if (resends.current >= SIZE_RESENDS) return;+ const t = window.setTimeout(() => {+ const msg = resizeFor(stage, window.devicePixelRatio);+ if (!msg || !sizeDrifted(requested.current, pageRef.current)) return;+ resends.current += 1;+ sendRef.current(msg);+ }, SIZE_DRIFT_MS);+ return () => window.clearTimeout(t);+ }, [controlling, page.width, page.height, pageUrl]);++ const focusPage = useCallback(() => sinkRef.current?.focus({ preventScroll: true }), []);+ useEffect(() => {+ focusPage();+ }, [focusPage]);++ const toPage = useCallback((clientX: number, clientY: number, clampToEdge: boolean) => {+ const img = imgRef.current;+ if (!img) return null;+ const r = img.getBoundingClientRect();+ return pagePoint(clientX, clientY, r, pageRef.current, clampToEdge);+ }, []);++ // Mouse: moves once a frame, presses and releases as they happen, wheel steps summed per frame+ const heldButtons = useRef(0);+ const lastTouch = useRef(-Infinity);+ const raf = useCallback((fn: () => void) => {+ requestAnimationFrame(fn);+ }, []);+ const moves = useMemo(+ () =>+ createFrameCoalescer<{ x: number; y: number; buttons: number; modifiers: number }>(raf, (m) => {+ const button = m.buttons & 1 ? 'left' : m.buttons & 2 ? 'right' : m.buttons & 4 ? 'middle' : 'none';+ sendRef.current({ action: 'mouse', type: 'move', x: m.x, y: m.y, button, buttons: m.buttons, click_count: 0, modifiers: m.modifiers });+ }),+ [raf]+ );+ const wheel = useMemo(() => createWheelCoalescer(raf, (m) => sendRef.current({ ...m })), [raf]);+ const keyboard = useMemo(() => createKeyboard(mac, (m) => sendRef.current(m as unknown as Record<string, unknown>)), [mac]);++ const popupOpen = !!stream.select || !!stream.dialog;+ const popupRef = useRef(popupOpen);+ popupRef.current = popupOpen;++ useEffect(() => {+ const el = stageRef.current;+ if (!el) return;+ const inPopup = (t: EventTarget | null) => !!(t as Element | null)?.closest?.('[data-browser-popup]');++ const onDown = (e: MouseEvent) => {+ if (inPopup(e.target)) return;+ // A touch also fires mouse events after it; the touch path already sent it+ if (e.timeStamp - lastTouch.current < 800) return;+ e.preventDefault();+ focusPage();+ if (!controllingRef.current) {+ // The first click takes the browser back; it isn't passed to the page+ onRetryControl();+ return;+ }+ const p = toPage(e.clientX, e.clientY, false);+ if (!p) return;+ moves.flush();+ heldButtons.current |= BUTTON_BIT[e.button] ?? 0;+ sendRef.current({ action: 'mouse', type: 'down', x: p.x, y: p.y, button: buttonName(e.button), buttons: e.buttons || heldButtons.current, click_count: Math.max(1, e.detail || 1), modifiers: mouseModifiers(e, mac) });+ };+ const onMove = (e: MouseEvent) => {+ if (!controllingRef.current || popupRef.current) return;+ if (e.timeStamp - lastTouch.current < 800) return;+ const held = heldButtons.current !== 0;+ if (!held && !el.contains(e.target as Node)) return;+ const p = toPage(e.clientX, e.clientY, held);+ if (!p) return;+ moves.push({ ...p, buttons: held ? e.buttons || heldButtons.current : 0, modifiers: mouseModifiers(e, mac) });+ };+ const onUp = (e: MouseEvent) => {+ const bit = BUTTON_BIT[e.button] ?? 0;+ if (!(heldButtons.current & bit)) return;+ heldButtons.current &= ~bit;+ const p = toPage(e.clientX, e.clientY, true);+ if (!p) return;+ moves.flush();+ sendRef.current({ action: 'mouse', type: 'up', x: p.x, y: p.y, button: buttonName(e.button), buttons: heldButtons.current, click_count: Math.max(1, e.detail || 1), modifiers: mouseModifiers(e, mac) });+ };+ const onContext = (e: MouseEvent) => {+ if (!inPopup(e.target)) e.preventDefault();+ };+ const onWheel = (e: WheelEvent) => {+ if (inPopup(e.target)) return;+ e.preventDefault();+ if (!controllingRef.current) return;+ const p = toPage(e.clientX, e.clientY, true);+ if (!p) return;+ wheel.add(p, wheelPixels(e, pageRef.current.height), mouseModifiers(e, mac));+ };+ const onBlurWindow = () => {+ // Released outside the window: the page shouldn't think a button is still down+ if (!heldButtons.current) return;+ heldButtons.current = 0;+ };+ el.addEventListener('mousedown', onDown);+ window.addEventListener('mousemove', onMove);+ window.addEventListener('mouseup', onUp);+ el.addEventListener('contextmenu', onContext);+ el.addEventListener('wheel', onWheel, { passive: false });+ window.addEventListener('blur', onBlurWindow);+ return () => {+ el.removeEventListener('mousedown', onDown);+ window.removeEventListener('mousemove', onMove);+ window.removeEventListener('mouseup', onUp);+ el.removeEventListener('contextmenu', onContext);+ el.removeEventListener('wheel', onWheel);+ window.removeEventListener('blur', onBlurWindow);+ moves.drop();+ };+ }, [focusPage, mac, moves, onRetryControl, toPage, wheel]);++ // Touch on a tablet: tap clicks, one finger drags, two fingers scroll (the phone's gestures, no zoom)+ const tracker = useMemo(+ () =>+ createGestureTracker({+ toPage: (p: Pt) => toPage(p.x, p.y, false),+ toPageClamped: (p: Pt) => toPage(p.x, p.y, true) ?? { x: 0, y: 0 },+ send: (input: PageInput) => sendPageInput(sendRef.current, input),+ now: () => performance.now(),+ later: (fn, ms) => {+ const t = window.setTimeout(fn, ms);+ return () => window.clearTimeout(t);+ },+ }),+ [toPage]+ );++ // Keyboard: a hidden, focused text area takes every key (and IME, and paste) for the page+ useEffect(() => {+ const sink = sinkRef.current;+ if (!sink) return;+ const onKey = (e: KeyboardEvent) => {+ // Nothing reaches the app's own shortcuts (Escape, Cmd+K, Ctrl+1…) while typing into the page+ e.stopPropagation();+ if (e.type === 'keydown' && e.key === 'F6') {+ e.preventDefault();+ (actionRef.current ?? urlRef.current)?.focus();+ return;+ }+ if (!controllingRef.current) {+ if (e.type === 'keydown' && !e.isComposing) e.preventDefault();+ return;+ }+ if (keyboard.handle(e)) e.preventDefault();+ };+ const onPaste = (e: ClipboardEvent) => {+ e.preventDefault();+ e.stopPropagation();+ if (!controllingRef.current) return;+ const text = e.clipboardData?.getData('text/plain') ?? '';+ for (const m of typeMessages(text)) sendRef.current(m, true);+ };+ const onCompositionEnd = (e: CompositionEvent) => {+ if (controllingRef.current && e.data) for (const m of typeMessages(e.data)) sendRef.current(m, true);+ sink.value = '';+ };+ // Text that came without a key we could send (dictation, an on-screen keyboard)+ const onInput = (e: Event) => {+ const ie = e as InputEvent;+ if (ie.isComposing) return;+ if (controllingRef.current && ie.inputType === 'insertText' && ie.data) for (const m of typeMessages(ie.data)) sendRef.current(m, true);+ sink.value = '';+ };+ const onBlur = () => {+ keyboard.releaseAll();+ // Switching to another window keeps the page as the target; focus comes back to it+ window.setTimeout(() => {+ if (document.hasFocus() && document.activeElement !== sink) setPageFocused(false);+ }, 0);+ };+ const onFocus = () => setPageFocused(true);+ sink.addEventListener('focus', onFocus);+ sink.addEventListener('keydown', onKey);+ sink.addEventListener('keyup', onKey);+ sink.addEventListener('paste', onPaste);+ sink.addEventListener('compositionend', onCompositionEnd);+ sink.addEventListener('input', onInput);+ sink.addEventListener('blur', onBlur);+ return () => {+ sink.removeEventListener('keydown', onKey);+ sink.removeEventListener('keyup', onKey);+ sink.removeEventListener('paste', onPaste);+ sink.removeEventListener('compositionend', onCompositionEnd);+ sink.removeEventListener('input', onInput);+ sink.removeEventListener('blur', onBlur);+ sink.removeEventListener('focus', onFocus);+ keyboard.releaseAll();+ };+ }, [keyboard]);++ // A new frame is drawn in the same image; acknowledge it once it has loaded+ const frameId = useRef<number | null>(null);+ frameId.current = frame?.id ?? null;+ const onFrameLoaded = useCallback(() => {+ if (frameId.current !== null) acknowledgeFrame(frameId.current);+ }, [acknowledgeFrame]);++ const navigate = (raw: string) => {+ let target = raw.trim();+ if (!target) return;+ if (!/^https?:\/\//i.test(target)) target = `https://${target}`;+ setUrlEditing(false);+ if (controlling) send({ action: 'navigate', url: target }, true);+ else onNavigate?.(target);+ focusPage();+ };+ const history = (direction: 'back' | 'forward' | 'reload') => {+ send({ action: 'history', direction }, true);+ focusPage();+ };++ const answerStep = async () => {+ if (!step) return;+ setStepBusy(true);+ setStepError(null);+ try {+ const err = await step.onDone();+ if (err) {+ setStepError(err);+ return;+ }+ onHandBack();+ } finally {+ setStepBusy(false);+ }+ };+++ const domain = domainOf(pageUrl) || pageUrl || 'the page';+ const address = splitAddress(urlEditing ? pageUrl : url || pageUrl);+ const anchor = stream.select+ ? {+ left: layout.left + stream.select.rect.x * layout.scale,+ top: layout.top + stream.select.rect.y * layout.scale,+ width: stream.select.rect.width * layout.scale,+ height: stream.select.rect.height * layout.scale,+ }+ : null;+ const showHistory = !stream.unsupported.has('history');+ const error = stream.error;++ // "Relaying…" only for a discrete action still waiting after a moment, so quick ones never flash+ const [relaying, setRelaying] = useState(false);+ useEffect(() => {+ if (!stream.busy) {+ setRelaying(false);+ return;+ }+ const t = window.setTimeout(() => setRelaying(true), RELAYING_DELAY_MS);+ return () => window.clearTimeout(t);+ }, [stream.busy]);++ // The app behind can't be reached while the stage is up+ useEffect(() => {+ const root = document.getElementById('root');+ if (!root || root.hasAttribute('inert')) return;+ root.setAttribute('inert', '');+ return () => root.removeAttribute('inert');+ }, []);++ const focusOut = controlling && !pageFocused && !popupOpen;+ const outline = controlling ? (focusOut ? 'rgb(124 196 255 / 0.45)' : '#7cc4ff') : 'rgb(255 255 255 / 0.14)';+ const hintId = useId();++ const coarse = '[@media(pointer:coarse)]:h-11';+ const navButton = `shrink-0 inline-flex items-center justify-center w-8 h-8 [@media(pointer:coarse)]:w-11 ${coarse} rounded-lg text-zinc-200 hover:bg-white/[0.06] aria-disabled:text-[#5a5383] aria-disabled:hover:bg-transparent aria-disabled:cursor-default focus:outline-none focus-visible:ring-2 focus-visible:ring-[#b8adff]`;+ const actionButton = `shrink-0 inline-flex items-center gap-1.5 h-8 ${coarse} px-3 rounded-[10px] text-[13px] font-semibold disabled:opacity-60`;++ const who = (+ <div className="shrink-0 w-[248px] max-w-[50vw] min-w-0 flex items-center gap-2.5" data-stage-who>+ <span className="relative shrink-0 w-7 h-7">+ <ModernAvatar role={avatarRole || botName} name={botName} size={28} />+ {controlling && (+ // The bot waits: its Thinking dots, held still+ <span aria-hidden="true" className="absolute -top-1 -right-1.5 flex gap-[2px] px-[3px] py-[2px] rounded-full bg-[#0e0a21] border border-white/[0.14]">+ {[0, 1, 2].map((i) => (+ <span key={i} className="w-[3px] h-[3px] rounded-full bg-zinc-100" />+ ))}+ </span>+ )}+ </span>+ <div className="min-w-0">+ <div className="text-sm leading-[18px] font-semibold text-zinc-100 truncate">{botName}</div>+ <div className="flex items-center gap-1.5 text-xs leading-4 whitespace-nowrap min-w-0" role="status" aria-live="polite">+ {controlling ? (+ <>+ <span className="shrink-0 w-2 h-2 rounded-full bg-control" aria-hidden="true" />+ <span className="shrink-0 font-semibold text-control">You’re in control</span>+ <span className="min-w-0 truncate text-[#a39dcc]">· @{botName} waits</span>+ </>+ ) : (+ <>+ <Loader2 size={12} className="shrink-0 text-[#9d8fff] animate-spin motion-reduce:animate-none" aria-hidden="true" />+ <span className="text-[#a39dcc]">Taking control…</span>+ </>+ )}+ </div>+ </div>+ </div>+ );++ const nav = showHistory && (+ <div className="shrink-0 flex items-center gap-1" data-stage-nav>+ {(+ [+ ['back', 'Back', <ArrowLeft key="b" size={16} aria-hidden="true" />],+ ['forward', 'Forward', <ArrowRight key="f" size={16} aria-hidden="true" />],+ ['reload', 'Reload', <RotateCw key="r" size={16} aria-hidden="true" />],+ ] as const+ ).map(([dir, label, icon]) => (+ <button+ key={dir}+ type="button"+ className={navButton}+ onClick={() => controlling && history(dir)}+ aria-disabled={!controlling || undefined}+ aria-label={label}+ title={label}+ >+ {icon}+ </button>+ ))}+ </div>+ );++ const urlField = (+ <div+ className={`relative flex-1 min-w-0 ${wide ? 'max-w-[760px]' : ''} h-9 [@media(pointer:coarse)]:h-10 flex items-center gap-2 px-3 rounded-[10px] bg-[#120e26] border border-white/[0.14] focus-within:border-transparent focus-within:ring-2 focus-within:ring-[#b8adff]`}+ data-stage-url+ >+ {address.secure ? <Lock size={13} className="shrink-0 text-[#8d87b8]" aria-hidden="true" /> : <Globe size={13} className="shrink-0 text-[#8d87b8]" aria-hidden="true" />}+ <div className="relative flex-1 min-w-0 h-full">+ <input+ ref={urlRef}+ type="text"+ value={url}+ aria-label="Address"+ title={pageTitle || pageUrl}+ spellCheck={false}+ autoCapitalize="off"+ autoCorrect="off"+ onFocus={(e) => {+ setUrlEditing(true);+ e.currentTarget.select();+ }}+ onBlur={() => setUrlEditing(false)}+ onChange={(e) => setUrl(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ navigate(url);+ } else if (e.key === 'Escape') {+ e.preventDefault();+ e.stopPropagation();+ setUrl(pageUrl);+ focusPage();+ }+ }}+ className={`absolute inset-0 w-full bg-transparent font-mono text-[13px] focus:outline-none ${urlEditing ? 'text-zinc-100' : 'text-transparent'}`}+ />+ {!urlEditing && (+ <span aria-hidden="true" className="absolute inset-0 flex items-center font-mono text-[13px] whitespace-nowrap overflow-hidden pointer-events-none">+ <span className="shrink-0 text-zinc-100">{address.host}</span>+ <span className="min-w-0 truncate text-[#8d87b8]">{address.rest}</span>+ </span>+ )}+ </div>+ </div>+ );++ const actions = (+ <div className="shrink-0 ml-auto flex items-center gap-2" data-stage-actions>+ <button ref={actionRef} type="button" onClick={onHandBack} className={`${actionButton} ${step ? GHOST_BUTTON : PRIMARY_BUTTON}`} data-primary={!step || undefined}>+ <Hand size={15} aria-hidden="true" /> Hand back+ </button>+ {step && (+ <button type="button" onClick={answerStep} disabled={stepBusy} className={`${actionButton} ${PRIMARY_BUTTON}`} data-primary>+ {stepBusy ? <Loader2 size={15} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Check size={15} aria-hidden="true" />}+ {step.doneLabel}+ </button>+ )}+ </div>+ );++ return createPortal(+ <div className={`fixed inset-0 z-[70] flex bg-[rgb(5_3_15/0.72)] kw-scrim-in ${wide ? 'p-4' : ''}`} data-browser-takeover>+ <div+ role="dialog"+ aria-modal="true"+ aria-label={`${botName}'s browser, you're in control`}+ aria-describedby={hintId}+ data-escape-layer+ data-control-outline={focusOut ? 'dim' : controlling ? 'on' : 'off'}+ className={`relative flex-1 min-w-0 flex flex-col overflow-hidden bg-[#0a0719] text-zinc-100 kw-stage-in ${wide ? 'rounded-[16px]' : ''}`}+ style={wide ? { boxShadow: `0 0 0 2px ${outline}, 0 24px 80px rgb(0 0 0 / 0.6)` } : undefined}+ onKeyDown={(e) => {+ // Keys in the top bar stay in the top bar; F6 and Escape go back to the page+ e.stopPropagation();+ if (e.key === 'F6' || e.key === 'Escape') {+ e.preventDefault();+ focusPage();+ }+ }}+ >+ <p id={hintId} className="sr-only">+ Press F6 to reach Hand back.+ </p>+ <div+ className={`shrink-0 bg-[#0e0a21] border-b border-white/[0.07] ${wide ? 'h-14 pl-[14px] pr-3 flex items-center gap-3' : 'px-3 py-2 flex flex-col gap-2'}`}+ data-stage-bar+ >+ {wide ? (+ <>+ {who}+ {nav}+ {urlField}+ {actions}+ </>+ ) : (+ <>+ <div className="flex items-center gap-3 min-w-0">+ {who}+ {actions}+ </div>+ <div className="flex items-center gap-2 min-w-0">+ {nav}+ {urlField}+ </div>+ </>+ )}+ </div>++ {notice && !error && !stepError && (+ <div+ role="status"+ aria-live="polite"+ className={`shrink-0 px-3 py-1.5 text-xs border-b ${+ notice.tone === 'success' ? 'border-[rgb(94_234_212/0.2)] bg-[rgb(94_234_212/0.08)] text-[#5eead4]' : 'border-[rgb(252_211_77/0.2)] bg-[rgb(252_211_77/0.08)] text-[#fcd34d]'+ }`}+ >+ {notice.text}+ </div>+ )}+ {(error || stepError) && (+ <div role="alert" className="shrink-0 px-3 py-1.5 flex items-center gap-2 text-xs border-b border-rose-500/20 bg-rose-950/40 text-rose-200">+ <span className="flex-1">{stepError || error}</span>+ {!controlling && error === BOT_BUSY_TEXT && (+ <button type="button" onClick={onRetryControl} className={`px-2 h-7 rounded-md text-xs ${PRIMARY_BUTTON}`}>+ Try again+ </button>+ )}+ </div>+ )}++ <div+ ref={stageRef}+ data-browser-stage+ className="relative flex-1 min-h-0 overflow-hidden bg-[#0a0719] select-none"+ style={{ touchAction: 'none', cursor: controlling ? stream.cursor || 'default' : 'progress' }}+ onPointerDown={(e) => {+ if (e.pointerType !== 'touch' || popupOpen) return;+ lastTouch.current = e.timeStamp;+ focusPage();+ if (!controlling) {+ onRetryControl();+ return;+ }+ e.currentTarget.setPointerCapture?.(e.pointerId);+ tracker.down(e.pointerId, { x: e.clientX, y: e.clientY }, e.isPrimary);+ }}+ onPointerMove={(e) => {+ if (e.pointerType !== 'touch') return;+ lastTouch.current = e.timeStamp;+ tracker.move(e.pointerId, { x: e.clientX, y: e.clientY });+ }}+ onPointerUp={(e) => {+ if (e.pointerType !== 'touch') return;+ lastTouch.current = e.timeStamp;+ tracker.up(e.pointerId, { x: e.clientX, y: e.clientY });+ }}+ onPointerCancel={(e) => e.pointerType === 'touch' && tracker.cancel(e.pointerId)}+ >+ {image ? (+ <img+ ref={imgRef}+ src={image}+ alt={`${botName}'s page: ${domain}`}+ draggable={false}+ onLoad={onFrameLoaded}+ onError={onFrameLoaded}+ data-browser-page+ className="absolute max-w-none pointer-events-none"+ style={{ left: layout.left, top: layout.top, width: layout.width, height: layout.height }}+ />+ ) : (+ <div className="absolute inset-0 flex items-center justify-center text-[#a39dcc]">+ <Loader2 size={20} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />+ <span className="sr-only">Waiting for the browser</span>+ </div>+ )}++ {focusOut && (+ <>+ <div className="absolute inset-0 bg-[rgb(10_7_25/0.18)] pointer-events-none" aria-hidden="true" />+ <div+ className="absolute top-3 left-1/2 -translate-x-1/2 h-7 px-3 inline-flex items-center gap-1.5 rounded-full bg-[rgb(14_10_33/0.92)] border border-white/[0.14] text-xs text-zinc-100 whitespace-nowrap pointer-events-none"+ data-focus-hint+ >+ <Keyboard size={13} aria-hidden="true" /> Click the page to type into it+ </div>+ </>+ )}++ {relaying && (+ <div className="absolute top-3 right-3 h-6 px-2.5 inline-flex items-center gap-1.5 rounded-full bg-[rgb(14_10_33/0.9)] border border-white/[0.14] text-xs text-zinc-200 pointer-events-none" data-relaying>+ <Loader2 size={12} className="text-[#9d8fff] animate-spin motion-reduce:animate-none" aria-hidden="true" />+ Relaying…+ </div>+ )}++ {!controlling && (+ <div className="absolute inset-0 flex items-center justify-center pointer-events-none">+ <span className="inline-flex items-center gap-2 px-4 h-10 rounded-full bg-[rgb(14_10_33/0.92)] border border-white/[0.14] text-sm">+ {error === BOT_BUSY_TEXT ? (+ <>+ <MousePointerClick size={15} aria-hidden="true" /> Click to try again+ </>+ ) : (+ <>+ <Loader2 size={15} className="text-[#9d8fff] animate-spin motion-reduce:animate-none" aria-hidden="true" /> Taking control…+ </>+ )}+ </span>+ </div>+ )}++ {stream.select && controlling && (+ <SelectPopover+ key={JSON.stringify(stream.select.rect)}+ request={stream.select}+ anchor={anchor}+ stage={stage}+ onPick={(indexes) => {+ send(stream.select!.multiple ? { action: 'select_option', indexes } : { action: 'select_option', index: indexes[0] }, true);+ stream.clearSelect();+ focusPage();+ }}+ onClose={() => {+ stream.clearSelect();+ focusPage();+ }}+ />+ )}+ {stream.dialog && (+ <PageDialogModal+ key={`${stream.dialog.kind}:${stream.dialog.message}`}+ dialog={stream.dialog}+ host={domain}+ onAnswer={(accept, text) => {+ send(text !== undefined ? { action: 'dialog', accept, prompt_text: text } : { action: 'dialog', accept }, true);+ stream.clearDialog();+ focusPage();+ }}+ />+ )}++ <textarea+ ref={sinkRef}+ aria-label={`Type into ${domain}. F6 moves to Hand back.`}+ aria-keyshortcuts="F6"+ autoCapitalize="off"+ autoCorrect="off"+ autoComplete="off"+ spellCheck={false}+ data-browser-keys+ className="absolute left-0 top-0 w-px h-px p-0 border-0 opacity-0 resize-none overflow-hidden"+ style={{ caretColor: 'transparent' }}+ tabIndex={0}+ />+ </div>+ {!wide && <div aria-hidden="true" className="absolute inset-0 pointer-events-none z-[60]" style={{ boxShadow: `inset 0 0 0 2px ${outline}` }} />}+ </div>+ </div>,+ document.body+ );+};diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex 8df9ea3b..11d3fa71 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -200,6 +200,10 @@ export interface ChatViewProps {vmApprovalsOff?: boolean;/** The CAPTCHA the open bot's browser waits on, and a counter that opens it to solve. */vmCaptchaStep?: HumanStep | null;+ /** The newest open step (any kind) holding this browser. */+ vmHumanStep?: HumanStep | null;+ /** Answers that step as done from the browser; resolves to an error message on failure. */+ onVmStepDone?: (id: string) => Promise<string | void> | void;vmSolveRequest?: number;/** Pinned team/channel instructions, shown collapsed above the messages. */pinned?: PinnedItem[];@@ -412,6 +416,8 @@ export const ChatView: React.FC<ChatViewProps> = ({onNavigateVm,vmApprovalsOff,vmCaptchaStep,+ vmHumanStep,+ onVmStepDone,vmSolveRequest,pinned = [],onEditInstructions,@@ -1775,6 +1781,8 @@ export const ChatView: React.FC<ChatViewProps> = ({onNavigate={onNavigateVm}approvalsOff={vmApprovalsOff}captchaStep={vmCaptchaStep}+ humanStep={vmHumanStep}+ onStepDone={onVmStepDone}solveRequest={vmSolveRequest}/></div>diff --git a/frontend/src/components/HumanStepCard.tsx b/frontend/src/components/HumanStepCard.tsxindex 3012d614..cb3a1476 100644--- a/frontend/src/components/HumanStepCard.tsx+++ b/frontend/src/components/HumanStepCard.tsx@@ -126,10 +126,10 @@ export const HumanStepCard: React.FC<HumanStepCardProps> = ({ meta, messageId, k{onOpenBrowser && !captcha && (<buttontype="button"- onClick={() => onOpenBrowser(view.sandbox_target)}- className={`inline-flex items-center justify-center gap-1.5 min-h-[40px] sm:min-h-[34px] px-3 py-1.5 rounded-xl text-sm border bg-zinc-800/80 border-zinc-700 text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600 ${focusRing}`}+ onClick={() => onOpenBrowser(view.sandbox_target, true)}+ className={`inline-flex items-center justify-center gap-2 min-h-[48px] sm:min-h-[38px] px-4 py-2 rounded-xl text-base sm:text-sm font-semibold bg-amber-400 text-zinc-950 hover:bg-amber-300 ${focusRing}`}>- <MonitorPlay size={14} aria-hidden="true" /> Open browser+ <MonitorPlay size={16} aria-hidden="true" /> Open browser</button>)}<button@@ -137,7 +137,7 @@ export const HumanStepCard: React.FC<HumanStepCardProps> = ({ meta, messageId, konClick={() => answer('done')}disabled={busy !== null}className={`inline-flex items-center justify-center gap-1.5 min-h-[40px] sm:min-h-[34px] px-3 py-1.5 rounded-xl text-sm disabled:opacity-60 ${focusRing} ${- captcha && onOpenBrowser+ onOpenBrowser? 'border bg-zinc-800/80 border-zinc-700 text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600': 'font-semibold bg-amber-400 text-zinc-950 hover:bg-amber-300'}`}@@ -163,7 +163,7 @@ export const HumanStepCard: React.FC<HumanStepCardProps> = ({ meta, messageId, k{open && captcha && (<p className="basis-full text-zinc-400">Solve the puzzle and {kwantName} continues by itself. Nothing you do there is passed to {kwantName}.</p>)}- {open && !captcha && <p className="basis-full text-zinc-400">Do it in the browser panel, then press Done. What you type into fields there isn’t passed to {kwantName}.</p>}+ {open && !captcha && <p className="basis-full text-zinc-400">Open the browser and do it there, then press Done. What you type into fields there isn’t passed to {kwantName}.</p>}{error && (<span role="alert" className="basis-full text-rose-300">{error}diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsxindex 5a57f6ad..535f8b55 100644--- a/frontend/src/components/VirtualMachinePane.tsx+++ b/frontend/src/components/VirtualMachinePane.tsx@@ -8,26 +8,45 @@ import {Cpu,Key,MousePointerClick,- Keyboard,Loader2,Laptop,Puzzle,CheckCircle2,+ Eye,+ Hand,} from 'lucide-react';import { playSfx } from '../audio/chiptune';-import { mapBrowserPoint } from '../browserViewport';-import { useBrowserStream } from '../useBrowserStream';+import { BOT_BUSY_TEXT, useBrowserStream } from '../useBrowserStream';import { ComputerModeChip, ComputerModeError, LocalBrowserNote, OpenWindowButton, useComputerMode } from './ComputerModeSwitch';import { browserFooterLabel, isBlankPage, showsLocalWindow } from '../computerMode';import { loginMatchesPage } from '../savedPasswords';import { PendingLoginPrompt, SavedPasswordsPanel, useSavedPasswords } from './SavedPasswordsPanel';import { usePasswordStore } from './PasswordStorePanel';-import { BrowserControlOverlay, sendPageInput } from './BrowserControlOverlay';-import { PAGE_H, PAGE_W, PageInput, Pt, createGestureTracker, stageToPage, stageToPageClamped } from '../browserGestures';-import { HumanStep } from '../humanSteps';+import { BrowserControlOverlay } from './BrowserControlOverlay';+import { BrowserTakeoverStage } from './BrowserTakeoverStage';+import { HumanStep, HumanStepKind } from '../humanSteps';const PHONE_QUERY = '(max-width: 639px)';+/** While the bot finishes a step, taking over is retried this often, for this long (no backend change). */+export const TAKEOVER_RETRY_MS = 1000;+export const TAKEOVER_RETRY_FOR_MS = 10_000;++/** "@Bot needs you …" for a step holding this browser (Mira's spec §3 C). */+export const STEP_NEED: Record<HumanStepKind, string> = {+ sign_in: 'needs you to sign in',+ two_factor: 'needs you to enter a code',+ captcha: 'needs you to solve a puzzle',+ other: 'needs you in the browser',+};++/** The stage's primary "Done" for each kind (captcha keeps its auto-continue, so it has none). */+export const STEP_DONE: Record<Exclude<HumanStepKind, 'captcha'>, string> = {+ sign_in: 'Done, I’m signed in',+ two_factor: 'Done, I’m in',+ other: 'Done',+};+/** Below 640px taking control opens the page full screen. */function useNarrow(): boolean {const [narrow, setNarrow] = useState(() => typeof window !== 'undefined' && !!window.matchMedia?.(PHONE_QUERY).matches);@@ -67,6 +86,10 @@ export interface VirtualMachinePaneProps {captchaStep?: HumanStep | null;/** Goes up each time the person asks to solve it: take control and, on a phone, go full screen. */solveRequest?: number;+ /** An open sign-in, code or other step this browser is held for: the stage offers its Done. */+ humanStep?: HumanStep | null;+ /** Answers that step as done; resolves to an error message on failure. */+ onStepDone?: (id: string) => Promise<string | void> | void;}type PaneTab = 'browser' | 'terminal' | 'vault';@@ -104,6 +127,8 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({approvalsOff = false,captchaStep = null,solveRequest = 0,+ humanStep = null,+ onStepDone,}) => {const [activeTab, setActiveTab] = useState<PaneTab>(() => chosenPaneTab(teamId));useEffect(() => rememberPaneTab(teamId, activeTab), [teamId, activeTab]);@@ -124,14 +149,12 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({const stream = useBrowserStream(teamId, isOpen && activeTab === 'browser' && !isWindow && !computer.windowPending);const isControlMode = stream.controlling;const isInteracting = stream.busy;- const [quickTypeText, setQuickTypeText] = useState('');- const [clickRipples, setClickRipples] = useState<Array<{ id: number; x: number; y: number }>>([]);- const lastWheelTimeRef = useRef<number>(0);- const imageRef = useRef<HTMLImageElement>(null);- const viewportRef = useRef<HTMLDivElement>(null);const narrow = useNarrow();+ // Wanted open (asked for, control on its way) or in control: the page takes over the screenconst [fullScreen, setFullScreen] = useState(false);- const showFullScreen = fullScreen && narrow && activeTab === 'browser' && !isWindow;+ const takeover = (fullScreen || isControlMode) && activeTab === 'browser' && !isWindow && isOpen;+ const showFullScreen = takeover && narrow;+ const showStage = takeover && !narrow;const captchaOpen = captchaStep?.status === 'open';// Shown for a moment after the CAPTCHA closes by itself, before control goes back to the botconst [solvedNote, setSolvedNote] = useState(false);@@ -139,6 +162,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({// Once the stream reports where the tab is, trust it; before that, the last URL the app heard of.const pageUrl = stream.location ? stream.location.url : activeUrl;const currentScreenshot = isBlankPage(pageUrl) ? null : stream.frame?.image || screenshotBase64;+ const frameSrc = currentScreenshot ? (currentScreenshot.startsWith('data:') ? currentScreenshot : `data:image/jpeg;base64,${currentScreenshot}`) : null;// A hidden frame never loads, so acknowledge it here or the stream stalls waiting for the ack.const blankFrameId = isBlankPage(pageUrl) ? stream.frame?.id : undefined;const { acknowledgeFrame } = stream;@@ -197,111 +221,64 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({const handBack = () => {playSfx('click');+ setWaitBot(null);setFullScreen(false);+ setWantsControl(false);if (isControlMode) send({ action: 'release_control' });};- // Mouse or finger in the side panel: a click clicks, a drag presses, moves and releases (sliders)- const lastDownRef = useRef<{ x: number; y: number } | null>(null);- const pageFromClient = useCallback((p: Pt, clamp: boolean) => {- const img = imageRef.current;- if (!img) return clamp ? { x: 0, y: 0 } : null;- const rect = img.getBoundingClientRect();- const page = { width: img.naturalWidth || PAGE_W, height: img.naturalHeight || PAGE_H };- const scale = Math.min(rect.width / page.width, rect.height / page.height);- const view = { scale, tx: (rect.width - page.width * scale) / 2, ty: (rect.height - page.height * scale) / 2 };- const x = p.x - rect.left;- const y = p.y - rect.top;- return clamp ? stageToPageClamped(x, y, view, page) : stageToPage(x, y, view, page);- }, []);- const sendRef = useRef(stream.send);- sendRef.current = stream.send;- const tracker = useMemo(- () =>- createGestureTracker({- toPage: (p) => pageFromClient(p, false),- toPageClamped: (p) => pageFromClient(p, true) as Pt,- send: (input: PageInput) => {- if (input.action === 'click') {- playSfx('click');- const frame = viewportRef.current?.getBoundingClientRect();- const at = lastDownRef.current;- if (frame && at) {- const rippleId = Date.now();- setClickRipples((prev) => [...prev, { id: rippleId, x: at.x - frame.left, y: at.y - frame.top }]);- setTimeout(() => setClickRipples((prev) => prev.filter((r) => r.id !== rippleId)), 600);- }- }- sendPageInput(sendRef.current, input);- },- now: () => performance.now(),- later: (fn, ms) => {- const t = window.setTimeout(fn, ms);- return () => window.clearTimeout(t);- },- }),- [pageFromClient]- );-- const loginsOnThisPage = useMemo(() => passwords.logins.filter((l) => loginMatchesPage(l, pageUrl)).length, [passwords.logins, pageUrl]);-- // Dispatch interactive action to backend- const sendInteraction = useCallback(- (payload: {- action: 'click' | 'type' | 'key' | 'scroll';- x?: number;- y?: number;- text?: string;- key?: string;- code?: string;- delta_x?: number;- delta_y?: number;- }) => {- stream.send({ ...payload, delta_x: payload.delta_x || 0, delta_y: payload.delta_y || 0 }, true);- },- [stream.send]- );-- // Viewport Wheel / Scroll Handler- const handleViewportWheel = (e: React.WheelEvent<HTMLDivElement>) => {- if (!isControlMode || !imageRef.current) return;- const now = Date.now();- if (now - lastWheelTimeRef.current < 120) return;- lastWheelTimeRef.current = now;-- const img = imageRef.current;- const rect = img.getBoundingClientRect();- const point = mapBrowserPoint(e.clientX, e.clientY, rect, img.naturalWidth, img.naturalHeight);- if (!point) return;-- sendInteraction({ action: 'scroll', ...point, delta_x: e.deltaX, delta_y: e.deltaY });- };+ // Take the browser now (a click on the watch view, Take over, or Try again)+ const takeOver = useCallback(() => {+ playSfx('click');+ setWaitBot(null);+ setActiveTab('browser');+ setFullScreen(true);+ if (connected) send({ action: 'take_control' });+ else setWantsControl(true);+ }, [connected, send]);- // Viewport Keydown Handler- const handleViewportKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {- if (!isControlMode) return;- const targetTag = (e.target as HTMLElement)?.tagName?.toLowerCase();- if (targetTag === 'input' || targetTag === 'textarea') return;-- if (['Enter', 'Backspace', 'Tab', 'Escape', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {- e.preventDefault();- playSfx('blip');- sendInteraction({ action: 'key', key: e.key, code: e.code });- } else if (e.key.length === 1 && !e.metaKey && !e.ctrlKey) {- e.preventDefault();- playSfx('blip');- sendInteraction({ action: 'type', text: e.key });+ // The server let go (timeout, the bot's turn ended it, another tab): the stage closes with it+ const wasControlling = useRef(false);+ useEffect(() => {+ if (wasControlling.current && !controlling) setFullScreen(false);+ wasControlling.current = controlling;+ }, [controlling]);++ // Opening a sign-in or code step's browser takes control the same way Solve it does+ const stepForStage = humanStep && humanStep.status === 'open' && humanStep.kind !== 'captcha' && onStepDone+ ? { doneLabel: STEP_DONE[humanStep.kind], need: STEP_NEED[humanStep.kind], onDone: () => onStepDone(humanStep.id) }+ : null;+ // Any open step holding this browser, the CAPTCHA included: the watch view says so without a hover+ const needsYou = humanStep?.status === 'open' ? STEP_NEED[humanStep.kind] : captchaOpen ? STEP_NEED.captcha : null;++ // The bot is finishing a step: keep asking every second for ten seconds, then offer Try again+ const [waitBot, setWaitBot] = useState<{ since: number; gaveUp: boolean } | null>(null);+ const botBusy = stream.error === BOT_BUSY_TEXT;+ useEffect(() => {+ if (controlling) {+ setWaitBot(null);+ return;}- };+ if (!botBusy) return;+ if (!narrow) setFullScreen(false);+ setWaitBot((w) => w ?? { since: Date.now(), gaveUp: false });+ }, [botBusy, controlling, narrow]);+ useEffect(() => {+ if (!waitBot || waitBot.gaveUp || !botBusy) return;+ if (Date.now() - waitBot.since >= TAKEOVER_RETRY_FOR_MS) {+ setWaitBot({ ...waitBot, gaveUp: true });+ return;+ }+ const t = window.setTimeout(() => send({ action: 'take_control' }), TAKEOVER_RETRY_MS);+ return () => window.clearTimeout(t);+ }, [waitBot, botBusy, send]);+ const waitingForBot = !!waitBot && !waitBot.gaveUp;- // Quick Type Submit- const handleQuickTypeSubmit = (e: React.FormEvent) => {- e.preventDefault();- if (!quickTypeText.trim()) return;- playSfx('coin');- sendInteraction({ action: 'type', text: quickTypeText });- setQuickTypeText('');- };+ // The frame the side pane shows is acknowledged once drawn; one image, its source swapped+ const paneFrameId = useRef<number | null>(null);+ paneFrameId.current = stream.frame?.id ?? null;++ const loginsOnThisPage = useMemo(() => passwords.logins.filter((l) => loginMatchesPage(l, pageUrl)).length, [passwords.logins, pageUrl]);if (!isOpen) return null;@@ -321,26 +298,20 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({<ComputerModeChip api={computer} /><OpenWindowButton api={computer} />- {/* Interactive Control Toggle */}+ {/* Take over: always there while a browser exists, so keyboard users have a way in */}{!isWindow && (<buttontype="button"- onClick={() => {- playSfx('click');- stream.send({ action: isControlMode ? 'release_control' : 'take_control' });- if (!isControlMode) setActiveTab('browser');- setFullScreen(!isControlMode);- }}- disabled={!stream.connected}- title={isControlMode ? 'Exit Control Mode' : 'Take Control of Bot Browser'}- className={`p-1.5 rounded-md transition-colors cursor-pointer flex items-center gap-1 ${- isControlMode- ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/40 shadow-sm shadow-cyan-500/20 animate-pulse'- : 'text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800'+ onClick={() => (isControlMode ? handBack() : takeOver())}+ disabled={!stream.connected || waitingForBot}+ title={isControlMode ? 'Hand the browser back to the bot' : `Take over @${teamName}'s browser`}+ data-takeover-button+ className={`h-[30px] px-2.5 rounded-[10px] inline-flex items-center gap-1.5 text-[13px] font-semibold whitespace-nowrap cursor-pointer disabled:cursor-not-allowed disabled:opacity-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300 ${+ isControlMode ? 'border border-[#3f3868] bg-[rgb(44_37_82/0.8)] text-zinc-100' : 'bg-control text-control-ink hover:brightness-110'}`}>- <MousePointerClick size={13} className={isControlMode ? 'text-cyan-400' : ''} />- <span className="text-[10px] font-semibold whitespace-nowrap">{isControlMode ? 'Controlling' : 'Take Control'}</span>+ {isControlMode ? <Hand size={14} aria-hidden="true" /> : <MousePointerClick size={14} aria-hidden="true" />}+ {isControlMode ? 'Hand back' : 'Take over'}</button>)}@@ -524,41 +495,6 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({</div>)}- {/* Interactive Control Mode Banner */}- {isControlMode && (- <div className="flex items-center justify-between px-2.5 py-1 rounded-lg bg-cyan-950/60 border border-cyan-500/30 text-[11px] text-cyan-300 animate-in fade-in duration-150">- <div className="flex items-center gap-1.5">- <span className="w-1.5 h-1.5 rounded-full bg-cyan-400 animate-ping" />- <span className="font-medium">Direct Control Active</span>- </div>- <span className="text-[10px] text-cyan-400/80">Click & type on screen</span>- </div>- )}-- {/* Quick Type Input Bar (When in Control Mode) */}- {isControlMode && (- <form- onSubmit={handleQuickTypeSubmit}- className="hidden sm:flex items-center gap-1.5 p-1 bg-zinc-900 border border-cyan-500/40 rounded-lg text-xs"- >- <Keyboard size={12} className="text-cyan-400 flex-shrink-0 ml-1" />- <input- type="text"- value={quickTypeText}- onChange={(e) => setQuickTypeText(e.target.value)}- placeholder="Type into focused field (e.g. search, input)..."- className="flex-1 bg-transparent text-zinc-100 text-[11px] font-mono focus:outline-none"- />- <button- type="submit"- disabled={!quickTypeText.trim()}- className="px-2 py-0.5 rounded bg-cyan-500 hover:bg-cyan-400 text-zinc-950 font-semibold text-[10px] cursor-pointer disabled:opacity-40"- >- Send- </button>- </form>- )}-{(captchaOpen || solvedNote) && (<divrole="status"@@ -585,74 +521,119 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({</div>)}- {/* Viewport Frame */}- {controlError && (+ {/* D: the bot is finishing a step; taking over follows as soon as it's done */}+ {waitBot && !isControlMode && (+ <div role="status" aria-live="polite" data-takeover-wait className="flex items-start gap-2.5 px-3 py-2.5 rounded-xl border border-[rgb(157_143_255/0.35)] bg-[#1a1538]">+ {waitBot.gaveUp ? (+ <Hand size={16} className="shrink-0 mt-0.5 text-[#9d8fff]" aria-hidden="true" />+ ) : (+ <Loader2 size={16} className="shrink-0 mt-0.5 text-[#9d8fff] animate-spin motion-reduce:animate-none" aria-hidden="true" />+ )}+ <div className="flex-1 min-w-0">+ {waitBot.gaveUp ? (+ <p className="text-[13px] leading-[18px] text-zinc-100">@{teamName} is finishing a step, try again in a moment.</p>+ ) : (+ <>+ <p className="text-[13px] leading-[18px] text-zinc-100">+ <span className="font-semibold">@{teamName} is finishing a step.</span> Taking over as soon as it’s done.+ </p>+ <p className="mt-0.5 text-xs text-[#a39dcc]">Trying every second for 10 seconds.</p>+ </>+ )}+ </div>+ <button+ type="button"+ onClick={() => {+ setWaitBot(null);+ stream.clearError();+ }}+ aria-label="Close"+ className="shrink-0 -mr-1 -mt-0.5 w-6 h-6 inline-flex items-center justify-center rounded-md text-[#a39dcc] hover:text-zinc-100 hover:bg-white/[0.06]"+ >+ <X size={14} aria-hidden="true" />+ </button>+ </div>+ )}++ {controlError && !botBusy && (<div role="alert" className="px-2.5 py-2 rounded-lg border border-red-500/30 bg-red-950/40 text-xs text-red-300">{controlError}</div>)}<div- ref={viewportRef}- tabIndex={0}- onKeyDown={handleViewportKeyDown}- onPointerDown={(e) => {- if (!isControlMode || (e.pointerType === 'mouse' && e.button !== 0)) return;- viewportRef.current?.focus({ preventScroll: true });- e.currentTarget.setPointerCapture?.(e.pointerId);- lastDownRef.current = { x: e.clientX, y: e.clientY };- tracker.down(e.pointerId, { x: e.clientX, y: e.clientY }, e.isPrimary);- }}- onPointerMove={(e) => {- if (isControlMode) tracker.move(e.pointerId, { x: e.clientX, y: e.clientY });- }}- onPointerUp={(e) => {- if (isControlMode) tracker.up(e.pointerId, { x: e.clientX, y: e.clientY });- }}- onPointerCancel={(e) => tracker.cancel(e.pointerId)}- onWheel={handleViewportWheel}- style={isControlMode ? { touchAction: 'none' } : undefined}- className={`flex-1 border rounded-xl bg-zinc-950 overflow-hidden flex items-center justify-center relative shadow-inner focus:outline-none ${- isControlMode- ? 'border-cyan-500/60 ring-2 ring-cyan-500/20 cursor-crosshair'- : 'border-zinc-800'- }`}+ data-browser-watch+ data-watch-state={takeover ? 'stage' : waitingForBot ? 'busy' : needsYou ? 'needs-you' : 'watching'}+ className="group relative w-full aspect-[16/10] shrink-0 border border-white/[0.07] rounded-xl bg-[#0a0719] overflow-hidden flex items-center justify-center">- {/* Relaying feedback pill */}- {isInteracting && (- <div className="absolute top-2 right-2 px-2 py-0.5 rounded-full bg-zinc-950/90 border border-cyan-500/40 text-cyan-300 text-[10px] font-mono flex items-center gap-1.5 z-20 shadow-md pointer-events-none">- <Loader2 size={10} className="animate-spin text-cyan-400" />- <span>Relaying...</span>+ {/* Relaying: a discrete action (a navigate from the address bar) */}+ {isInteracting && !takeover && (+ <div className="absolute top-2 right-2 h-6 px-2.5 rounded-full bg-[rgb(14_10_33/0.9)] border border-white/[0.14] text-zinc-200 text-xs flex items-center gap-1.5 z-20 pointer-events-none">+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none text-[#9d8fff]" aria-hidden="true" />+ <span>Relaying…</span></div>)}- {/* Click Ripple Animations */}- {clickRipples.map((r) => (- <span- key={r.id}- style={{ left: r.x, top: r.y }}- className="absolute w-5 h-5 -ml-2.5 -mt-2.5 rounded-full border-2 border-cyan-400 bg-cyan-400/30 animate-ping pointer-events-none z-30"- />- ))}-- {showFullScreen ? (- <p className="text-center p-6 text-zinc-500 text-xs">Showing full screen</p>- ) : currentScreenshot ? (- <img- key={stream.frame?.id}- ref={imageRef}- src={- currentScreenshot.startsWith('data:')- ? currentScreenshot- : `data:image/jpeg;base64,${currentScreenshot}`- }- alt="Browser Viewport"- onLoad={() => { if (stream.frame) stream.acknowledgeFrame(stream.frame.id); }}- onError={() => { if (stream.frame) stream.acknowledgeFrame(stream.frame.id); }}- draggable={false}- className="w-full h-full object-contain pointer-events-auto"- />+ {takeover ? (+ <div className="text-center p-6 text-[#a39dcc] text-xs space-y-2">+ <p>{showFullScreen ? 'Showing full screen' : isControlMode ? 'You’re in control in the large view' : 'Taking control…'}</p>+ <button type="button" onClick={handBack} className="px-2.5 h-8 rounded-[10px] border border-[#3f3868] bg-[rgb(44_37_82/0.8)] text-zinc-100 hover:bg-[#2c2552]">+ Hand back+ </button>+ </div>+ ) : frameSrc ? (+ <>+ <img+ src={frameSrc}+ alt={`${teamName}'s browser`}+ onLoad={() => { if (paneFrameId.current !== null) stream.acknowledgeFrame(paneFrameId.current); }}+ onError={() => { if (paneFrameId.current !== null) stream.acknowledgeFrame(paneFrameId.current); }}+ draggable={false}+ className="w-full h-full object-contain"+ />+ {!needsYou && !waitingForBot && !waitBot?.gaveUp && (+ <span className="absolute top-2 left-2 h-[22px] px-2 inline-flex items-center gap-1 rounded-full bg-[rgb(14_10_33/0.88)] text-[11px] text-zinc-200 pointer-events-none group-hover:opacity-0 group-focus-within:opacity-0 kw-veil-in">+ <Eye size={12} aria-hidden="true" /> Watching+ </span>+ )}+ {!isWindow && stream.connected && (+ /* B / C: one click anywhere on the page takes it over (that click isn't passed on) */+ <button+ type="button"+ onClick={waitingForBot ? undefined : takeOver}+ aria-disabled={waitingForBot || undefined}+ aria-label={waitingForBot ? `Waiting for ${teamName}` : `Take over ${teamName}'s browser`}+ className={`absolute inset-0 flex flex-col items-center justify-center gap-2 px-6 text-center focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-sky-300 rounded-xl kw-veil-in ${+ waitingForBot+ ? 'bg-[rgb(10_7_25/0.8)] cursor-default'+ : needsYou || waitBot?.gaveUp+ ? 'bg-[rgb(10_7_25/0.84)] cursor-pointer'+ : 'bg-[rgb(10_7_25/0.8)] opacity-0 hover:opacity-100 focus-visible:opacity-100 cursor-pointer'+ }`}+ >+ {needsYou && !waitingForBot && (+ <span className="inline-flex items-center gap-1.5 text-xs font-semibold text-[#fcd34d]">+ <Hand size={14} aria-hidden="true" /> @{teamName} {needsYou}+ </span>+ )}+ <span+ className={`inline-flex items-center gap-1.5 px-3.5 h-9 rounded-[10px] text-sm font-semibold ${+ waitingForBot ? 'bg-[#2c2552] text-[#a39dcc]' : 'bg-control text-control-ink'+ }`}+ >+ {waitingForBot ? (+ <>Waiting for @{teamName}…</>+ ) : (+ <>+ <MousePointerClick size={15} aria-hidden="true" /> {waitBot?.gaveUp ? 'Try again' : 'Take over'}+ </>+ )}+ </span>+ {!needsYou && !waitingForBot && !waitBot?.gaveUp && <span className="text-xs text-zinc-200">Click anywhere to take over. @{teamName} pauses.</span>}+ </button>+ )}+ </>) : (- <div className="text-center p-6 text-zinc-600 text-xs">+ <div className="text-center p-6 text-zinc-500 text-xs"><Globe size={32} className="mx-auto mb-2 opacity-40 text-zinc-500" /><p>{browserReady ? 'Browser idle' : 'Browser unavailable'}</p><p className="text-[10px] text-zinc-500 mt-1">{browserReady ? 'Enter a URL above to open a page' : isLocal ? 'Check that Chrome is installed, then use Restart Browser below' : 'Start Docker, then use Restart Browser below'}</p>@@ -713,9 +694,10 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({<BrowserControlOverlaybotName={teamName}pageUrl={pageUrl}- image={currentScreenshot ? (currentScreenshot.startsWith('data:') ? currentScreenshot : `data:image/jpeg;base64,${currentScreenshot}`) : null}+ image={frameSrc}+ page={stream.frame ? { width: stream.frame.width, height: stream.frame.height } : undefined}onFrameDone={() => {- if (stream.frame) stream.acknowledgeFrame(stream.frame.id);+ if (paneFrameId.current !== null) stream.acknowledgeFrame(paneFrameId.current);}}send={stream.send}busy={isInteracting}@@ -724,6 +706,29 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({captcha={captchaOpen ? { target: captchaStep?.target ?? null } : null}solved={solvedNote}onHandBack={handBack}+ stream={stream}+ step={stepForStage}+ />+ )}++ {showStage && (+ <BrowserTakeoverStage+ botName={teamName}+ pageUrl={pageUrl}+ pageTitle={stream.location?.title || pageTitle}+ stream={stream}+ image={frameSrc}+ step={stepForStage}+ notice={+ solvedNote+ ? { tone: 'success', text: `Solved, ${teamName} continues` }+ : captchaOpen+ ? { tone: 'warn', text: `Solve the puzzle, ${teamName} continues by itself` }+ : null+ }+ onNavigate={onNavigate}+ onHandBack={handBack}+ onRetryControl={takeOver}/>)}diff --git a/frontend/src/humanSteps.ts b/frontend/src/humanSteps.tsindex 47736e15..98326f82 100644--- a/frontend/src/humanSteps.ts+++ b/frontend/src/humanSteps.ts@@ -135,6 +135,14 @@ export function openStepsByKwant(map: Record<string, HumanStep>): Record<string,}/** The newest open step a bot raised, e.g. to open from a notification. */+/** The newest open step of any kind that holds this browser, for the stage's Done and the pane's "needs you". */+export function openStepFor(map: Record<string, HumanStep>, sandboxId: string | undefined): HumanStep | null {+ if (!sandboxId) return null;+ let best: HumanStep | null = null;+ for (const s of Object.values(map)) if (s.sandbox_target === sandboxId && s.status === 'open' && (!best || s.created_at > best.created_at)) best = s;+ return best;+}+export function latestOpenStep(map: Record<string, HumanStep>, kwantId: string): HumanStep | null {let best: HumanStep | null = null;for (const s of Object.values(map)) if (s.kwant_id === kwantId && s.status === 'open' && (!best || s.created_at > best.created_at)) best = s;diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.cssindex b705a2f2..609f8d3f 100644--- a/frontend/src/styles/modern.css+++ b/frontend/src/styles/modern.css@@ -497,3 +497,15 @@ a.kw-sticker:hover { transform: rotate(var(--kw-tilt)) scale(1.04); box-shadow:.kw-avatar-blink { display: none; }}+/* Browser takeover stage (Mira's spec §2, §4, §5): enters with a fade and a slight scale; nothing loops */+@keyframes kw-stage-in { from { opacity: 0; transform: scale(0.98); } to { opacity: 1; transform: none; } }+@keyframes kw-scrim-in { from { opacity: 0; } to { opacity: 1; } }+@keyframes kw-pop-in { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }+.kw-stage-in { animation: kw-stage-in 160ms cubic-bezier(0.2, 0.7, 0.2, 1) both; }+.kw-scrim-in { animation: kw-scrim-in 160ms cubic-bezier(0.2, 0.7, 0.2, 1) both; }+.kw-pop-in { animation: kw-pop-in 120ms cubic-bezier(0.2, 0.7, 0.2, 1) both; }+.kw-veil-in { transition: opacity 120ms cubic-bezier(0.2, 0.7, 0.2, 1); }+@media (prefers-reduced-motion: reduce) {+ .kw-stage-in, .kw-scrim-in, .kw-pop-in { animation: none; }+ .kw-veil-in { transition: none; }+}diff --git a/frontend/src/useBrowserStream.ts b/frontend/src/useBrowserStream.tsindex 37011c73..53d92a99 100644--- a/frontend/src/useBrowserStream.ts+++ b/frontend/src/useBrowserStream.ts@@ -1,19 +1,40 @@import { useCallback, useEffect, useRef, useState } from 'react';import { browserStreamUrl } from './browserViewport';+import { PageDialog, SelectRequest, Size, parseDialog, parseSelect, streamErrorText } from './browserInput';++export interface BrowserFrame {+ id: number;+ image: string;+ /** The page's viewport in CSS px (the image itself may be dpr times larger). */+ width: number;+ height: number;+}++/** Said when taking control fails because the bot is in the middle of something. */+export const BOT_BUSY_TEXT = 'The bot is finishing a step, try again in a moment.';export function useBrowserStream(id: string | undefined, visible: boolean) {const socket = useRef<WebSocket | null>(null);const sequence = useRef(0);const pending = useRef(new Set<number>());+ const takingControl = useRef(false);+ const lastImage = useRef<string | null>(null);const [connected, setConnected] = useState(false);const [controlling, setControlling] = useState(false);const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);- const [frame, setFrame] = useState<{ id: number; image: string } | null>(null);+ const [frame, setFrame] = useState<BrowserFrame | null>(null);const [location, setLocation] = useState<{ url: string; title: string } | null>(null);// After each tap: whether it focused a text field on the page (the phone keyboard follows it)const [tapFocus, setTapFocus] = useState<{ seq: number; editable: boolean } | null>(null);+ const [viewport, setViewport] = useState<Size | null>(null);+ const [select, setSelect] = useState<SelectRequest | null>(null);+ const [dialog, setDialog] = useState<PageDialog | null>(null);+ const [cursor, setCursor] = useState<string>('default');+ // Actions the server answered "Invalid browser input" for (an older server): hide their buttons+ const [unsupported, setUnsupported] = useState<ReadonlySet<string>>(new Set());+ const actionsById = useRef(new Map<number, string>());useEffect(() => {if (!id || id === 'default' || !visible) return;@@ -30,15 +51,53 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {};ws.onmessage = (event) => {if (disposed || socket.current !== ws) return;- const message = JSON.parse(event.data);+ let message: Record<string, any>;+ try { message = JSON.parse(event.data); } catch { return; }switch (message.type) {case 'ping': ws.send(JSON.stringify({ action: 'pong' })); break;- case 'frame': attempts = 0; setConnected(true); setFrame({ id: message.id, image: message.image }); break;+ case 'frame': {+ attempts = 0;+ setConnected(true);+ const width = Number(message.width) > 0 ? Number(message.width) : 1280;+ const height = Number(message.height) > 0 ? Number(message.height) : 800;+ // An identical picture leaves <img src> unchanged, so no load event comes to acknowledge it+ if (message.image === lastImage.current) ws.send(JSON.stringify({ action: 'frame_ack', id: message.id }));+ lastImage.current = message.image;+ setFrame({ id: message.id, image: message.image, width, height });+ break;+ }case 'location': setLocation({ url: message.url || '', title: message.title || '' }); break;- case 'control': setControlling(message.active); break;- case 'error': setError(message.error); pending.current.delete(message.id); setBusy(pending.current.size > 0); break;+ case 'control':+ takingControl.current = false;+ setControlling(!!message.active);+ if (message.viewport && message.viewport.width > 0) setViewport({ width: message.viewport.width, height: message.viewport.height });+ if (!message.active) { setSelect(null); setDialog(null); setCursor('default'); }+ break;+ case 'select': setSelect(parseSelect(message)); break;+ case 'dialog': setDialog(parseDialog(message)); break;+ case 'dialog_closed': setDialog(null); break;+ case 'cursor': if (typeof message.cursor === 'string') setCursor(message.cursor); break;+ case 'clipboard':+ if (typeof message.text === 'string' && message.text) navigator.clipboard?.writeText(message.text).catch(() => {});+ break;+ case 'error': {+ const action = typeof message.id === 'number' ? actionsById.current.get(message.id) : undefined;+ if (action && /invalid browser input/i.test(String(message.error))) {+ setUnsupported((s) => new Set(s).add(action));+ } else if (action === 'take_control' || (takingControl.current && message.id === undefined)) {+ takingControl.current = false;+ setError(BOT_BUSY_TEXT);+ } else {+ const text = streamErrorText(action, message.error);+ if (text) setError(text);+ }+ if (typeof message.id === 'number') { pending.current.delete(message.id); actionsById.current.delete(message.id); }+ setBusy(pending.current.size > 0);+ break;+ }case 'ack':pending.current.delete(message.id);+ actionsById.current.delete(message.id);setBusy(pending.current.size > 0);if (typeof message.editable === 'boolean') setTapFocus({ seq: message.id, editable: message.editable });break;@@ -48,10 +107,15 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {if (disposed || socket.current !== ws) return;socket.current = null;pending.current.clear();+ actionsById.current.clear();+ takingControl.current = false;setConnected(false);setControlling(false);setBusy(false);setFrame(null);+ lastImage.current = null;+ setSelect(null);+ setDialog(null);setError((current) => current || 'Browser disconnected. Reconnecting…');reconnect = setTimeout(connect, Math.min(1000 * 2 ** attempts++, 10000));};@@ -63,25 +127,39 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {socket.current?.close();socket.current = null;pending.current.clear();+ actionsById.current.clear();setConnected(false);setControlling(false);setBusy(false);setFrame(null);setLocation(null);setTapFocus(null);+ setSelect(null);+ setDialog(null);+ setViewport(null);};}, [id, visible]);- /** `input` waits for the page's ack (shows busy); pointer moves don't, they're fire-and-forget. */+ /**+ * `input` marks a discrete action that waits for the page's ack (and shows "Relaying…").+ * Moves, wheel steps and keys don't: they stream, and a stuck one must never block the rest.+ */const send = useCallback((payload: Record<string, unknown>, input = false) => {const ws = socket.current;if (!ws || ws.readyState !== WebSocket.OPEN) { setError('Browser is reconnecting. Try again when connected.'); return; }- if (ws.bufferedAmount > 64 * 1024 || pending.current.size >= 128) {+ if (input && (ws.bufferedAmount > 64 * 1024 || pending.current.size >= 128)) {setError('Browser input is busy. Wait for pending input to finish.'); return;}+ // A stream of moves on a slow link: drop moves, never presses, releases or keys+ if (!input && payload.action === 'mouse' && payload.type === 'move' && ws.bufferedAmount > 256 * 1024) return;const id = ++sequence.current;if (input) { pending.current.add(id); setBusy(true); }- setError(null);+ if (typeof payload.action === 'string') {+ actionsById.current.set(id, payload.action);+ if (actionsById.current.size > 512) actionsById.current.delete(actionsById.current.keys().next().value as number);+ if (payload.action === 'take_control') takingControl.current = true;+ }+ if (input || payload.action === 'take_control') setError(null);ws.send(JSON.stringify({ ...payload, id }));}, []);@@ -90,5 +168,14 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ action: 'frame_ack', id }));}, []);- return { connected, controlling, busy, error, frame, location, tapFocus, send, acknowledgeFrame };+ const clearSelect = useCallback(() => setSelect(null), []);+ const clearDialog = useCallback(() => setDialog(null), []);+ const clearError = useCallback(() => setError(null), []);++ return {+ connected, controlling, busy, error, frame, location, tapFocus, viewport, select, dialog, cursor, unsupported,+ send, acknowledgeFrame, clearSelect, clearDialog, clearError,+ };}++export type BrowserStream = ReturnType<typeof useBrowserStream>;diff --git a/frontend/tailwind.config.js b/frontend/tailwind.config.jsindex 786e5038..f39e6a64 100644--- a/frontend/tailwind.config.js+++ b/frontend/tailwind.config.js@@ -36,6 +36,11 @@ export default {900: '#3a2f7c',950: '#231b4d',},+ // "You have the wheel" in a bot's browser (Mira's stage spec §1): never sky-* (violet here), never amber+ control: {+ DEFAULT: '#7cc4ff',+ ink: '#071629',+ },brand: {50: '#f0f9ff',100: '#e0f2fe',diff --git a/frontend/tests/browserInput.test.mjs b/frontend/tests/browserInput.test.mjsnew file mode 100644index 00000000..497e154b--- /dev/null+++ b/frontend/tests/browserInput.test.mjs@@ -0,0 +1,196 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };++const b = await loadBundled(`export * from './src/browserInput';`);+const st = await loadBundled(`export { splitAddress, RELAYING_DELAY_MS } from './src/components/BrowserTakeoverStage';`);+const hs = await loadBundled(`export { openStepFor } from './src/humanSteps';`);+const vm = await loadBundled(`export { TAKEOVER_RETRY_MS, TAKEOVER_RETRY_FOR_MS, STEP_NEED, STEP_DONE } from './src/components/VirtualMachinePane';`);++const key = (over = {}) => ({ type: 'keydown', key: 'a', code: 'KeyA', altKey: false, ctrlKey: false, metaKey: false, shiftKey: false, ...over });++test('resizeFor asks for the stage size, clamped to the server limits', () => {+ assert.deepEqual(b.resizeFor({ width: 1280.7, height: 760.2 }, 2), { action: 'resize', width: 1280, height: 760, dpr: 2 });+ assert.deepEqual(b.resizeFor({ width: 200, height: 3000 }, 3), { action: 'resize', width: 360, height: 1200, dpr: 2 });+ assert.equal(b.resizeFor({ width: 0, height: 500 }), null);+});++test('stageLayout draws 1:1 when it fits and scales down when it does not', () => {+ assert.deepEqual(b.stageLayout({ width: 1000, height: 800 }, { width: 800, height: 600 }), { scale: 1, left: 100, top: 100, width: 800, height: 600 });+ const l = b.stageLayout({ width: 400, height: 600 }, { width: 800, height: 600 });+ assert.equal(l.scale, 0.5);+ assert.equal(l.top, 150);+});++test('pagePoint maps client points to page pixels, null outside unless clamped', () => {+ const drawn = { left: 100, top: 50, width: 400, height: 300 };+ const page = { width: 800, height: 600 };+ assert.deepEqual(b.pagePoint(300, 200, drawn, page), { x: 400, y: 300 });+ assert.deepEqual(b.pagePoint(100, 50, drawn, page), { x: 0, y: 0 });+ assert.equal(b.pagePoint(99, 60, drawn, page), null);+ assert.equal(b.pagePoint(500, 60, drawn, page), null);+ assert.deepEqual(b.pagePoint(900, -10, drawn, page, true), { x: 799, y: 0 });+});++test('mouse buttons and modifiers', () => {+ assert.equal(b.buttonName(0), 'left');+ assert.equal(b.buttonName(1), 'middle');+ assert.equal(b.buttonName(2), 'right');+ assert.equal(b.mouseModifiers({ altKey: false, ctrlKey: true, metaKey: false, shiftKey: true }), b.MOD.ctrl | b.MOD.shift);+});++test('frame coalescer sends only the last move per frame and flushes before a press', () => {+ const queue = [];+ const sent = [];+ const c = b.createFrameCoalescer((fn) => queue.push(fn), (v) => sent.push(v));+ c.push(1); c.push(2); c.push(3);+ assert.equal(queue.length, 1);+ queue.shift()();+ assert.deepEqual(sent, [3]);+ c.push(4);+ c.flush();+ assert.deepEqual(sent, [3, 4]);+ queue.shift()(); // the scheduled run finds nothing left+ assert.deepEqual(sent, [3, 4]);+ c.push(5); c.drop(); queue.shift()();+ assert.deepEqual(sent, [3, 4]);+});++test('wheel: lines and pages become pixels; steps in a frame add up and fractions carry', () => {+ assert.deepEqual(b.wheelPixels({ deltaX: 0, deltaY: 3, deltaMode: 1 }, 700), { dx: 0, dy: 120 });+ assert.deepEqual(b.wheelPixels({ deltaX: 0, deltaY: 1, deltaMode: 2 }, 700), { dx: 0, dy: 700 });+ const queue = [];+ const sent = [];+ const w = b.createWheelCoalescer((fn) => queue.push(fn), (m) => sent.push(m));+ w.add({ x: 10, y: 20 }, { dx: 0, dy: 4.25 });+ w.add({ x: 11, y: 21 }, { dx: 0, dy: 4.5 }, b.MOD.shift);+ assert.equal(queue.length, 1);+ queue.shift()();+ assert.deepEqual(sent, [{ action: 'wheel', x: 11, y: 21, delta_x: 0, delta_y: 8, modifiers: b.MOD.shift }]);+ w.add({ x: 11, y: 21 }, { dx: 0, dy: 0.25 });+ queue.shift()();+ assert.equal(sent[1].delta_y, 1, 'the 0.75 left over plus 0.25 makes one pixel');+});++test('planKey: printable keys carry text, Enter carries \\r, composition is skipped', () => {+ const p = b.planKey(key(), false);+ assert.equal(p.kind, 'send');+ assert.equal(p.messages[0].text, 'a');+ assert.equal(b.planKey(key({ key: 'Enter', code: 'Enter' }), false).messages[0].text, '\r');+ assert.equal(b.planKey(key({ isComposing: true }), false).kind, 'skip');+ assert.equal(b.planKey(key({ key: 'Process', keyCode: 229 }), false).kind, 'skip');+ assert.equal(b.planKey(key({ type: 'keyup' }), false).messages[0].text, undefined);+});++test('planKey: Mac Cmd becomes Ctrl, Cmd+arrows Home/End, Option+arrows word moves', () => {+ const cmdA = b.planKey(key({ metaKey: true }), true).messages[0];+ assert.equal(cmdA.modifiers, b.MOD.ctrl);+ assert.equal(cmdA.text, undefined);+ const home = b.planKey(key({ key: 'ArrowLeft', code: 'ArrowLeft', metaKey: true }), true).messages[0];+ assert.deepEqual([home.key, home.modifiers], ['Home', 0]);+ const top = b.planKey(key({ key: 'ArrowUp', code: 'ArrowUp', metaKey: true }), true).messages[0];+ assert.deepEqual([top.key, top.modifiers], ['Home', b.MOD.ctrl]);+ const word = b.planKey(key({ key: 'ArrowLeft', code: 'ArrowLeft', altKey: true }), true).messages[0];+ assert.equal(word.modifiers, b.MOD.ctrl);+ const accent = b.planKey(key({ key: 'é', code: 'KeyE', altKey: true }), true).messages[0];+ assert.deepEqual([accent.text, accent.modifiers], ['é', 0]);+ const cmd = b.planKey(key({ key: 'Meta', code: 'MetaRight', metaKey: true }), true).messages[0];+ assert.deepEqual([cmd.key, cmd.code], ['Control', 'ControlRight']);+});++test('planKey: paste is left to the paste event, copy also asks for the selection', () => {+ assert.equal(b.planKey(key({ key: 'v', code: 'KeyV', ctrlKey: true }), false).kind, 'paste');+ assert.equal(b.planKey(key({ key: 'v', code: 'KeyV', metaKey: true }), true).kind, 'paste');+ assert.equal(b.planKey(key({ key: 'c', code: 'KeyC', ctrlKey: true }), false).copy, true);+ assert.equal(b.planKey(key({ key: 'x', code: 'KeyX', metaKey: true }), true).copy, true);+});++test('createKeyboard: Mac Cmd chords go up at once, held keys go up on blur, stray ups are dropped', () => {+ const sent = [];+ const kb = b.createKeyboard(true, (m) => sent.push(m));+ kb.handle(key({ key: 'c', code: 'KeyC', metaKey: true }));+ assert.deepEqual(sent.map((m) => m.action === 'key' ? `${m.type}:${m.code}` : m.action), ['down:KeyC', 'up:KeyC', 'copy']);+ sent.length = 0;+ kb.handle(key({ key: 'b', code: 'KeyB' }));+ assert.deepEqual(kb.held(), ['KeyB']);+ kb.releaseAll();+ assert.deepEqual(sent.map((m) => `${m.type}:${m.code}`), ['down:KeyB', 'up:KeyB']);+ sent.length = 0;+ kb.handle(key({ type: 'keyup', key: 'q', code: 'KeyQ' }));+ assert.equal(sent.length, 0);+ assert.equal(kb.handle(key({ key: 'v', code: 'KeyV', metaKey: true })), false, 'paste keeps its default');+});++test('typeMessages splits text into 16 KB chunks without breaking characters', () => {+ assert.deepEqual(b.typeMessages(''), []);+ const parts = b.typeMessages('ab😀cd', 5);+ assert.deepEqual(parts.map((p) => p.text), ['ab', '😀c', 'd']);+});++test('parseSelect and parseDialog read server messages defensively', () => {+ const s = b.parseSelect({ type: 'select', id: 's1', options: [{ value: 'a', label: 'A' }], selected: [0], anchor: { left: 1, top: 2, width: 3, height: 4 }, label: ' Country ' });+ assert.ok(s);+ assert.equal(s.label, 'Country');+ assert.equal(b.parseSelect({ type: 'select' }), null);+ assert.equal(b.parseDialog({ type: 'dialog', kind: 'weird', message: 'Hi' }).kind, 'alert');+});++test('matchOption: type-ahead skips disabled options and cycles on a repeated letter', () => {+ const opts = [{ label: 'Austria' }, { label: 'Belgium', disabled: true }, { label: 'Brazil' }, { label: 'Bulgaria' }, { label: 'Canada' }].map((o, i) => ({ value: String(i), ...o }));+ assert.equal(b.matchOption(opts, 'b', 0), 2);+ assert.equal(b.matchOption(opts, 'b', 2), 3);+ assert.equal(b.matchOption(opts, 'bb', 3), 2, 'bb cycles back to Brazil');+ assert.equal(b.matchOption(opts, 'bu', 0), 3);+ assert.equal(b.matchOption(opts, 'z', 4), 4, 'no match keeps the active row');+ assert.equal(b.nextEnabled(opts, 0, 1), 2);+ assert.equal(b.nextEnabled(opts, 4, 1), 4);+});++test('popoverPlacement follows spec §4: 4 px below, 180–360 wide, 8 px inset, flips above', () => {+ const stage = { width: 1200, height: 800 };+ const p = b.popoverPlacement({ left: 100, top: 100, width: 120, height: 32 }, stage, 200);+ assert.deepEqual(p, { left: 100, top: 136, width: 180, maxHeight: 320 });+ assert.equal(b.popoverPlacement({ left: 100, top: 100, width: 600, height: 32 }, stage, 200).width, 360);+ assert.equal(b.popoverPlacement({ left: 1150, top: 100, width: 200, height: 32 }, stage, 200).left, 1200 - 8 - 200);+ const up = b.popoverPlacement({ left: 100, top: 700, width: 200, height: 32 }, stage, 200);+ assert.equal(up.top, 700 - 4 - 200);+ assert.ok(up.maxHeight <= 320);+});++test('splitAddress shows the host bright and the path muted', () => {+ assert.deepEqual(st.splitAddress('https://github.com/login?x=1'), { secure: true, host: 'github.com', rest: '/login?x=1' });+ assert.deepEqual(st.splitAddress('http://example.com/'), { secure: false, host: 'example.com', rest: '' });+ assert.deepEqual(st.splitAddress('about:blank'), { secure: false, host: 'about:blank', rest: '' });+ assert.equal(st.RELAYING_DELAY_MS, 300);+});++test('openStepFor picks the newest open step on this browser', () => {+ const s = (id, over) => ({ id, kind: 'sign_in', status: 'open', sandbox_target: 'vm', created_at: '2026-11-03T10:00:00Z', ...over });+ const map = { a: s('a'), b: s('b', { created_at: '2026-11-03T11:00:00Z', kind: 'two_factor' }), c: s('c', { sandbox_target: 'other', created_at: '2026-11-03T12:00:00Z' }), d: s('d', { status: 'done', created_at: '2026-11-03T13:00:00Z' }) };+ assert.equal(hs.openStepFor(map, 'vm').id, 'b');+ assert.equal(hs.openStepFor(map, undefined), null);+ assert.equal(hs.openStepFor(map, 'none'), null);+});++test('busy retry is every second for ten seconds; step copy per kind', () => {+ assert.equal(vm.TAKEOVER_RETRY_MS, 1000);+ assert.equal(vm.TAKEOVER_RETRY_FOR_MS, 10_000);+ assert.equal(vm.STEP_DONE.sign_in, 'Done, I’m signed in');+ assert.equal(vm.STEP_NEED.captcha, 'needs you to solve a puzzle');+});++test('live view errors: end of history is silent, the server prefix is dropped', () => {+ assert.equal(b.streamErrorText('history', 'Protocol error: No page to go forward to'), null);+ assert.equal(b.streamErrorText('history', 'Protocol error: No page to go back to'), null);+ assert.equal(b.streamErrorText('navigate', 'Protocol error: Navigation timed out'), 'Navigation timed out');+ assert.equal(b.streamErrorText('click', 'No page to go back to'), 'No page to go back to');+ assert.equal(b.streamErrorText(undefined, ''), 'Something went wrong in the browser.');+});++test('size drift: a cross-site navigation that drops the override is noticed, a pixel of rounding is not', () => {+ assert.equal(b.sizeDrifted({ width: 1408, height: 812 }, { width: 1408, height: 783 }), true);+ assert.equal(b.sizeDrifted({ width: 1408, height: 812 }, { width: 1409, height: 812 }), false);+ assert.equal(b.sizeDrifted(null, { width: 1280, height: 713 }), false);+ assert.equal(b.sizeDrifted({ width: 1408, height: 812 }, { width: 0, height: 0 }), false);+});diff --git a/frontend/tests/browserPanel.test.mjs b/frontend/tests/browserPanel.test.mjsindex e77d2f87..42c0922e 100644--- a/frontend/tests/browserPanel.test.mjs+++ b/frontend/tests/browserPanel.test.mjs@@ -31,13 +31,13 @@ test('before the bot opens a page the panel says "Browser idle" instead of the bfor (const activeUrl of ['', 'about:blank']) {const html = pane({ activeUrl });assert.match(html, /Browser idle/);- assert.doesNotMatch(html, /alt="Browser Viewport"/);+ assert.doesNotMatch(html, /data-browser-watch[^>]*>\s*<img [^>]*alt="Team's browser"/);}});test('once the bot has opened a page the live frame shows', () => {const html = pane({ activeUrl: 'https://www.google.com/maps' });- assert.match(html, /alt="Browser Viewport"/);+ assert.match(html, /data-browser-watch[^>]*>\s*<img [^>]*alt="Team's browser"/);assert.match(html, /data:image\/jpeg;base64,AAAA/);assert.doesNotMatch(html, /Browser idle/);});diff --git a/frontend/tests/browserStreamAck.test.mjs b/frontend/tests/browserStreamAck.test.mjsnew file mode 100644index 00000000..31ab9a4f--- /dev/null+++ b/frontend/tests/browserStreamAck.test.mjs@@ -0,0 +1,71 @@+// Rigel's D1 from the 0.6.9 takeover QA: the views acknowledge a frame from <img onLoad>, but an+// identical frame leaves the image's src unchanged, so no load event fires, no ack goes out and the+// server stops sending frames (after 15 s it drops the socket). The stream hook acks those itself.+import assert from 'node:assert/strict';+import test from 'node:test';+import { JSDOM } from 'jsdom';+import { loadBundled } from './bundle.mjs';++const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/spc_default', pretendToBeVisual: true });+const g = globalThis;+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage']) {+ if (!(k in dom.window)) continue;+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });+}++const sockets = [];+class FakeWebSocket {+ static OPEN = 1;+ constructor(url) { this.url = url; this.readyState = 1; this.sent = []; sockets.push(this); }+ send(text) { this.sent.push(JSON.parse(text)); }+ close() { this.readyState = 3; }+ receive(message) { this.onmessage?.({ data: JSON.stringify(message) }); }+}+g.WebSocket = g.window.WebSocket = FakeWebSocket;++const m = await loadBundled(`+ export { default as React } from 'react';+ export { createRoot } from 'react-dom/client';+ export { flushSync } from 'react-dom';+ export { useBrowserStream } from './src/useBrowserStream';+`);+const settle = async () => { for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0)); };++function Probe() {+ m.useBrowserStream('k1', true);+ return null;+}++test('an identical frame is acknowledged at once; a changed one waits for the image to load', async () => {+ const root = m.createRoot(document.createElement('div'));+ m.flushSync(() => root.render(m.React.createElement(Probe)));+ await settle();+ const ws = sockets.at(-1);+ assert.ok(ws, 'the hook opened a socket');+ ws.onopen?.();+ const acks = () => ws.sent.filter((s) => s.action === 'frame_ack').map((s) => s.id);++ ws.receive({ type: 'frame', id: 1, image: 'AAAA', width: 1280, height: 800 });+ await settle();+ assert.deepEqual(acks(), [], 'a first frame is acked by the image load, not the hook');++ ws.receive({ type: 'frame', id: 2, image: 'AAAA', width: 1280, height: 800 });+ await settle();+ assert.deepEqual(acks(), [2], 'the same picture again is acked straight away');++ ws.receive({ type: 'frame', id: 3, image: 'BBBB', width: 1280, height: 800 });+ await settle();+ assert.deepEqual(acks(), [2], 'a new picture waits for its load event');++ // After a reconnect the image is drawn afresh, so its load event acks it+ ws.onclose?.();+ await new Promise((r) => setTimeout(r, 1100));+ const next = sockets.at(-1);+ assert.notEqual(next, ws, 'the hook reconnected');+ next.onopen?.();+ next.receive({ type: 'frame', id: 4, image: 'BBBB', width: 1280, height: 800 });+ await settle();+ assert.deepEqual(next.sent.filter((s) => s.action === 'frame_ack'), [], 'the first frame after a reconnect is not acked early');++ m.flushSync(() => root.unmount());+});