Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

CAPTCHA hand-off frontend: full-screen phone control, drag and pinch, Solve it

Pixel (kwant bot)a734c7867906
diff --git a/frontend/e2e/captcha-handoff.mjs b/frontend/e2e/captcha-handoff.mjs
new file mode 100644
index 00000000..46b9a159
--- /dev/null
+++ b/frontend/e2e/captcha-handoff.mjs
@@ -0,0 +1,96 @@
+// Headless phone check of the CAPTCHA hand-off against tests/captcha_ui_harness.rs:
+// open the bot's chat, tap Solve it, check the view zooms to the puzzle, drag the slider with a
+// finger, and check the step closes by itself and the full-screen view goes away.
+// node captcha-handoff.mjs <harness dir> <out dir>
+// Needs playwright-core (PW_CORE=/path/to/playwright-core/index.mjs) and Chromium (CHROMIUM=...).
+const { chromium } = await import(process.env.PW_CORE || 'playwright-core');
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+
+const [dir, out] = process.argv.slice(2);
+const ready = JSON.parse(readFileSync(`${dir}/ready.json`, 'utf8'));
+const base = ready.url.replace(/\/$/, '');
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const steps = async () => (await (await fetch(`${base}/api/human-steps`)).json()).filter((s) => s.kind === 'captcha');
+const openStep = async () => (await steps()).find((s) => s.status === 'open');
+const results = [];
+
+async function waitFor(fn, what, ms = 20000) {
+ const end = Date.now() + ms;
+ while (Date.now() < end) {
+ const v = await fn();
+ if (v) return v;
+ await sleep(200);
+ }
+ throw new Error(`timed out: ${what}`);
+}
+
+const browser = await chromium.launch({ executablePath: process.env.CHROMIUM || '/usr/bin/chromium', args: ['--no-sandbox'] });
+try {
+ for (const [i, vp] of [{ width: 390, height: 844 }, { width: 412, height: 915 }].entries()) {
+ const tag = `${vp.width}x${vp.height}`;
+ if (i > 0) writeFileSync(`${dir}/rearm-${i}`, '');
+ const step = await waitFor(openStep, 'an open captcha step');
+ const ctx = await browser.newContext({ viewport: vp, isMobile: true, hasTouch: true, deviceScaleFactor: 2 });
+ const page = await ctx.newPage();
+ const errors = [];
+ page.on('pageerror', (e) => errors.push(String(e)));
+ await page.goto(base + '/');
+ await page.getByText(ready.bot_name, { exact: true }).first().tap();
+ const solve = page.getByRole('button', { name: 'Solve it' }).last();
+ await solve.waitFor({ timeout: 15000 });
+ await solve.scrollIntoViewIfNeeded();
+ await page.screenshot({ path: `${out}/${tag}-1-card.png` });
+ await solve.tap();
+
+ const overlay = page.locator('[data-browser-fullscreen]');
+ await overlay.waitFor({ timeout: 15000 });
+ const img = overlay.locator('[data-browser-stage] img');
+ await img.waitFor({ timeout: 15000 });
+ await page.getByText('continues by itself').first().waitFor();
+ await sleep(800);
+ const geo = await page.evaluate(() => {
+ const stage = document.querySelector('[data-browser-fullscreen] [data-browser-stage]');
+ const im = stage.querySelector('img');
+ const m = /translate\(([-\d.]+)px, ([-\d.]+)px\) scale\(([-\d.]+)\)/.exec(im.style.transform);
+ const r = stage.getBoundingClientRect();
+ return { tx: +m[1], ty: +m[2], scale: +m[3], left: r.left, top: r.top, width: r.width, height: r.height };
+ });
+ const fit = geo.width / 1280;
+ const box = step.target;
+ const boxLeft = box.x * geo.scale + geo.tx;
+ const boxRight = (box.x + box.width) * geo.scale + geo.tx;
+ const zoomed = geo.scale > fit * 2 && boxLeft >= -1 && boxRight <= geo.width + 1;
+ if (!zoomed) throw new Error(`not zoomed to the puzzle: ${JSON.stringify({ geo, fit, box })}`);
+ await page.screenshot({ path: `${out}/${tag}-2-zoomed.png` });
+
+ // The slider knob sits at page (510, 500); drag it 260 page px right with one finger
+ const toScreen = (x, y) => ({ x: geo.left + x * geo.scale + geo.tx, y: geo.top + y * geo.scale + geo.ty });
+ const from = toScreen(510, 500);
+ const to = toScreen(770, 500);
+ const cdp = await ctx.newCDPSession(page);
+ const touch = (type, p) => cdp.send('Input.dispatchTouchEvent', { type, touchPoints: p ? [{ x: p.x, y: p.y, id: 1 }] : [] });
+ await touch('touchStart', from);
+ const n = 24;
+ for (let k = 1; k <= n; k++) {
+ await touch('touchMove', { x: from.x + ((to.x - from.x) * k) / n, y: from.y });
+ await sleep(20);
+ if (k === n / 2) await page.screenshot({ path: `${out}/${tag}-3-dragging.png` });
+ }
+ await touch('touchEnd');
+
+ const closed = await waitFor(async () => (await steps()).find((s) => s.id === step.id && s.status !== 'open'), 'the step to close', 20000);
+ if (closed.status !== 'resolved_auto') throw new Error(`step closed as ${closed.status}`);
+ await page.getByText(/Solved, .* continues/).first().waitFor({ timeout: 5000 });
+ await page.screenshot({ path: `${out}/${tag}-4-solved.png` });
+ await overlay.waitFor({ state: 'detached', timeout: 10000 });
+ await page.getByText(/Solved\. .* continues\./).first().waitFor({ timeout: 5000 });
+ await page.screenshot({ path: `${out}/${tag}-5-card-after.png` });
+ if (errors.length) throw new Error(`page errors: ${errors.join('; ')}`);
+ results.push({ viewport: tag, step: step.id, zoom: +(geo.scale / fit).toFixed(2), status: closed.status });
+ console.log(`PASS ${tag}: zoom ${(geo.scale / fit).toFixed(2)}x of fit, drag solved it, step ${closed.status}, view closed`);
+ await ctx.close();
+ }
+} finally {
+ await browser.close();
+}
+writeFileSync(`${out}/playwright-result.json`, JSON.stringify(results, null, 2));
diff --git a/frontend/e2e/desktop-drag.mjs b/frontend/e2e/desktop-drag.mjs
new file mode 100644
index 00000000..78869e68
--- /dev/null
+++ b/frontend/e2e/desktop-drag.mjs
@@ -0,0 +1,34 @@
+// Desktop: Solve it opens the side panel (no full screen) and a mouse drag on the panel image solves the slider.
+const { chromium } = await import(process.env.PW_CORE || 'playwright-core');
+import { readFileSync, writeFileSync } from 'node:fs';
+const [dir, out] = process.argv.slice(2);
+const ready = JSON.parse(readFileSync(`${dir}/ready.json`, 'utf8'));
+const base = ready.url.replace(/\/$/, '');
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const steps = async () => (await (await fetch(`${base}/api/human-steps`)).json()).filter((s) => s.kind === 'captcha');
+async function waitFor(fn, what, ms = 20000) { const end = Date.now() + ms; while (Date.now() < end) { const v = await fn(); if (v) return v; await sleep(200); } throw new Error(`timed out: ${what}`); }
+writeFileSync(`${dir}/rearm-desktop-${Date.now()}`, '');
+const step = await waitFor(async () => (await steps()).find((s) => s.status === 'open'), 'open step');
+const b = await chromium.launch({ executablePath: process.env.CHROMIUM || '/usr/bin/chromium', args: ['--no-sandbox'] });
+const page = await (await b.newContext({ viewport: { width: 1280, height: 800 } })).newPage();
+await page.goto(base + '/');
+await page.getByText(ready.bot_name, { exact: true }).first().click();
+await page.getByRole('button', { name: 'Solve it' }).first().click();
+await page.getByText('Controlling').first().waitFor({ timeout: 15000 });
+if (await page.locator('[data-browser-fullscreen]').count()) throw new Error('full screen opened on desktop');
+const img = page.locator('img[alt="Browser Viewport"]');
+await img.waitFor();
+await sleep(800);
+await page.screenshot({ path: `${out}/1280x800-1-panel.png` });
+const r = await img.boundingBox();
+const s = Math.min(r.width / 1280, r.height / 800);
+const ox = r.x + (r.width - 1280 * s) / 2, oy = r.y + (r.height - 800 * s) / 2;
+await page.mouse.move(ox + 510 * s, oy + 500 * s);
+await page.mouse.down();
+for (let k = 1; k <= 20; k++) { await page.mouse.move(ox + (510 + 13 * k) * s, oy + 500 * s); await sleep(20); }
+await page.mouse.up();
+const closed = await waitFor(async () => (await steps()).find((x) => x.id === step.id && x.status !== 'open'), 'close');
+await page.getByText(/Solved\. .* continues\./).first().waitFor({ timeout: 5000 });
+await page.screenshot({ path: `${out}/1280x800-2-solved.png` });
+console.log(`PASS 1280x800 mouse drag: step ${closed.status}`);
+await b.close();
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index d1229caf..06ec8cf0 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -14,6 +14,7 @@ import {
HumanStep,
HumanStepMeta,
applyHumanStep,
+ captchaStepFor,
humanStepsApi,
latestOpenStep,
openStepsByKwant,
@@ -345,7 +346,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const openNotified = (n: Pick<NotifyEvent, 'kind' | 'kwant_id' | 'channel_id'>) => {
const target = { channel_id: n.channel_id, kwant_id: n.kwant_id };
if (n.kind === 'skill_proposed') openSkillsRef.current(n.kwant_id);
- else if (n.kind === 'human_step' && openHumanStepRef.current(n.kwant_id)) setIsVmPaneOpen(true);
+ else if (n.kind === 'human_step' && openHumanStepRef.current(n.kwant_id)) {
+ setIsVmPaneOpen(true);
+ // A CAPTCHA lands straight in the solve view
+ if (latestOpenStep(humanStepsRef.current, n.kwant_id)?.kind === 'captcha') setSolveRequest((v) => v + 1);
+ }
else if (!(n.kind === 'question_asked' && openQuestionRef.current(n.kwant_id))) openTargetRef.current(target);
};
const openNotifiedRef = useRef(openNotified);
@@ -554,6 +559,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// Virtual Machine & Live Browser state
const [isVmPaneOpen, setIsVmPaneOpen] = useState(false);
+ const [solveRequest, setSolveRequest] = useState(0);
const [activeUrl, setActiveUrl] = useState('');
const [pageTitle, setPageTitle] = useState('');
const [screenshotBase64, setScreenshotBase64] = useState<string | null>(null);
@@ -1572,8 +1578,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
kwantId={st?.kwant_id}
live={st}
waiting={!!turnId && !!turns[turnId]}
- onOpenBrowser={() => {
+ onOpenBrowser={(_target, solve) => {
setIsVmPaneOpen(true);
+ if (solve) setSolveRequest((v) => v + 1);
playSfx('click');
}}
onDone={(id) => answerHumanStep(id, 'done')}
@@ -2755,6 +2762,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onRestartVm={handleRestartVm}
onNavigateVm={handleNavigateVm}
vmApprovalsOff={space.approvals === 'off' || kwants.some(approvalsOff)}
+ vmCaptchaStep={captchaStepFor(humanSteps, activeSandboxId)}
+ vmSolveRequest={solveRequest}
pinned={pinned}
onEditInstructions={
isChannel && currentChannel
diff --git a/frontend/src/browserGestures.ts b/frontend/src/browserGestures.ts
new file mode 100644
index 00000000..561bff77
--- /dev/null
+++ b/frontend/src/browserGestures.ts
@@ -0,0 +1,252 @@
+// Live browser control on a phone: the page image sits in a stage the person can zoom and pan
+// with two fingers, while one finger taps (click) or drags (press, move, release) in the page.
+// Pure math and a small gesture state machine, so both can be tested without a DOM.
+
+export const PAGE_W = 1280;
+export const PAGE_H = 800;
+
+/** Page pixel (x, y) shows at stage pixel (x * scale + tx, y * scale + ty). */
+export interface View {
+ scale: number;
+ tx: number;
+ ty: number;
+}
+
+export interface Size {
+ width: number;
+ height: number;
+}
+
+export interface Box {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+/** How far in a person can zoom: four stage pixels per page pixel. */
+export const MAX_SCALE = 4;
+
+/** The whole page, as large as fits, pinned to the top so no band sits above it. */
+export function fitView(stage: Size, page: Size = { width: PAGE_W, height: PAGE_H }): View {
+ if (stage.width <= 0 || stage.height <= 0) return { scale: 1, tx: 0, ty: 0 };
+ const scale = Math.min(stage.width / page.width, stage.height / page.height);
+ return { scale, tx: (stage.width - page.width * scale) / 2, ty: 0 };
+}
+
+/** Keeps the zoom between fit and MAX_SCALE and the page covering the stage where it can. */
+export function clampView(view: View, stage: Size, page: Size = { width: PAGE_W, height: PAGE_H }): View {
+ const min = fitView(stage, page).scale;
+ const scale = Math.min(Math.max(view.scale, min), Math.max(min, MAX_SCALE));
+ const axis = (t: number, stageLen: number, pageLen: number, centre: boolean) => {
+ const len = pageLen * scale;
+ if (len <= stageLen) return centre ? (stageLen - len) / 2 : 0;
+ return Math.min(0, Math.max(stageLen - len, t));
+ };
+ return { scale, tx: axis(view.tx, stage.width, page.width, true), ty: axis(view.ty, stage.height, page.height, false) };
+}
+
+/** Zooms so `box` fills the stage with a margin, centred on it (a CAPTCHA widget, say). */
+export function zoomToBox(box: Box, stage: Size, page: Size = { width: PAGE_W, height: PAGE_H }, margin = 16): View {
+ if (box.width <= 0 || box.height <= 0) return fitView(stage, page);
+ const room = { width: Math.max(1, stage.width - margin * 2), height: Math.max(1, stage.height - margin * 2) };
+ const scale = Math.min(room.width / box.width, room.height / box.height, MAX_SCALE);
+ const cx = box.x + box.width / 2;
+ const cy = box.y + box.height / 2;
+ return clampView({ scale, tx: stage.width / 2 - cx * scale, ty: stage.height / 2 - cy * scale }, stage, page);
+}
+
+/** The page pixel under a stage point, or null off the page. */
+export function stageToPage(sx: number, sy: number, view: View, page: Size = { width: PAGE_W, height: PAGE_H }): { x: number; y: number } | null {
+ if (view.scale <= 0) return null;
+ const x = (sx - view.tx) / view.scale;
+ const y = (sy - view.ty) / view.scale;
+ if (x < 0 || y < 0 || x >= page.width || y >= page.height) return null;
+ return { x: Math.floor(x), y: Math.floor(y) };
+}
+
+/** Like stageToPage, but holds the point on the page's edge (a drag that strays off it). */
+export function stageToPageClamped(sx: number, sy: number, view: View, page: Size = { width: PAGE_W, height: PAGE_H }): { x: number; y: number } {
+ const x = (sx - view.tx) / view.scale;
+ const y = (sy - view.ty) / view.scale;
+ return { x: Math.floor(Math.min(page.width - 1, Math.max(0, x))), y: Math.floor(Math.min(page.height - 1, Math.max(0, y))) };
+}
+
+/** Two fingers moved from (a0, b0) to (a1, b1): the page point under their midpoint stays under it. */
+export function pinchView(start: View, a0: Pt, b0: Pt, a1: Pt, b1: Pt): View {
+ const d0 = Math.hypot(b0.x - a0.x, b0.y - a0.y) || 1;
+ const d1 = Math.hypot(b1.x - a1.x, b1.y - a1.y) || 1;
+ const scale = start.scale * (d1 / d0);
+ const m0 = { x: (a0.x + b0.x) / 2, y: (a0.y + b0.y) / 2 };
+ const m1 = { x: (a1.x + b1.x) / 2, y: (a1.y + b1.y) / 2 };
+ const px = (m0.x - start.tx) / start.scale;
+ const py = (m0.y - start.ty) / start.scale;
+ return { scale, tx: m1.x - px * scale, ty: m1.y - py * scale };
+}
+
+export interface Pt {
+ x: number;
+ y: number;
+}
+
+/** What a gesture sends to the page; coordinates are page pixels. */
+export type PageInput =
+ | { action: 'click'; x: number; y: number }
+ | { action: 'pointer_down' | 'pointer_move' | 'pointer_up'; x: number; y: number }
+ | { action: 'scroll'; x: number; y: number; delta_x: number; delta_y: number };
+
+export interface GestureHost {
+ /** Stage point → page point, null off the page. */
+ toPage(p: Pt): Pt | null;
+ /** Same, held on the page's edge. */
+ toPageClamped(p: Pt): Pt;
+ send(input: PageInput): void;
+ /** Two-finger zoom or pan of the local view; omit where the view doesn't zoom (desktop). */
+ view?: { get(): View; set(v: View): void; zoomed(): boolean };
+ now(): number;
+ /** Runs `fn` after `ms` (for the move throttle); returns a cancel. */
+ later(fn: () => void, ms: number): () => void;
+}
+
+/** A finger or the mouse has to travel this far (stage px) before a tap becomes a drag. */
+export const DRAG_SLOP = 6;
+/** About one move per frame, which sliders need to follow the drag. */
+export const MOVE_INTERVAL_MS = 16;
+/** Stage pixels of two-finger swipe per wheel step, and how much a wheel step scrolls. */
+const WHEEL_GAIN = 2.5;
+
+type Mode =
+ | { kind: 'idle' }
+ | { kind: 'press'; id: number; start: Pt; last: Pt }
+ | { kind: 'drag'; id: number; last: Pt }
+ | { kind: 'two'; a0: Pt; b0: Pt; start: View; ids: [number, number]; pos: Map<number, Pt>; split: 'undecided' | 'view' | 'wheel'; wheelFrom: Pt }
+ | { kind: 'spent' };
+
+/**
+ * One finger: a tap clicks, a drag presses, moves (about 60 a second) and releases.
+ * Two fingers: pinch or pan the view when it can zoom; at the fitted view a vertical two-finger
+ * swipe scrolls the page instead. A finger added mid-drag is ignored so a drag never breaks.
+ */
+export function createGestureTracker(host: GestureHost) {
+ let mode: Mode = { kind: 'idle' };
+ let lastMoveAt = -Infinity;
+ let pendingMove: Pt | null = null;
+ let cancelTimer: (() => void) | null = null;
+ const fingers = new Map<number, Pt>();
+
+ const flushMove = () => {
+ cancelTimer?.();
+ cancelTimer = null;
+ if (!pendingMove) return;
+ const p = host.toPageClamped(pendingMove);
+ pendingMove = null;
+ lastMoveAt = host.now();
+ host.send({ action: 'pointer_move', ...p });
+ };
+
+ const queueMove = (p: Pt) => {
+ pendingMove = p;
+ const wait = MOVE_INTERVAL_MS - (host.now() - lastMoveAt);
+ if (wait <= 0) flushMove();
+ else if (!cancelTimer) cancelTimer = host.later(flushMove, wait);
+ };
+
+ const startTwo = () => {
+ const [a, b] = [...fingers.entries()];
+ const v = host.view?.get() ?? { scale: 1, tx: 0, ty: 0 };
+ mode = { kind: 'two', a0: a[1], b0: b[1], start: v, ids: [a[0], b[0]], pos: fingers, split: 'undecided', wheelFrom: mid(a[1], b[1]) };
+ };
+
+ return {
+ down(id: number, p: Pt, primary = true) {
+ fingers.set(id, p);
+ if (mode.kind === 'idle' && primary) {
+ if (!host.toPage(p)) { mode = { kind: 'spent' }; return; }
+ mode = { kind: 'press', id, start: p, last: p };
+ } else if (mode.kind === 'press' && fingers.size === 2) {
+ // A second finger before the first moved: a zoom, not a tap
+ startTwo();
+ } else if (mode.kind === 'spent' && fingers.size === 2) {
+ startTwo();
+ }
+ },
+
+ move(id: number, p: Pt) {
+ if (!fingers.has(id)) return;
+ fingers.set(id, p);
+ if (mode.kind === 'press' && mode.id === id) {
+ if (Math.hypot(p.x - mode.start.x, p.y - mode.start.y) < DRAG_SLOP) return;
+ const from = host.toPageClamped(mode.start);
+ host.send({ action: 'pointer_down', ...from });
+ lastMoveAt = host.now();
+ mode = { kind: 'drag', id, last: p };
+ queueMove(p);
+ } else if (mode.kind === 'drag' && mode.id === id) {
+ mode.last = p;
+ queueMove(p);
+ } else if (mode.kind === 'two' && mode.ids.includes(id)) {
+ const a1 = fingers.get(mode.ids[0])!;
+ const b1 = fingers.get(mode.ids[1])!;
+ if (mode.split === 'undecided') {
+ const spread = Math.abs(Math.hypot(b1.x - a1.x, b1.y - a1.y) - Math.hypot(mode.b0.x - mode.a0.x, mode.b0.y - mode.a0.y));
+ const m = mid(a1, b1);
+ const travel = Math.hypot(m.x - mode.wheelFrom.x, m.y - mode.wheelFrom.y);
+ if (spread < 10 && travel < 10) return;
+ // Fingers spreading or pinching zoom; moving together scroll the page unless zoomed in
+ mode.split = host.view && (spread >= 10 || host.view.zoomed()) ? 'view' : 'wheel';
+ }
+ if (mode.split === 'view' && host.view) {
+ host.view.set(pinchView(mode.start, mode.a0, mode.b0, a1, b1));
+ } else if (mode.split === 'wheel') {
+ const m = mid(a1, b1);
+ const dy = mode.wheelFrom.y - m.y;
+ const dx = mode.wheelFrom.x - m.x;
+ if (Math.abs(dy) < 12 && Math.abs(dx) < 12) return;
+ mode.wheelFrom = m;
+ const at = host.toPage(m) ?? { x: PAGE_W / 2, y: PAGE_H / 2 };
+ const scale = host.view?.get().scale ?? 1;
+ host.send({ action: 'scroll', ...at, delta_x: Math.round((dx * WHEEL_GAIN) / scale), delta_y: Math.round((dy * WHEEL_GAIN) / scale) });
+ }
+ }
+ },
+
+ up(id: number, p?: Pt) {
+ if (p) fingers.set(id, p);
+ const at = fingers.get(id);
+ fingers.delete(id);
+ if (mode.kind === 'press' && mode.id === id) {
+ const target = host.toPage(at ?? mode.start);
+ mode = fingers.size ? { kind: 'spent' } : { kind: 'idle' };
+ if (target) host.send({ action: 'click', ...target });
+ return;
+ }
+ if (mode.kind === 'drag' && mode.id === id) {
+ if (at) pendingMove = at;
+ flushMove();
+ host.send({ action: 'pointer_up', ...host.toPageClamped(at ?? mode.last) });
+ mode = fingers.size ? { kind: 'spent' } : { kind: 'idle' };
+ return;
+ }
+ if (!fingers.size) mode = { kind: 'idle' };
+ else if (mode.kind === 'two') mode = { kind: 'spent' };
+ },
+
+ /** The browser took the touch away (a system gesture, say): let go without clicking. */
+ cancel(id: number) {
+ const at = fingers.get(id);
+ fingers.delete(id);
+ if (mode.kind === 'drag' && mode.id === id) {
+ flushMove();
+ host.send({ action: 'pointer_up', ...host.toPageClamped(at ?? mode.last) });
+ }
+ mode = fingers.size ? { kind: 'spent' } : { kind: 'idle' };
+ },
+
+ /** Mid-drag right now (for the cursor and to keep the page from scrolling). */
+ dragging: () => mode.kind === 'drag',
+ };
+}
+
+function mid(a: Pt, b: Pt): Pt {
+ return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
+}
diff --git a/frontend/src/components/BrowserControlOverlay.tsx b/frontend/src/components/BrowserControlOverlay.tsx
new file mode 100644
index 00000000..00a42bab
--- /dev/null
+++ b/frontend/src/components/BrowserControlOverlay.tsx
@@ -0,0 +1,350 @@
+import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { CheckCircle2, Hand, Keyboard, Loader2, Maximize, Puzzle } from 'lucide-react';
+import {
+ Box,
+ PAGE_H,
+ PAGE_W,
+ PageInput,
+ Pt,
+ Size,
+ View,
+ clampView,
+ createGestureTracker,
+ fitView,
+ stageToPage,
+ stageToPageClamped,
+ zoomToBox,
+} from '../browserGestures';
+import { domainOf } from '../humanSteps';
+
+/** 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) {
+ send(input.action === 'scroll' ? input : { ...input, delta_x: 0, delta_y: 0 }, input.action !== 'pointer_move');
+}
+
+/** A live page image the person drives with a finger (tap, drag) and zooms with two (pinch, pan). */
+function ZoomStage({
+ image,
+ onFrameDone,
+ send,
+ target,
+ onTap,
+ label,
+}: {
+ image: string | null;
+ onFrameDone: () => void;
+ send: (input: PageInput) => void;
+ /** A box to zoom to (the CAPTCHA); null shows the whole page. */
+ target: Box | null;
+ onTap?: () => void;
+ label: string;
+}) {
+ const stageRef = useRef<HTMLDivElement>(null);
+ const [stage, setStage] = useState<Size>({ width: 0, height: 0 });
+ const [view, setView] = useState<View>({ scale: 0, tx: 0, ty: 0 });
+ // 'box' follows the target as it moves or the screen turns; a pinch makes it 'free'
+ const [mode, setMode] = useState<'fit' | 'box' | 'free'>(target ? 'box' : 'fit');
+ const viewRef = useRef(view);
+ viewRef.current = view;
+ const stageSize = useRef(stage);
+ stageSize.current = stage;
+
+ 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();
+ }, []);
+
+ const targetKey = target ? `${target.x},${target.y},${target.width},${target.height}` : '';
+ useEffect(() => {
+ if (target) setMode('box');
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [targetKey]);
+
+ 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));
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [stage.width, stage.height, mode, targetKey]);
+
+ const sendRef = useRef(send);
+ sendRef.current = send;
+ const onTapRef = useRef(onTap);
+ onTapRef.current = onTap;
+ const tracker = useMemo(
+ () =>
+ createGestureTracker({
+ toPage: (p) => stageToPage(p.x, p.y, viewRef.current),
+ toPageClamped: (p) => stageToPageClamped(p.x, p.y, viewRef.current),
+ send: (input) => {
+ if (input.action === 'click') onTapRef.current?.();
+ sendRef.current(input);
+ },
+ view: {
+ get: () => viewRef.current,
+ set: (v) => {
+ setMode('free');
+ setView(clampView(v, stageSize.current));
+ },
+ zoomed: () => viewRef.current.scale > fitView(stageSize.current).scale * 1.02,
+ },
+ now: () => performance.now(),
+ later: (fn, ms) => {
+ const t = window.setTimeout(fn, ms);
+ return () => window.clearTimeout(t);
+ },
+ }),
+ []
+ );
+
+ const at = (e: React.PointerEvent): Pt => {
+ const r = stageRef.current!.getBoundingClientRect();
+ return { x: e.clientX - r.left, y: e.clientY - r.top };
+ };
+
+ return (
+ <div
+ ref={stageRef}
+ data-browser-stage
+ aria-label={label}
+ className="relative flex-1 min-h-0 overflow-hidden bg-black select-none"
+ style={{ touchAction: 'none' }}
+ onPointerDown={(e) => {
+ if (e.pointerType === 'mouse' && e.button !== 0) return;
+ e.currentTarget.setPointerCapture?.(e.pointerId);
+ tracker.down(e.pointerId, at(e), e.isPrimary);
+ }}
+ onPointerMove={(e) => tracker.move(e.pointerId, at(e))}
+ onPointerUp={(e) => tracker.up(e.pointerId, at(e))}
+ onPointerCancel={(e) => tracker.cancel(e.pointerId)}
+ onContextMenu={(e) => e.preventDefault()}
+ >
+ {image && view.scale > 0 ? (
+ <img
+ src={image}
+ alt="The bot's browser"
+ draggable={false}
+ 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})` }}
+ />
+ ) : (
+ <div className="absolute inset-0 flex items-center justify-center text-zinc-500">
+ <Loader2 size={20} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ <span className="sr-only">Waiting for the browser</span>
+ </div>
+ )}
+
+ <div className="absolute right-3 bottom-3 flex gap-2" style={{ marginBottom: 'env(safe-area-inset-bottom)' }}>
+ {target && mode !== 'box' && (
+ <button
+ type="button"
+ onPointerDown={(e) => e.stopPropagation()}
+ onClick={() => setMode('box')}
+ className="inline-flex items-center gap-1.5 min-h-[40px] px-3 rounded-full bg-zinc-900/90 border border-zinc-700 text-sm text-zinc-100"
+ >
+ <Puzzle size={14} aria-hidden="true" /> Puzzle
+ </button>
+ )}
+ {mode !== 'fit' && (
+ <button
+ type="button"
+ onPointerDown={(e) => e.stopPropagation()}
+ onClick={() => setMode('fit')}
+ className="inline-flex items-center gap-1.5 min-h-[40px] px-3 rounded-full bg-zinc-900/90 border border-zinc-700 text-sm text-zinc-100"
+ >
+ <Maximize size={14} aria-hidden="true" /> Whole page
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+/** Text typed on the phone's keyboard goes to the page; the field itself stays invisible. */
+export function textEdits(before: string, after: string): Array<{ action: 'key'; key: 'Backspace' } | { action: 'type'; text: string }> {
+ let same = 0;
+ while (same < before.length && same < after.length && before[same] === after[same]) same++;
+ const out: Array<{ action: 'key'; key: 'Backspace' } | { action: 'type'; text: string }> = [];
+ for (let i = same; i < before.length; i++) out.push({ action: 'key', key: 'Backspace' });
+ if (after.length > same) out.push({ action: 'type', text: after.slice(same) });
+ return out;
+}
+
+const PASSED_KEYS = ['Enter', 'Tab', 'Escape', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];
+
+export interface BrowserControlOverlayProps {
+ botName: string;
+ pageUrl: string;
+ image: string | null;
+ onFrameDone: () => void;
+ send: (payload: Record<string, unknown>, input?: boolean) => void;
+ busy: boolean;
+ error: string | null;
+ /** After a tap: did it land in a text field (then the keyboard opens). */
+ tapFocus: { seq: number; editable: boolean } | null;
+ /** A CAPTCHA is open: show the hint and zoom to its box. */
+ captcha: { target: Box | null } | null;
+ /** The CAPTCHA closed by itself: say so, then the parent closes this. */
+ solved: boolean;
+ onHandBack: () => void;
+}
+
+/**
+ * Taking control on a phone: the page fills the screen with one slim bar on top.
+ * One finger taps and drags in the page, two fingers zoom the view, and tapping a text field
+ * opens the phone's own keyboard.
+ */
+export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({
+ botName,
+ pageUrl,
+ image,
+ onFrameDone,
+ send,
+ busy,
+ error,
+ tapFocus,
+ captcha,
+ solved,
+ onHandBack,
+}) => {
+ const keys = useRef<HTMLInputElement>(null);
+ const typed = useRef('');
+ const [keyboard, setKeyboard] = useState(false);
+
+ const openKeyboard = useCallback(() => {
+ const el = keys.current;
+ if (!el) return;
+ el.value = '';
+ typed.current = '';
+ el.focus({ preventScroll: true });
+ setKeyboard(true);
+ }, []);
+
+ // A tap that focused a text field in the page brings up the keyboard; one that didn't puts it away
+ const lastSeq = useRef(tapFocus?.seq ?? 0);
+ useEffect(() => {
+ if (!tapFocus || tapFocus.seq === lastSeq.current) return;
+ lastSeq.current = tapFocus.seq;
+ if (tapFocus.editable) openKeyboard();
+ else keys.current?.blur();
+ }, [tapFocus, openKeyboard]);
+
+ // The page behind can't scroll or zoom while this is up
+ useEffect(() => {
+ const html = document.documentElement;
+ const before = html.style.overflow;
+ html.style.overflow = 'hidden';
+ return () => {
+ html.style.overflow = before;
+ };
+ }, []);
+
+ const domain = domainOf(pageUrl) || pageUrl || 'Browser';
+ const pageInput = useCallback((input: PageInput) => sendPageInput(send, input), [send]);
+
+ return createPortal(
+ <div
+ role="dialog"
+ 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"
+ 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 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="flex-1 min-w-0 truncate font-mono text-xs text-zinc-300" title={pageUrl}>
+ {domain}
+ </span>
+ <button
+ type="button"
+ 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"
+ >
+ <Keyboard size={18} aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ onClick={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"
+ >
+ <Hand size={15} aria-hidden="true" /> Hand back
+ </button>
+ </div>
+ {(solved || captcha || error) && (
+ <p
+ role="status"
+ aria-live="polite"
+ className={`px-3 pb-2 text-xs ${solved ? 'text-emerald-300' : error ? 'text-rose-300' : 'text-amber-200'}`}
+ >
+ {solved ? (
+ <span className="inline-flex items-center gap-1.5">
+ <CheckCircle2 size={13} aria-hidden="true" /> Solved, {botName} continues
+ </span>
+ ) : error ? (
+ error
+ ) : (
+ <>Solve the puzzle, {botName} continues by itself</>
+ )}
+ </p>
+ )}
+ </div>
+
+ <ZoomStage
+ image={image}
+ onFrameDone={onFrameDone}
+ send={pageInput}
+ target={captcha?.target ?? null}
+ label={`${botName}'s page. Tap to click, drag with one finger, pinch to zoom.`}
+ />
+
+ <div className="shrink-0" style={{ height: 'env(safe-area-inset-bottom)' }} />
+
+ <input
+ ref={keys}
+ type="text"
+ aria-label="Type into the page"
+ autoCapitalize="off"
+ autoCorrect="off"
+ autoComplete="off"
+ spellCheck={false}
+ enterKeyHint="send"
+ onBlur={() => setKeyboard(false)}
+ onInput={(e) => {
+ const now = e.currentTarget.value;
+ for (const edit of textEdits(typed.current, now)) send(edit, true);
+ typed.current = now;
+ }}
+ onKeyDown={(e) => {
+ if (PASSED_KEYS.includes(e.key)) {
+ e.preventDefault();
+ send({ action: 'key', key: e.key, code: e.code }, true);
+ if (e.key === 'Enter') {
+ e.currentTarget.value = '';
+ typed.current = '';
+ }
+ } else if (e.key === 'Backspace' && !e.currentTarget.value) {
+ send({ action: 'key', key: 'Backspace', code: 'Backspace' }, true);
+ }
+ }}
+ className="fixed left-0 bottom-0 w-px h-px opacity-0"
+ style={{ fontSize: 16 }}
+ />
+ </div>,
+ document.body
+ );
+};
+
+export { ZoomStage };
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 8ad5d5be..aa94b37a 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -11,7 +11,7 @@ import { groupDiscussionThreads, stripDiscussionMarkers } from '../discussionThr
import { PinnedInstructions, PinnedItem } from './Instructions';
import { DelegationMeta, parseDelegationMeta } from '../threads';
import { QuestionMeta, parseQuestionMeta } from '../questions';
-import { HumanStepMeta, parseHumanStepMeta } from '../humanSteps';
+import { HumanStep, HumanStepMeta, parseHumanStepMeta } from '../humanSteps';
import { LiveActivity, hasThinkingText, parseActivityMeta } from '../activity';
import { LiveActivityList, SavedActivityList } from './ActivityList';
import { SuggestionMeta, parseSuggestionMeta } from '../mcpSuggestions';
@@ -174,6 +174,9 @@ export interface ChatViewProps {
onNavigateVm?: (url: string) => void;
/** Some bot in the space runs without asking (the saved-passwords note). */
vmApprovalsOff?: boolean;
+ /** The CAPTCHA the open bot's browser waits on, and a counter that opens it to solve. */
+ vmCaptchaStep?: HumanStep | null;
+ vmSolveRequest?: number;
/** Pinned team/channel instructions, shown collapsed above the messages. */
pinned?: PinnedItem[];
/** Opens the channel's instructions editor; only for channels. */
@@ -393,6 +396,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
onRestartVm,
onNavigateVm,
vmApprovalsOff,
+ vmCaptchaStep,
+ vmSolveRequest,
pinned = [],
onEditInstructions,
highlightMessageId,
@@ -1458,6 +1463,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
onRestartVm={onRestartVm}
onNavigate={onNavigateVm}
approvalsOff={vmApprovalsOff}
+ captchaStep={vmCaptchaStep}
+ solveRequest={vmSolveRequest}
/>
</div>
</div>
diff --git a/frontend/src/components/HumanStepCard.tsx b/frontend/src/components/HumanStepCard.tsx
index b192c878..9eb0c74c 100644
--- a/frontend/src/components/HumanStepCard.tsx
+++ b/frontend/src/components/HumanStepCard.tsx
@@ -1,5 +1,5 @@
import React, { useState } from 'react';
-import { CheckCircle2, Clock, Globe, Hand, Loader2, MinusCircle, MonitorPlay } from 'lucide-react';
+import { CheckCircle2, Clock, Globe, Hand, Loader2, MinusCircle, MonitorPlay, Puzzle } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { HumanStep, HumanStepMeta, KIND_TEXT, domainOf, humanStepView } from '../humanSteps';
@@ -12,8 +12,8 @@ export interface HumanStepCardProps {
live?: HumanStep | null;
/** A turn is paused on this step right now (else Done starts a new reply). */
waiting: boolean;
- /** Shows the bot's browser panel. */
- onOpenBrowser?: (sandboxTarget: string | null) => void;
+ /** Shows the bot's browser panel; `solve` takes control and, on a phone, opens it full screen. */
+ onOpenBrowser?: (sandboxTarget: string | null, solve?: boolean) => void;
/** Resolve to an error message on failure. */
onDone: (id: string) => Promise<string | void>;
onSkip: (id: string) => Promise<string | void>;
@@ -36,6 +36,7 @@ export const HumanStepCard: React.FC<HumanStepCardProps> = ({ meta, messageId, k
const text = KIND_TEXT[view.step_kind];
const domain = domainOf(view.url);
const headingId = `hs-${messageId}`;
+ const captcha = view.step_kind === 'captcha';
const answer = async (which: 'done' | 'skip') => {
if (!open || busy) return;
@@ -48,7 +49,15 @@ export const HumanStepCard: React.FC<HumanStepCardProps> = ({ meta, messageId, k
};
const line =
- status === 'done' ? (
+ status === 'resolved_auto' ? (
+ <span className="inline-flex items-center gap-1.5 text-emerald-300">
+ <CheckCircle2 size={13} aria-hidden="true" /> Solved. {kwantName} continues.
+ </span>
+ ) : status === 'timed_out' ? (
+ <span className="inline-flex items-center gap-1.5 text-zinc-400">
+ <Clock size={13} aria-hidden="true" /> Nobody solved it in time. {kwantName} moved on without it.
+ </span>
+ ) : status === 'done' ? (
<span className="inline-flex items-center gap-1.5 text-emerald-300">
<CheckCircle2 size={13} aria-hidden="true" /> Done. {kwantName} is carrying on{view.status === 'open' ? '…' : '.'}
</span>
@@ -100,7 +109,16 @@ export const HumanStepCard: React.FC<HumanStepCardProps> = ({ meta, messageId, k
{open && (
<div className="px-4 pb-2 flex flex-col sm:flex-row sm:flex-wrap gap-2">
- {onOpenBrowser && (
+ {onOpenBrowser && captcha && (
+ <button
+ type="button"
+ 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}`}
+ >
+ <Puzzle size={16} aria-hidden="true" /> Solve it
+ </button>
+ )}
+ {onOpenBrowser && !captcha && (
<button
type="button"
onClick={() => onOpenBrowser(view.sandbox_target)}
@@ -113,7 +131,11 @@ export const HumanStepCard: React.FC<HumanStepCardProps> = ({ meta, messageId, k
type="button"
onClick={() => 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 font-semibold bg-amber-400 text-zinc-950 hover:bg-amber-300 disabled:opacity-60 ${focusRing}`}
+ 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
+ ? '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'
+ }`}
>
{busy === 'done' ? <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <CheckCircle2 size={14} aria-hidden="true" />}
{text.done}
@@ -133,7 +155,10 @@ export const HumanStepCard: React.FC<HumanStepCardProps> = ({ meta, messageId, k
<p role="status" aria-live="polite" className="min-w-0">
{line}
</p>
- {open && <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">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>}
{error && (
<span role="alert" className="basis-full text-rose-300">
{error}
diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsx
index 66d9f2e7..5a57f6ad 100644
--- a/frontend/src/components/VirtualMachinePane.tsx
+++ b/frontend/src/components/VirtualMachinePane.tsx
@@ -11,6 +11,8 @@ import {
Keyboard,
Loader2,
Laptop,
+ Puzzle,
+ CheckCircle2,
} from 'lucide-react';
import { playSfx } from '../audio/chiptune';
import { mapBrowserPoint } from '../browserViewport';
@@ -20,6 +22,24 @@ import { browserFooterLabel, isBlankPage, showsLocalWindow } from '../computerMo
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';
+
+const PHONE_QUERY = '(max-width: 639px)';
+
+/** Below 640px taking control opens the page full screen. */
+function useNarrow(): boolean {
+ const [narrow, setNarrow] = useState(() => typeof window !== 'undefined' && !!window.matchMedia?.(PHONE_QUERY).matches);
+ useEffect(() => {
+ const mq = window.matchMedia?.(PHONE_QUERY);
+ if (!mq) return;
+ const on = () => setNarrow(mq.matches);
+ mq.addEventListener('change', on);
+ return () => mq.removeEventListener('change', on);
+ }, []);
+ return narrow;
+}
export interface TerminalLogEntry {
command: string;
@@ -43,6 +63,10 @@ export interface VirtualMachinePaneProps {
onNavigate?: (url: string) => void;
/** Some bot in the space runs without asking (shown next to saved passwords). */
approvalsOff?: boolean;
+ /** The CAPTCHA this bot's browser is stuck on (open, or closed a moment ago). */
+ captchaStep?: HumanStep | null;
+ /** Goes up each time the person asks to solve it: take control and, on a phone, go full screen. */
+ solveRequest?: number;
}
type PaneTab = 'browser' | 'terminal' | 'vault';
@@ -56,6 +80,9 @@ export function chosenPaneTab(teamId: string | undefined): PaneTab {
return (teamId && chosenTabs.get(teamId)) || 'browser';
}
+// A notification tap switches chats, which mounts a new pane: the request it carries is still new to that one.
+let handledSolve = 0;
+
export function rememberPaneTab(teamId: string | undefined, tab: PaneTab): void {
if (teamId) chosenTabs.set(teamId, tab);
}
@@ -75,6 +102,8 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
onRestartVm,
onNavigate,
approvalsOff = false,
+ captchaStep = null,
+ solveRequest = 0,
}) => {
const [activeTab, setActiveTab] = useState<PaneTab>(() => chosenPaneTab(teamId));
useEffect(() => rememberPaneTab(teamId, activeTab), [teamId, activeTab]);
@@ -100,6 +129,12 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
const lastWheelTimeRef = useRef<number>(0);
const imageRef = useRef<HTMLImageElement>(null);
const viewportRef = useRef<HTMLDivElement>(null);
+ const narrow = useNarrow();
+ const [fullScreen, setFullScreen] = useState(false);
+ const showFullScreen = fullScreen && narrow && activeTab === 'browser' && !isWindow;
+ const captchaOpen = captchaStep?.status === 'open';
+ // Shown for a moment after the CAPTCHA closes by itself, before control goes back to the bot
+ const [solvedNote, setSolvedNote] = useState(false);
// 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;
@@ -121,6 +156,93 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
setInputUrl(activeUrl);
}, [activeUrl]);
+ // "Solve it" on the card or a CAPTCHA notification: take control once the stream is up
+ const [wantsControl, setWantsControl] = useState(false);
+ useEffect(() => {
+ if (solveRequest <= handledSolve) return;
+ handledSolve = solveRequest;
+ setActiveTab('browser');
+ setSolvedNote(false);
+ setWantsControl(true);
+ setFullScreen(true);
+ }, [solveRequest]);
+ const { connected, controlling, send } = stream;
+ useEffect(() => {
+ if (!wantsControl || !connected) return;
+ setWantsControl(false);
+ if (!controlling) send({ action: 'take_control' });
+ }, [wantsControl, connected, controlling, send]);
+
+ // The CAPTCHA went away: by itself it says so, then hands the browser back; any other way just closes
+ const captchaStatus = captchaStep?.status;
+ const lastCaptcha = useRef<{ id?: string; status?: string }>({ id: captchaStep?.id, status: captchaStatus });
+ useEffect(() => {
+ const was = lastCaptcha.current;
+ lastCaptcha.current = { id: captchaStep?.id, status: captchaStatus };
+ if (was.status !== 'open' || was.id !== captchaStep?.id || captchaStatus === 'open') return;
+ const finish = () => {
+ setFullScreen(false);
+ setSolvedNote(false);
+ if (stream.controlling) send({ action: 'release_control' });
+ };
+ if (captchaStatus === 'resolved_auto') {
+ setSolvedNote(true);
+ playSfx('coin');
+ const t = setTimeout(finish, 1500);
+ return () => clearTimeout(t);
+ }
+ finish();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [captchaStep?.id, captchaStatus]);
+
+ const handBack = () => {
+ playSfx('click');
+ setFullScreen(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
@@ -140,26 +262,6 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
[stream.send]
);
- // Viewport Click Handler
- const handleViewportClick = (e: React.MouseEvent<HTMLDivElement>) => {
- if (!isControlMode || !imageRef.current) return;
- const img = imageRef.current;
- const rect = img.getBoundingClientRect();
- const point = mapBrowserPoint(e.clientX, e.clientY, rect, img.naturalWidth, img.naturalHeight);
- if (!point) return;
- viewportRef.current?.focus({ preventScroll: true });
- const frame = e.currentTarget.getBoundingClientRect();
-
- playSfx('click');
- const rippleId = Date.now();
- setClickRipples((prev) => [...prev, { id: rippleId, x: e.clientX - frame.left, y: e.clientY - frame.top }]);
- setTimeout(() => {
- setClickRipples((prev) => prev.filter((r) => r.id !== rippleId));
- }, 600);
-
- sendInteraction({ action: 'click', ...point });
- };
-
// Viewport Wheel / Scroll Handler
const handleViewportWheel = (e: React.WheelEvent<HTMLDivElement>) => {
if (!isControlMode || !imageRef.current) return;
@@ -227,6 +329,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
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'}
@@ -436,7 +539,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
{isControlMode && (
<form
onSubmit={handleQuickTypeSubmit}
- className="flex items-center gap-1.5 p-1 bg-zinc-900 border border-cyan-500/40 rounded-lg text-xs"
+ 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
@@ -456,6 +559,32 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
</form>
)}
+ {(captchaOpen || solvedNote) && (
+ <div
+ role="status"
+ aria-live="polite"
+ className={`flex items-center gap-2 px-2.5 py-1.5 rounded-lg border text-[11px] ${
+ solvedNote ? 'border-emerald-500/30 bg-emerald-950/40 text-emerald-300' : 'border-amber-500/30 bg-amber-950/40 text-amber-200'
+ }`}
+ >
+ {solvedNote ? <CheckCircle2 size={13} aria-hidden="true" /> : <Puzzle size={13} aria-hidden="true" />}
+ <span className="flex-1">{solvedNote ? `Solved, ${teamName} continues` : `Solve the puzzle, ${teamName} continues by itself`}</span>
+ {!solvedNote && (!isControlMode || narrow) && (
+ <button
+ type="button"
+ onClick={() => {
+ playSfx('click');
+ setWantsControl(true);
+ setFullScreen(true);
+ }}
+ className="px-2 py-1 rounded-md bg-amber-400 text-zinc-950 font-semibold"
+ >
+ Solve it
+ </button>
+ )}
+ </div>
+ )}
+
{/* Viewport Frame */}
{controlError && (
<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">
@@ -466,8 +595,22 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
ref={viewportRef}
tabIndex={0}
onKeyDown={handleViewportKeyDown}
- onClick={handleViewportClick}
+ 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'
@@ -491,7 +634,9 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
/>
))}
- {currentScreenshot ? (
+ {showFullScreen ? (
+ <p className="text-center p-6 text-zinc-500 text-xs">Showing full screen</p>
+ ) : currentScreenshot ? (
<img
key={stream.frame?.id}
ref={imageRef}
@@ -564,6 +709,24 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
)}
</div>
+ {showFullScreen && (
+ <BrowserControlOverlay
+ botName={teamName}
+ pageUrl={pageUrl}
+ image={currentScreenshot ? (currentScreenshot.startsWith('data:') ? currentScreenshot : `data:image/jpeg;base64,${currentScreenshot}`) : null}
+ onFrameDone={() => {
+ if (stream.frame) stream.acknowledgeFrame(stream.frame.id);
+ }}
+ send={stream.send}
+ busy={isInteracting}
+ error={controlError ?? null}
+ tapFocus={stream.tapFocus}
+ captcha={captchaOpen ? { target: captchaStep?.target ?? null } : null}
+ solved={solvedNote}
+ onHandBack={handBack}
+ />
+ )}
+
{/* Footer Status */}
<div className="p-2.5 border-t border-zinc-800 bg-zinc-900/60 flex items-center justify-between text-[11px] text-zinc-400">
<div className="flex items-center gap-1.5" data-browser-footer>
diff --git a/frontend/src/humanSteps.ts b/frontend/src/humanSteps.ts
index d4dbb8ae..47736e15 100644
--- a/frontend/src/humanSteps.ts
+++ b/frontend/src/humanSteps.ts
@@ -4,7 +4,16 @@ import { parseMetaObject } from './questions';
import { request } from './threads';
export type HumanStepKind = 'sign_in' | 'captcha' | 'two_factor' | 'other';
-export type HumanStepStatus = 'open' | 'done' | 'declined' | 'cancelled';
+export type HumanStepStatus = 'open' | 'done' | 'declined' | 'cancelled' | 'resolved_auto' | 'timed_out';
+
+/** Where a CAPTCHA widget sits on the bot's page, in page pixels (1280×800). */
+export interface CaptchaTarget {
+ kind: string;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
export interface HumanStep {
id: string;
@@ -17,6 +26,8 @@ export interface HumanStep {
reason: string;
url: string | null;
sandbox_target: string | null;
+ /** CAPTCHA steps: the widget's box, while known. */
+ target?: CaptchaTarget | null;
source: 'bot' | 'auto';
status: HumanStepStatus;
message_id: string | null;
@@ -32,15 +43,26 @@ export interface HumanStepMeta {
reason: string;
url: string | null;
sandbox_target: string | null;
+ target: CaptchaTarget | null;
source: 'bot' | 'auto';
status: HumanStepStatus;
}
const STEP_KINDS: HumanStepKind[] = ['sign_in', 'captcha', 'two_factor', 'other'];
-const STATUSES: HumanStepStatus[] = ['open', 'done', 'declined', 'cancelled'];
+const STATUSES: HumanStepStatus[] = ['open', 'done', 'declined', 'cancelled', 'resolved_auto', 'timed_out'];
const kindOf = (v: unknown): HumanStepKind => (STEP_KINDS.includes(v as HumanStepKind) ? (v as HumanStepKind) : 'other');
const statusOf = (v: unknown): HumanStepStatus => (STATUSES.includes(v as HumanStepStatus) ? (v as HumanStepStatus) : 'open');
+/** A usable widget box (finite, non-empty), else null. */
+export function parseCaptchaTarget(raw: unknown): CaptchaTarget | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const t = raw as Record<string, unknown>;
+ const n = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : NaN);
+ const [x, y, width, height] = [n(t.x), n(t.y), n(t.width), n(t.height)];
+ if ([x, y, width, height].some(Number.isNaN) || width <= 0 || height <= 0) return null;
+ return { kind: typeof t.kind === 'string' ? t.kind : 'puzzle', x, y, width, height };
+}
+
export function parseHumanStepMeta(raw: unknown): HumanStepMeta | null {
const m = parseMetaObject(raw);
if (!m || m.kind !== 'human_step' || typeof m.human_step_id !== 'string') return null;
@@ -51,6 +73,7 @@ export function parseHumanStepMeta(raw: unknown): HumanStepMeta | null {
reason: typeof m.reason === 'string' ? m.reason : '',
url: typeof m.url === 'string' && m.url ? m.url : null,
sandbox_target: typeof m.sandbox_target === 'string' && m.sandbox_target ? m.sandbox_target : null,
+ target: parseCaptchaTarget(m.target),
source: m.source === 'auto' ? 'auto' : 'bot',
status: statusOf(m.status),
};
@@ -59,17 +82,47 @@ export function parseHumanStepMeta(raw: unknown): HumanStepMeta | null {
/** Card state: the live record from `human_step_updated` wins over the (possibly stale) meta. */
export function humanStepView(meta: HumanStepMeta, live?: HumanStep | null): HumanStepMeta {
if (!live || live.id !== meta.human_step_id) return meta;
- return { ...meta, status: live.status, url: live.url ?? meta.url, sandbox_target: live.sandbox_target ?? meta.sandbox_target };
+ return {
+ ...meta,
+ status: live.status,
+ url: live.url ?? meta.url,
+ sandbox_target: live.sandbox_target ?? meta.sandbox_target,
+ target: parseCaptchaTarget(live.target) ?? meta.target,
+ };
}
/** Keeps the latest known record per step; a closed step never reopens. */
export function applyHumanStep(map: Record<string, HumanStep>, s: HumanStep): Record<string, HumanStep> {
const prev = map[s.id];
- if (prev && prev.status === s.status) return map;
+ if (prev && prev.status === s.status && sameTarget(prev.target, s.target)) return map;
if (prev && prev.status !== 'open' && s.status === 'open') return map;
return { ...map, [s.id]: s };
}
+function sameTarget(a: CaptchaTarget | null | undefined, b: CaptchaTarget | null | undefined): boolean {
+ if (!a || !b) return !a === !b;
+ return a.kind === b.kind && a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
+}
+
+/**
+ * The CAPTCHA step to show over a bot browser: its newest open one, else the newest that closed
+ * in the last minute (so the view can say it was solved).
+ */
+export function captchaStepFor(map: Record<string, HumanStep>, sandboxId: string | undefined, now = Date.now()): HumanStep | null {
+ if (!sandboxId) return null;
+ let open: HumanStep | null = null;
+ let closed: HumanStep | null = null;
+ for (const s of Object.values(map)) {
+ if (s.kind !== 'captcha' || s.sandbox_target !== sandboxId) continue;
+ if (s.status === 'open') {
+ if (!open || s.created_at > open.created_at) open = s;
+ } else if (s.closed_at && now - Date.parse(s.closed_at) < 60_000 && (!closed || s.closed_at > (closed.closed_at ?? ''))) {
+ closed = s;
+ }
+ }
+ return open ?? closed;
+}
+
/** The chat a step lives in: the thread, else the channel, else the bot's direct chat. */
export const humanStepContextId = (s: Pick<HumanStep, 'thread_id' | 'channel_id' | 'direct_kwant_id'>) =>
s.thread_id || s.channel_id || s.direct_kwant_id || null;
diff --git a/frontend/src/useBrowserStream.ts b/frontend/src/useBrowserStream.ts
index cf8b7721..37011c73 100644
--- a/frontend/src/useBrowserStream.ts
+++ b/frontend/src/useBrowserStream.ts
@@ -12,6 +12,8 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {
const [error, setError] = useState<string | null>(null);
const [frame, setFrame] = useState<{ id: number; image: string } | 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);
useEffect(() => {
if (!id || id === 'default' || !visible) return;
@@ -35,7 +37,11 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {
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 'ack': pending.current.delete(message.id); setBusy(pending.current.size > 0); break;
+ case 'ack':
+ pending.current.delete(message.id);
+ setBusy(pending.current.size > 0);
+ if (typeof message.editable === 'boolean') setTapFocus({ seq: message.id, editable: message.editable });
+ break;
}
};
ws.onclose = () => {
@@ -62,9 +68,11 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {
setBusy(false);
setFrame(null);
setLocation(null);
+ setTapFocus(null);
};
}, [id, visible]);
+ /** `input` waits for the page's ack (shows busy); pointer moves don't, they're fire-and-forget. */
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; }
@@ -82,5 +90,5 @@ 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, send, acknowledgeFrame };
+ return { connected, controlling, busy, error, frame, location, tapFocus, send, acknowledgeFrame };
}
diff --git a/frontend/tests/browserGestures.test.mjs b/frontend/tests/browserGestures.test.mjs
new file mode 100644
index 00000000..05871bda
--- /dev/null
+++ b/frontend/tests/browserGestures.test.mjs
@@ -0,0 +1,211 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const g = await loadBundled(`export * from './src/browserGestures';`);
+const o = await loadBundled(`export { textEdits, sendPageInput } from './src/components/BrowserControlOverlay';`);
+
+const phone = { width: 390, height: 700 };
+
+test('fit: the page fills the width, top-aligned, no band above', () => {
+ const v = g.fitView(phone);
+ assert.equal(v.scale, 390 / 1280);
+ assert.equal(v.tx, 0);
+ assert.equal(v.ty, 0);
+ // Landscape: height limits, centred across
+ const l = g.fitView({ width: 844, height: 300 });
+ assert.equal(l.scale, 300 / 800);
+ assert.equal(l.tx, (844 - 1280 * l.scale) / 2);
+});
+
+test('clamp: never smaller than fit or past 4x, page edges stay on the stage', () => {
+ assert.equal(g.clampView({ scale: 0.01, tx: 50, ty: 50 }, phone).scale, 390 / 1280);
+ assert.equal(g.clampView({ scale: 10, tx: 0, ty: 0 }, phone).scale, g.MAX_SCALE);
+ const v = g.clampView({ scale: 1, tx: 100, ty: -5000 }, phone);
+ assert.equal(v.tx, 0);
+ assert.equal(v.ty, 700 - 800);
+});
+
+test('zoom to a box: it fills the stage with a margin, centred', () => {
+ const box = { x: 460, y: 180, width: 360, height: 380 };
+ const v = g.zoomToBox(box, phone);
+ assert.equal(v.scale, Math.min((390 - 32) / 360, (700 - 32) / 380));
+ const centre = { x: (box.x + box.width / 2) * v.scale + v.tx, y: (box.y + box.height / 2) * v.scale + v.ty };
+ assert.ok(Math.abs(centre.x - 195) < 1 && Math.abs(centre.y - 350) < 1, JSON.stringify(centre));
+ // Box corners are on screen
+ assert.ok(box.x * v.scale + v.tx >= 0 && (box.x + box.width) * v.scale + v.tx <= 390);
+ // A tiny box doesn't zoom past the max
+ assert.equal(g.zoomToBox({ x: 10, y: 10, width: 5, height: 5 }, phone).scale, g.MAX_SCALE);
+});
+
+test('stage ↔ page round-trips; off the page is null, clamped holds the edge', () => {
+ const v = { scale: 2, tx: -100, ty: -40 };
+ assert.deepEqual(g.stageToPage(2 * 510 - 100, 2 * 500 - 40, v), { x: 510, y: 500 });
+ assert.equal(g.stageToPage(10, 10, g.fitView(phone)) !== null, true);
+ assert.equal(g.stageToPage(10, 600, g.fitView(phone)), null);
+ assert.deepEqual(g.stageToPageClamped(-50, 9999, g.fitView(phone)), { x: 0, y: 799 });
+});
+
+test('pinch keeps the page point under the fingers', () => {
+ const start = { scale: 0.5, tx: 0, ty: 0 };
+ const v = g.pinchView(start, { x: 100, y: 100 }, { x: 200, y: 100 }, { x: 50, y: 100 }, { x: 250, y: 100 });
+ assert.equal(v.scale, 1);
+ // Midpoint 150,100 was page (300,200); still there
+ assert.equal(300 * v.scale + v.tx, 150);
+ assert.equal(200 * v.scale + v.ty, 100);
+});
+
+function harness({ zoomable = true, zoomed = false } = {}) {
+ const sent = [];
+ let t = 0;
+ const timers = [];
+ let view = { scale: 0.5, tx: 0, ty: 0 };
+ const host = {
+ toPage: (p) => g.stageToPage(p.x, p.y, view),
+ toPageClamped: (p) => g.stageToPageClamped(p.x, p.y, view),
+ send: (i) => sent.push(i),
+ now: () => t,
+ later: (fn, ms) => {
+ const timer = { at: t + ms, fn, live: true };
+ timers.push(timer);
+ return () => (timer.live = false);
+ },
+ };
+ if (zoomable) host.view = { get: () => view, set: (v) => (view = v), zoomed: () => zoomed };
+ const tick = (ms) => {
+ t += ms;
+ for (const tm of timers) if (tm.live && tm.at <= t) { tm.live = false; tm.fn(); }
+ };
+ return { tr: g.createGestureTracker(host), sent, tick, view: () => view };
+}
+
+test('a tap is one click at the page point', () => {
+ const { tr, sent } = harness();
+ tr.down(1, { x: 100, y: 50 });
+ tr.move(1, { x: 102, y: 51 });
+ tr.up(1, { x: 102, y: 51 });
+ assert.deepEqual(sent, [{ action: 'click', x: 204, y: 102 }]);
+});
+
+test('a drag presses at the start, moves at most every 16ms, flushes and releases', () => {
+ const { tr, sent, tick } = harness();
+ tr.down(1, { x: 255, y: 250 });
+ tick(5);
+ tr.move(1, { x: 265, y: 250 });
+ assert.deepEqual(sent[0], { action: 'pointer_down', x: 510, y: 500 });
+ // Many moves inside one interval: one goes out now or after the wait, with the newest point
+ for (let i = 1; i <= 5; i++) { tick(2); tr.move(1, { x: 265 + i * 10, y: 250 }); }
+ const movesBefore = sent.filter((e) => e.action === 'pointer_move').length;
+ tick(16);
+ const moves = sent.filter((e) => e.action === 'pointer_move');
+ assert.ok(moves.length <= movesBefore + 1 && moves.length <= 2, JSON.stringify(sent));
+ assert.deepEqual(moves.at(-1), { action: 'pointer_move', x: 630, y: 500 });
+ tr.move(1, { x: 400, y: 250 });
+ tr.up(1, { x: 400, y: 250 });
+ assert.deepEqual(sent.at(-2), { action: 'pointer_move', x: 800, y: 500 });
+ assert.deepEqual(sent.at(-1), { action: 'pointer_up', x: 800, y: 500 });
+ assert.ok(!sent.some((e) => e.action === 'click'));
+ assert.equal(tr.dragging(), false);
+});
+
+test('a drag that leaves the page keeps going, held at the edge', () => {
+ const { tr, sent } = harness();
+ tr.down(1, { x: 600, y: 10 });
+ tr.move(1, { x: 700, y: 10 });
+ tr.up(1, { x: 900, y: 10 });
+ assert.deepEqual(sent.at(-1), { action: 'pointer_up', x: 1279, y: 20 });
+});
+
+test('cancel releases a drag without a click; a cancelled press sends nothing', () => {
+ let h = harness();
+ h.tr.down(1, { x: 100, y: 100 });
+ h.tr.move(1, { x: 130, y: 100 });
+ h.tr.cancel(1);
+ assert.deepEqual(h.sent.map((e) => e.action), ['pointer_down', 'pointer_move', 'pointer_up']);
+ h = harness();
+ h.tr.down(1, { x: 100, y: 100 });
+ h.tr.cancel(1);
+ assert.deepEqual(h.sent, []);
+});
+
+test('two fingers spreading zoom the view and send nothing', () => {
+ const { tr, sent, view } = harness();
+ tr.down(1, { x: 100, y: 100 });
+ tr.down(2, { x: 200, y: 100 }, false);
+ tr.move(1, { x: 50, y: 100 });
+ tr.move(2, { x: 250, y: 100 });
+ tr.up(1);
+ tr.up(2);
+ assert.deepEqual(sent, []);
+ assert.equal(view().scale, 1);
+});
+
+test('two fingers moving up together scroll the page down (at fit)', () => {
+ const { tr, sent } = harness();
+ tr.down(1, { x: 100, y: 300 });
+ tr.down(2, { x: 200, y: 300 }, false);
+ tr.move(1, { x: 100, y: 260 });
+ tr.move(2, { x: 200, y: 260 });
+ tr.up(1);
+ tr.up(2);
+ const scrolls = sent.filter((e) => e.action === 'scroll');
+ assert.ok(scrolls.length >= 1, JSON.stringify(sent));
+ assert.ok(scrolls.every((s) => s.delta_y > 0));
+ assert.ok(!sent.some((e) => e.action === 'click'));
+});
+
+test('zoomed in, two fingers moving together pan the view instead', () => {
+ const { tr, sent, view } = harness({ zoomed: true });
+ tr.down(1, { x: 100, y: 300 });
+ tr.down(2, { x: 200, y: 300 }, false);
+ tr.move(1, { x: 100, y: 260 });
+ tr.move(2, { x: 200, y: 260 });
+ assert.deepEqual(sent, []);
+ assert.equal(view().ty, -40);
+});
+
+test('a finger added mid-drag is ignored; the drag ends cleanly', () => {
+ const { tr, sent } = harness();
+ tr.down(1, { x: 100, y: 100 });
+ tr.move(1, { x: 140, y: 100 });
+ tr.down(2, { x: 300, y: 300 }, false);
+ tr.move(2, { x: 340, y: 340 });
+ tr.up(2);
+ tr.up(1, { x: 160, y: 100 });
+ assert.deepEqual(sent.map((e) => e.action).filter((a) => a !== 'pointer_move'), ['pointer_down', 'pointer_up']);
+});
+
+test('a press that starts off the page does nothing', () => {
+ const { tr, sent } = harness();
+ tr.down(1, { x: 100, y: 600 });
+ tr.move(1, { x: 150, y: 600 });
+ tr.up(1);
+ assert.deepEqual(sent, []);
+});
+
+test('desktop (no zoom): two fingers always scroll', () => {
+ const { tr, sent } = harness({ zoomable: false });
+ tr.down(1, { x: 100, y: 300 });
+ tr.down(2, { x: 200, y: 300 }, false);
+ tr.move(1, { x: 60, y: 200 });
+ tr.move(2, { x: 240, y: 200 });
+ assert.ok(sent.some((e) => e.action === 'scroll'));
+});
+
+test('phone keyboard text becomes type and Backspace events (autocorrect replaces words)', () => {
+ assert.deepEqual(o.textEdits('', 'hi'), [{ action: 'type', text: 'hi' }]);
+ assert.deepEqual(o.textEdits('hi', 'h'), [{ action: 'key', key: 'Backspace' }]);
+ assert.deepEqual(o.textEdits('teh', 'the '), [{ action: 'key', key: 'Backspace' }, { action: 'key', key: 'Backspace' }, { action: 'type', text: 'he ' }]);
+ assert.deepEqual(o.textEdits('same', 'same'), []);
+});
+
+test('only moves skip the ack; non-scroll inputs carry zero deltas', () => {
+ const calls = [];
+ const send = (p, input) => calls.push([p, input]);
+ o.sendPageInput(send, { action: 'pointer_move', x: 1, y: 2 });
+ o.sendPageInput(send, { action: 'pointer_down', x: 1, y: 2 });
+ o.sendPageInput(send, { action: 'scroll', x: 1, y: 2, delta_x: 0, delta_y: 30 });
+ assert.deepEqual(calls.map((c) => c[1]), [false, true, true]);
+ assert.equal(calls[0][0].delta_x, 0);
+ assert.equal(calls[2][0].delta_y, 30);
+});
diff --git a/frontend/tests/humanSteps.test.mjs b/frontend/tests/humanSteps.test.mjs
index 7fef0870..3df3d28c 100644
--- a/frontend/tests/humanSteps.test.mjs
+++ b/frontend/tests/humanSteps.test.mjs
@@ -77,3 +77,42 @@ test('closed and stale cards', () => {
assert.match(ui.render(props({ waiting: false })), /stopped waiting/);
assert.match(ui.render(props({ meta: h.parseHumanStepMeta(meta({ source: 'auto' })) })), /spotted automatically/);
});
+
+test('captcha target: finite box only, kind defaults to puzzle', () => {
+ assert.deepEqual(h.parseCaptchaTarget({ x: 460, y: 180, width: 360, height: 380 }), { kind: 'puzzle', x: 460, y: 180, width: 360, height: 380 });
+ assert.equal(h.parseCaptchaTarget({ x: 1, y: 1, width: 0, height: 5 }), null);
+ assert.equal(h.parseCaptchaTarget({ x: 'a', y: 1, width: 5, height: 5 }), null);
+ assert.equal(h.parseCaptchaTarget(null), null);
+ const m = h.parseHumanStepMeta(meta({ step_kind: 'captcha', target: { kind: 'slider', x: 1, y: 2, width: 3, height: 4 } }));
+ assert.equal(m.target.kind, 'slider');
+ assert.equal(h.parseHumanStepMeta(meta({ status: 'resolved_auto' })).status, 'resolved_auto');
+ assert.equal(h.parseHumanStepMeta(meta({ status: 'timed_out' })).status, 'timed_out');
+});
+
+test('captcha step for a sandbox: open first, a just-closed one lingers a minute', () => {
+ const now = Date.parse('2026-10-22T12:00:00Z');
+ const box = { kind: 'puzzle', x: 1, y: 2, width: 30, height: 40 };
+ let map = h.applyHumanStep({}, rec({ id: 'c1', kind: 'captcha', sandbox_target: 'pixel', target: box }));
+ map = h.applyHumanStep(map, rec({ id: 's1', kind: 'sign_in', sandbox_target: 'pixel', created_at: '2026-10-22T11:59:00Z' }));
+ assert.equal(h.captchaStepFor(map, 'pixel', now).id, 'c1');
+ assert.equal(h.captchaStepFor(map, 'other', now), null);
+ // The box moves while the step stays open
+ map = h.applyHumanStep(map, rec({ id: 'c1', kind: 'captcha', sandbox_target: 'pixel', target: { ...box, x: 9 } }));
+ assert.equal(map.c1.target.x, 9);
+ map = h.applyHumanStep(map, rec({ id: 'c1', kind: 'captcha', sandbox_target: 'pixel', status: 'resolved_auto', closed_at: '2026-10-22T11:59:40Z' }));
+ assert.equal(h.captchaStepFor(map, 'pixel', now).status, 'resolved_auto');
+ assert.equal(h.captchaStepFor(map, 'pixel', now + 60_000), null);
+});
+
+test('captcha card: Solve it is the main button and opens solve mode; auto outcomes', () => {
+ const calls = [];
+ const cm = h.parseHumanStepMeta(meta({ step_kind: 'captcha' }));
+ const html = ui.render(props({ meta: cm, onOpenBrowser: (...a) => calls.push(a) }));
+ assert.match(html, /Solve it/);
+ assert.doesNotMatch(html, /Open browser/);
+ assert.match(html, /continues by itself/);
+ assert.equal((html.match(/<button/g) || []).length, 3);
+ assert.match(ui.render(props({ meta: cm, live: rec({ kind: 'captcha', status: 'resolved_auto' }) })), /Solved\. Pixel continues\./);
+ assert.match(ui.render(props({ meta: cm, live: rec({ kind: 'captcha', status: 'timed_out' }) })), /moved on without it/);
+ assert.doesNotMatch(ui.render(props({ meta: cm, live: rec({ kind: 'captcha', status: 'timed_out' }) })), /<button/);
+});
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index abb017af..6d2b878b 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -160,6 +160,24 @@ fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
std::fs::rename(&tmp, path)
}
+const FOCUSED_EDITABLE_JS: &str = r#"(() => {
+ let el = document.activeElement;
+ for (let i = 0; el && i < 8; i++) {
+ if (el.shadowRoot && el.shadowRoot.activeElement) { el = el.shadowRoot.activeElement; continue; }
+ if (el.tagName === 'IFRAME' || el.tagName === 'FRAME') {
+ try { const inner = el.contentDocument && el.contentDocument.activeElement; if (inner) { el = inner; continue; } } catch (e) {}
+ return false;
+ }
+ break;
+ }
+ if (!el) return false;
+ if (el.isContentEditable) return true;
+ if (el.tagName === 'TEXTAREA') return !el.readOnly && !el.disabled;
+ if (el.tagName !== 'INPUT') return false;
+ const t = (el.type || 'text').toLowerCase();
+ return !el.readOnly && !el.disabled && ['text','search','email','url','tel','password','number','date','datetime-local','month','time','week'].includes(t);
+})()"#;
+
/// Finds a visible CAPTCHA widget in the page (document, open shadow roots and same-origin
/// frames) and returns `{kind, x, y, width, height}` in viewport pixels, or null. Never scrolls:
/// a widget below the fold comes back with `offscreen: true` and no usable box.
@@ -962,6 +980,15 @@ impl BrowserController {
Ok(())
}
+ /// Whether the page's focused element takes typing (a text field or editable area), followed
+ /// into open shadow roots and same-origin frames. The live view opens the phone keyboard on it.
+ pub async fn focused_editable(&self) -> bool {
+ let Ok(res) = self.send_cdp_command("Runtime.evaluate", json!({
+ "expression": FOCUSED_EDITABLE_JS, "returnByValue": true
+ })).await else { return false };
+ res["result"]["value"].as_bool().unwrap_or(false)
+ }
+
/// A visible CAPTCHA widget on the page, if any. `Err` when the page couldn't be read
/// (mid-navigation, say): callers treat that as unknown, never as "gone".
pub async fn probe_captcha(&self) -> Result<Option<CaptchaHit>, BrowserError> {
diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rs
index fea63bcf..03477f98 100644
--- a/src/server/browser_stream.rs
+++ b/src/server/browser_stream.rs
@@ -213,8 +213,16 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
Err(_) => Err(BrowserError::Protocol("Invalid browser input".into())),
}
};
+ // After a tap, say whether it landed in a text field so a phone can open its keyboard
+ let editable = match (&result, value["action"].as_str().unwrap_or("")) {
+ (Ok(()), "click" | "pointer_up") => Some(ctrl.focused_editable().await),
+ _ => None,
+ };
send(&mut socket, match result {
- Ok(()) => json!({"type":"ack","id":value["id"]}),
+ Ok(()) => match editable {
+ Some(editable) => json!({"type":"ack","id":value["id"],"editable":editable}),
+ None => json!({"type":"ack","id":value["id"]}),
+ },
Err(error) => json!({"type":"error","id":value["id"],"error":error.to_string()}),
}).await?;
}
diff --git a/tests/browser_stream_test.rs b/tests/browser_stream_test.rs
index f022b27e..470a7c01 100644
--- a/tests/browser_stream_test.rs
+++ b/tests/browser_stream_test.rs
@@ -133,7 +133,10 @@ async fn stream_input_control_lease_and_origin_protection() {
for (i,payload) in [json!({"action":"click","x":50,"y":60}),json!({"action":"type","text":"abc"}),json!({"action":"key","key":"Enter","code":"Enter"})].into_iter().enumerate() {
let mut payload=payload; payload["id"]=json!(i);
ws.send(WsMessage::Text(payload.to_string())).await.unwrap();
- assert_eq!(receive(&mut ws,"ack").await["id"],i);
+ let ack=receive(&mut ws,"ack").await;
+ assert_eq!(ack["id"],i);
+ // a tap reports whether it focused a text field (the mock page has none); typing doesn't
+ if i==0 { assert_eq!(ack["editable"],false); } else { assert!(ack.get("editable").is_none()); }
}
let commands=mock.commands.lock().await.clone();
assert!(!commands.iter().any(|c|c["method"]=="Page.captureScreenshot"),"input must not wait for screenshots");
@@ -277,7 +280,10 @@ async fn live_chromium_stream_and_isolated_sessions() {
for (index, mut input) in inputs.into_iter().enumerate() {
input["id"] = json!(index);
ws.send(WsMessage::Text(input.to_string())).await.unwrap();
- assert_eq!(receive(&mut ws, "ack").await["id"], index);
+ let ack = receive(&mut ws, "ack").await;
+ assert_eq!(ack["id"], index);
+ // the first tap lands in the text field, the last on a button
+ match index { 0 => assert_eq!(ack["editable"], true), 2 => assert_eq!(ack["editable"], false), _ => {} }
}
let elapsed = start.elapsed();
let result = ctrl.send_cdp_command("Runtime.evaluate", json!({"expression":"({value:document.querySelector('#field').value,title:document.title})","returnByValue":true})).await.unwrap();
diff --git a/tests/captcha_ui_harness.rs b/tests/captcha_ui_harness.rs
new file mode 100644
index 00000000..bdf8b42e
--- /dev/null
+++ b/tests/captcha_ui_harness.rs
@@ -0,0 +1,127 @@
+//! A live kwant for checking the CAPTCHA hand-off in a real browser (Playwright, or by hand on a
+//! phone): a windowless Chrome as the bot browser, the UI from `frontend/dist`, and a bot whose
+//! turn lands on the local TikTok-style slider fixture, so a captcha step with a box is open.
+//!
+//! Opt in: build the frontend, then
+//! `KWNT_UI_HARNESS_DIR=/tmp/harness cargo test --test captcha_ui_harness -- --ignored --nocapture`.
+//! It writes `ready.json` ({url, bot_id, bot_name}) to that folder. Each `rearm-<n>` file put
+//! there starts a new turn that opens the slider again; a `stop` file (or 20 minutes) ends it.
+
+#[path = "support/chrome_guard.rs"]
+mod chrome_guard;
+use axum::{
+ body::{to_bytes, Body},
+ http::Request,
+ Router,
+};
+use chrome_guard::ChromeGuard;
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{spaces::SpaceId, Database},
+ router::LayaRouter,
+ sandbox::computer,
+ server::{
+ continuity::{SelfScope, TurnOrigin},
+ create_router, mcp_runtime, AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::{
+ collections::HashSet,
+ path::{Path, PathBuf},
+ time::{Duration, Instant},
+};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tower::ServiceExt;
+
+/// Serves `tests/fixtures/captcha/<name>` on 127.0.0.1.
+async fn serve_fixtures() -> String {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/captcha");
+ tokio::spawn(async move {
+ while let Ok((mut stream, _)) = listener.accept().await {
+ let dir = dir.clone();
+ tokio::spawn(async move {
+ let mut buf = [0u8; 4096];
+ let n = stream.read(&mut buf).await.unwrap_or(0);
+ let request = String::from_utf8_lossy(&buf[..n]);
+ let path = request.split_whitespace().nth(1).unwrap_or("/").trim_start_matches('/').to_string();
+ let body = if path.contains("..") || path.contains('/') { None } else { std::fs::read_to_string(dir.join(&path)).ok() };
+ let (status, body) = match body { Some(b) => ("200 OK", b), None => ("404 Not Found", String::new()) };
+ let reply = format!("HTTP/1.1 {status}\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len());
+ let _ = stream.write_all(reply.as_bytes()).await;
+ });
+ }
+ });
+ format!("http://127.0.0.1:{port}/")
+}
+
+async fn turn(state: &AppState, turn_id: &str) -> String {
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);
+ let scope = SelfScope {
+ kwant_id: bot.id.clone(),
+ kwant_name: bot.name.clone(),
+ origin: Some(TurnOrigin { direct_kwant_id: Some(bot.id.clone()), ..Default::default() }),
+ cancel: Some(tokio_util::sync::CancellationToken::new()),
+ turn_id: Some(turn_id.into()),
+ sandbox_target: Some(bot.id.clone()),
+ ..Default::default()
+ };
+ mcp_runtime::prepare_turn_with_self(state, &bot, Some(turn_id.into()), None, Some(scope)).await.unwrap().1
+}
+
+/// The bot opens the slider page, as the CLI would mid-turn; the result is logged when the turn resumes.
+fn open_slider(app: &Router, token: String, url: String, label: String) {
+ let app = app.clone();
+ tokio::spawn(async move {
+ let body = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "browser_open", "arguments": {"url": url}}});
+ let req = Request::builder().method("POST").uri("/api/mcp/self").header("content-type", "application/json")
+ .header("authorization", format!("Bearer {token}")).body(Body::from(body.to_string())).unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ let v: Value = serde_json::from_slice(&to_bytes(resp.into_body(), usize::MAX).await.unwrap()).unwrap_or_default();
+ let text = v["result"]["content"][0]["text"].as_str().unwrap_or("").chars().take(160).collect::<String>();
+ eprintln!("harness: {label} resumed: {text}");
+ });
+}
+
+#[tokio::test(flavor = "multi_thread")]
+#[ignore = "manual: a live UI for Playwright or a phone; see the file comment"]
+async fn captcha_handoff_ui_harness() {
+ let dir = PathBuf::from(std::env::var("KWNT_UI_HARNESS_DIR").expect("set KWNT_UI_HARNESS_DIR"));
+ std::fs::create_dir_all(&dir).unwrap();
+ let tmp = tempfile::tempdir().unwrap();
+ let profile = tmp.path().join("chrome");
+ let (endpoint, _) = computer::ensure_local_chrome(&profile, true).await.expect("Chrome starts");
+ let _chrome = ChromeGuard(profile);
+ std::env::set_var("KWNT_COMPUTER_MODE", "vm");
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), browser_cdp_url: Some(endpoint), ..Config::default() };
+ let state = AppState::new(config.clone(), db, ToolRunner::new(tmp.path().join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url));
+ state.human_steps.set_captcha_timing(Duration::from_secs(600), Duration::from_millis(1000));
+ let app = create_router(state.clone());
+ let port: u16 = std::env::var("KWNT_UI_HARNESS_PORT").ok().and_then(|p| p.parse().ok()).unwrap_or(8846);
+ let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.unwrap();
+ let serve = app.clone();
+ tokio::spawn(async move { axum::serve(listener, serve).await.unwrap() });
+ let fixtures = serve_fixtures().await;
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);
+ let slider = format!("{fixtures}tiktok_slider.html");
+ open_slider(&app, turn(&state, "harness-0").await, slider.clone(), "turn 0".into());
+ std::fs::write(dir.join("ready.json"), json!({"url": format!("http://127.0.0.1:{port}/"), "bot_id": bot.id, "bot_name": bot.name, "fixture": slider}).to_string()).unwrap();
+ eprintln!("harness: http://127.0.0.1:{port}/ bot {} ({})", bot.name, bot.id);
+
+ let started = Instant::now();
+ let mut armed = HashSet::new();
+ while started.elapsed() < Duration::from_secs(20 * 60) && !dir.join("stop").exists() {
+ for entry in std::fs::read_dir(&dir).unwrap().flatten() {
+ let name = entry.file_name().to_string_lossy().to_string();
+ if name.starts_with("rearm-") && armed.insert(name.clone()) {
+ open_slider(&app, turn(&state, &format!("harness-{name}")).await, slider.clone(), name);
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ }
+}