Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(browser): interaction verbs — click, type, press, scroll, wait

Claude Code96f43fef9e03
diff --git a/src/main/browser-actions.ts b/src/main/browser-actions.ts
index 395d6fcfb..90648fa74 100644
--- a/src/main/browser-actions.ts
+++ b/src/main/browser-actions.ts
@@ -20,8 +20,8 @@
* proteus-dev); the nav/read shape here is new.
*/
import { NT_SCRIPTS } from './browser-nt-scripts'
-import type { RefTable } from './browser-refs'
-import type { BrowserReadMode } from '../core/browser-verb'
+import type { RefTable, RefItem } from './browser-refs'
+import type { BrowserReadMode, BrowserKey } from '../core/browser-verb'
/** A one-line agent-facing outcome. `ok:false` is a NAMED refusal, never a hang and never a raw
* Electron error. */
@@ -35,6 +35,24 @@ export interface Sendable {
send(method: string, params: object): Promise<unknown>
}
+/** The page geometry `Page.getLayoutMetrics` reports: the visible viewport (what bounds a pointer
+ * coordinate), the current scroll offset, and the full content size (what `--scroll` reads back). */
+export interface LayoutMetrics {
+ width: number
+ height: number
+ scrollX: number
+ scrollY: number
+ contentWidth: number
+ contentHeight: number
+}
+
+/** The extra capability the POINTER verbs (`--click`, `--type`, `--scroll`) need beyond {@link Sendable}:
+ * measure + cache the viewport so a synthesized coordinate validates against the REAL page, not the
+ * 0×0 placeholder. A {@link import('./browser-lease').BrowserSession} implements it. */
+export interface Driver extends Sendable {
+ refreshViewport(): Promise<LayoutMetrics>
+}
+
/** The `--read text` hard ceiling and default; the parser clamps `--max` to the ceiling too. */
export const READ_TEXT_DEFAULT_MAX = 20_000
export const READ_TEXT_CEILING = 60_000
@@ -296,6 +314,266 @@ export async function browserReadText(
return { ok: true, message: text }
}
+// ── Interaction (PR 8): --click, --type, --press, --scroll, --wait ──────────────────────────────
+//
+// Every effect below is a real CDP event through the ONE gated `send` — a bounded mouse event, a
+// capped insertText, a fixed-table key event — never page-side JS: the NT_SCRIPTS this path calls
+// (resolveRef/resolveSelector/activeField/isVisible) are PURE READERS that only report coordinates and
+// visibility, and every actual effect goes through Input.* so it is bounded by the allowlist AND
+// traceable. Agent-supplied text is DATA (Input.insertText), and a key is one of a fixed table.
+//
+// The CDP child-session/wheel bookkeeping this leans on is lifted from PR #112's S8 (@Corvin,
+// proteus-dev); the verb shapes and the read-back replies here are new.
+
+/** The fixed key table `--press` maps onto (Task 8.3). A key outside {@link BrowserKey} never reaches
+ * here — the verb parser and the allowlist both gate on the same `BROWSER_KEYS` set — so this is a
+ * total map, not a lookup that can miss. */
+const KEY_TABLE: Record<BrowserKey, { key: string; code: string; windowsVirtualKeyCode: number }> = {
+ Enter: { key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 },
+ Tab: { key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 },
+ Escape: { key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 },
+ Backspace: { key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 },
+ ArrowUp: { key: 'ArrowUp', code: 'ArrowUp', windowsVirtualKeyCode: 38 },
+ ArrowDown: { key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40 },
+ ArrowLeft: { key: 'ArrowLeft', code: 'ArrowLeft', windowsVirtualKeyCode: 37 },
+ ArrowRight: { key: 'ArrowRight', code: 'ArrowRight', windowsVirtualKeyCode: 39 },
+ PageUp: { key: 'PageUp', code: 'PageUp', windowsVirtualKeyCode: 33 },
+ PageDown: { key: 'PageDown', code: 'PageDown', windowsVirtualKeyCode: 34 },
+ Home: { key: 'Home', code: 'Home', windowsVirtualKeyCode: 36 },
+ End: { key: 'End', code: 'End', windowsVirtualKeyCode: 35 }
+}
+
+/** `--press --times` is capped so a single verb cannot fire an unbounded keystroke storm. */
+const PRESS_MAX_TIMES = 50
+/** The poll interval `--wait` uses on OUR clock (never a page timer). */
+const WAIT_POLL_MS = 150
+
+/** A one-line, value-free description of a minted map item for a reply: `input#email` for a field
+ * (its identity, never its value), `button "Sign in"` for a control (role + accessible name). */
+function describeItem(it: RefItem): string {
+ const tag = typeof it.tag === 'string' ? it.tag : ''
+ if (tag === 'input' || tag === 'textarea' || tag === 'select') {
+ const id = typeof it.id === 'string' && it.id ? `#${it.id}` : ''
+ return `${tag}${id}`
+ }
+ const role = (typeof it.role === 'string' && it.role) || tag || 'element'
+ const name = (typeof it.name === 'string' ? it.name : '').replace(/\s+/g, ' ').trim()
+ return name ? `${role} ${JSON.stringify(name)}` : role
+}
+
+type Resolved =
+ | { ok: true; x: number; y: number; desc: string }
+ | { ok: false; message: string }
+
+/**
+ * Resolve a `@ref` OR a raw CSS selector to CURRENT viewport-centre coordinates plus a value-free
+ * description. A `@ref` is SPENT through the RefTable (node- and generation-scoped): a stale ref — the
+ * page navigated since the map that minted it — is a REFUSAL, never a re-resolution against a newer
+ * map (the PR 5 correctness property). A selector is resolved live. Coordinates come from a pure
+ * reader (getBoundingClientRect), never from the agent.
+ */
+async function resolveTarget(s: Sendable, refs: RefTable, nodeId: string, target: string): Promise<Resolved> {
+ if (target.startsWith('@')) {
+ const res = refs.spend(nodeId, target)
+ if (!res.ok) return { ok: false, message: res.message }
+ const item = res.item
+ const idx = typeof item.ref === 'number' ? item.ref : Number(item.ref)
+ const coords = (await callReader(s, NT_SCRIPTS.resolveRef, [idx])) as { x?: unknown; y?: unknown } | null
+ if (!coords || typeof coords.x !== 'number' || typeof coords.y !== 'number') {
+ return { ok: false, message: `browser: ${target} (${describeItem(item)}) is no longer on ${nodeId} — re-read the map` }
+ }
+ return { ok: true, x: coords.x, y: coords.y, desc: `${target} (${describeItem(item)})` }
+ }
+ const coords = (await callReader(s, NT_SCRIPTS.resolveSelector, [target])) as { x?: unknown; y?: unknown; tag?: unknown } | null
+ if (!coords || typeof coords.x !== 'number' || typeof coords.y !== 'number') {
+ return { ok: false, message: `browser: nothing matches ${target} on ${nodeId}` }
+ }
+ const tag = typeof coords.tag === 'string' ? coords.tag.toLowerCase() : 'element'
+ return { ok: true, x: coords.x, y: coords.y, desc: `${target} (${tag})` }
+}
+
+/** Inside the last-measured viewport? A coordinate off-screen is either a bug or an attempt to reach
+ * chrome the user cannot see; the allowlist enforces this independently, this gives a clear message. */
+function inViewport(x: number, y: number, m: LayoutMetrics): boolean {
+ return x >= 0 && y >= 0 && x <= m.width && y <= m.height
+}
+
+/** A synthesized left click: press then release at (x, y). Both events are bounded by the allowlist. */
+async function dispatchClick(s: Sendable, x: number, y: number): Promise<void> {
+ const at = { x, y, button: 'left', clickCount: 1 }
+ await s.send('Input.dispatchMouseEvent', { type: 'mousePressed', buttons: 1, ...at })
+ await s.send('Input.dispatchMouseEvent', { type: 'mouseReleased', buttons: 0, ...at })
+}
+
+/**
+ * `--click <ref|selector>` (Task 8.1). Resolve the handle to a current centre, refresh the viewport,
+ * refuse an off-screen target, then dispatch a bounded left click. Reply names WHAT was clicked, never
+ * a coordinate: `clicked @7 (button "Sign in") on browser-3`.
+ */
+export async function browserClick(s: Driver, refs: RefTable, nodeId: string, target: string): Promise<ActionResult> {
+ const t = await resolveTarget(s, refs, nodeId, target)
+ if (!t.ok) return { ok: false, message: t.message }
+ const m = await s.refreshViewport()
+ if (!inViewport(t.x, t.y, m)) {
+ return { ok: false, message: `browser: ${t.desc} is off-screen on ${nodeId} — scroll it into view first` }
+ }
+ await dispatchClick(s, t.x, t.y)
+ return { ok: true, message: `clicked ${t.desc} on ${nodeId}` }
+}
+
+/**
+ * `--type <text>` with `--into <ref|selector>` and `--clear true` (Task 8.2). The text is DATA: it goes
+ * to `Input.insertText` and is NEVER echoed in the reply — the reply says how MANY characters, not
+ * which. With `--into`, the field is focused the way a user would (a click); without it, an already
+ * focused editable field is typed into, and nothing focused is a NAMED refusal. `--clear` selects the
+ * field (a fixed editing command) so the insert replaces it.
+ */
+export async function browserType(
+ s: Driver,
+ refs: RefTable,
+ nodeId: string,
+ opts: { text: string; into?: string; clear: boolean }
+): Promise<ActionResult> {
+ const { text, into, clear } = opts
+ let desc: string
+ if (into) {
+ const t = await resolveTarget(s, refs, nodeId, into)
+ if (!t.ok) return { ok: false, message: t.message }
+ const m = await s.refreshViewport()
+ if (!inViewport(t.x, t.y, m)) {
+ return { ok: false, message: `browser: ${t.desc} is off-screen on ${nodeId} — scroll it into view first` }
+ }
+ await dispatchClick(s, t.x, t.y) // focus the field the way a user does
+ desc = t.desc
+ } else {
+ const active = (await callReader(s, NT_SCRIPTS.activeField)) as { tag?: unknown; id?: unknown } | null
+ if (!active || typeof active.tag !== 'string') {
+ return { ok: false, message: 'browser: --type needs --into, or a focused field (nothing is focused)' }
+ }
+ const id = typeof active.id === 'string' && active.id ? `#${active.id}` : ''
+ desc = `the focused ${active.tag}${id}`
+ }
+ if (clear) {
+ await s.send('Input.dispatchKeyEvent', { type: 'keyDown', commands: ['selectAll'] })
+ if (text === '') await s.send('Input.dispatchKeyEvent', { type: 'keyDown', commands: ['deleteBackward'] })
+ }
+ if (text !== '') await s.send('Input.insertText', { text })
+ if (text === '' && clear) return { ok: true, message: `cleared ${desc} on ${nodeId}` }
+ // The character COUNT only — never the characters themselves.
+ return { ok: true, message: `typed ${text.length} chars into ${desc} on ${nodeId}` }
+}
+
+/**
+ * `--press <key>` with `--times <n>` (Task 8.3). The key is one of the fixed {@link KEY_TABLE} entries
+ * (`--enter true` is not expressible under the old shim loop, and no real form is fillable without
+ * Enter/Tab); each press is a keyDown+keyUp, repeated up to a capped count.
+ */
+export async function browserPress(s: Sendable, nodeId: string, key: BrowserKey, times: number): Promise<ActionResult> {
+ const n = Math.min(Math.max(Math.floor(times) || 1, 1), PRESS_MAX_TIMES)
+ const spec = KEY_TABLE[key]
+ for (let i = 0; i < n; i++) {
+ await s.send('Input.dispatchKeyEvent', { type: 'keyDown', ...spec })
+ await s.send('Input.dispatchKeyEvent', { type: 'keyUp', ...spec })
+ }
+ return { ok: true, message: `pressed ${key}${n > 1 ? ` x${n}` : ''} on ${nodeId}` }
+}
+
+/**
+ * The wheel delta for a `--scroll` target. `down`/`up` move ~90% of a viewport; `top`/`bottom` move to
+ * the edge from the current offset; a signed pixel count is taken literally (positive = down).
+ *
+ * [UNVERIFIED] 1 — the wheel-translation salvage (Task 8.4). S8 could not scroll a `<webview>` with
+ * `Input.synthesizeScrollGesture` (Electron acknowledged the synthetic gesture without scrolling) and
+ * translated it into an `Input.dispatchMouseEvent { type:'mouseWheel', deltaY }`. We author the wheel
+ * delta directly in the DOM wheel convention (positive deltaY scrolls the page DOWN — scrollY grows),
+ * so the sign is NOT the gesture-distance inversion S8 warned about. This was NOT re-measured against a
+ * real Electron 42.8.1 `<webview>` in the implementation environment (headless, no display — the same
+ * reason the reader end-to-end harness is deferred, see the file header); the mitigation is that the
+ * reply ALWAYS reads the scroll position back from `Page.getLayoutMetrics`, so a wrong sign or a
+ * command that silently does nothing shows up as a 0px / opposite-direction delta the agent can see.
+ * See docs/superpowers/probes/2026-08-browser-scroll.md.
+ */
+function scrollDeltaY(where: string, m: LayoutMetrics): number {
+ const page = Math.round(m.height * 0.9)
+ switch (where) {
+ case 'down':
+ return page
+ case 'up':
+ return -page
+ case 'top':
+ return -Math.round(m.scrollY)
+ case 'bottom':
+ return Math.round(m.contentHeight - m.height - m.scrollY)
+ default: {
+ const n = Number.parseInt(where, 10)
+ return Number.isFinite(n) ? n : 0
+ }
+ }
+}
+
+/**
+ * `--scroll <where>` (Task 8.4). Measure, dispatch one bounded `mouseWheel` at the viewport centre,
+ * then RE-READ `Page.getLayoutMetrics` and report the ACTUAL delta and position:
+ * `scrolled browser-3 down 600px (at 1200/4400)`. The reply is built from the measured movement, never
+ * the requested delta, because the worst failure shape here is a command that succeeds and does
+ * nothing — and a requested-delta reply would hide exactly that (it shows as `0px`).
+ */
+export async function browserScroll(s: Driver, nodeId: string, where: string): Promise<ActionResult> {
+ const before = await s.refreshViewport()
+ const deltaY = scrollDeltaY(where, before)
+ const cx = Math.floor(before.width / 2)
+ const cy = Math.floor(before.height / 2)
+ await s.send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: cx, y: cy, deltaX: 0, deltaY })
+ const after = await s.refreshViewport()
+ const moved = Math.round(after.scrollY - before.scrollY)
+ const posPart = `(at ${Math.round(after.scrollY)}/${Math.round(after.contentHeight)})`
+ const movePart = moved === 0 ? '0px' : `${moved > 0 ? 'down' : 'up'} ${Math.abs(moved)}px`
+ return { ok: true, message: `scrolled ${nodeId} ${movePart} ${posPart}` }
+}
+
+/**
+ * `--wait <ref|selector>` with `--timeout` (Task 8.5). Polls on OUR OWN clock — a `@ref`'s element
+ * re-resolving, or a selector reporting visible — so the trace shows a verb that says what it is
+ * waiting for, instead of every agent hand-rolling a poll loop out of `--read`. Reply names the wait
+ * and how long it took; a timeout is a NAMED refusal. Clock/sleep are injected for deterministic tests.
+ */
+export async function browserWait(
+ s: Sendable,
+ refs: RefTable,
+ nodeId: string,
+ target: string,
+ timeoutMs: number,
+ opts: { now?: () => number; sleep?: (ms: number) => Promise<void> } = {}
+): Promise<ActionResult> {
+ const now = opts.now ?? Date.now
+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))
+ const start = now()
+ const probe = async (): Promise<boolean> => {
+ try {
+ if (target.startsWith('@')) {
+ const res = refs.spend(nodeId, target)
+ if (!res.ok) return false
+ const idx = typeof res.item.ref === 'number' ? res.item.ref : Number(res.item.ref)
+ const c = (await callReader(s, NT_SCRIPTS.resolveRef, [idx])) as { x?: unknown } | null
+ return !!c && typeof c.x === 'number'
+ }
+ return (await callReader(s, NT_SCRIPTS.isVisible, [target])) === true
+ } catch {
+ // A transient read failure (e.g. mid-navigation) is "not yet", never an abort of the wait.
+ return false
+ }
+ }
+ for (;;) {
+ if (await probe()) {
+ return { ok: true, message: `${target} appeared on ${nodeId} after ${now() - start}ms` }
+ }
+ if (now() - start >= timeoutMs) {
+ return { ok: false, message: `browser: ${target} did not appear on ${nodeId} within ${timeoutMs}ms` }
+ }
+ await sleep(Math.min(WAIT_POLL_MS, Math.max(1, timeoutMs - (now() - start))))
+ }
+}
+
/** Dispatch the `--read <mode>` family. */
export async function browserRead(
s: Sendable,
diff --git a/src/main/browser-drive.ts b/src/main/browser-drive.ts
index fb5b3e6b9..3412051a0 100644
--- a/src/main/browser-drive.ts
+++ b/src/main/browser-drive.ts
@@ -30,7 +30,19 @@ import {
} from './browser-control-ledger'
import { STRICT_CONTROL_REFUSAL } from '../core/agents/node-identity-policy'
import { browserDiscardedMessage } from './browser-guest-registry'
-import { browserNav, browserRead, type ActionResult, type Sendable, type CdpEventBus } from './browser-actions'
+import {
+ browserNav,
+ browserRead,
+ browserClick,
+ browserType,
+ browserPress,
+ browserScroll,
+ browserWait,
+ type ActionResult,
+ type Sendable,
+ type Driver,
+ type CdpEventBus
+} from './browser-actions'
import type { RefTable } from './browser-refs'
import type { BrowserCall } from '../core/browser-verb'
@@ -154,6 +166,8 @@ async function runAction(
nodeId: string
): Promise<ActionResult> {
const a = call.action
+ // The pointer verbs need the viewport-refreshing capability; the session is a Driver at runtime.
+ const driver = guest.session as Driver
switch (a.kind) {
case 'nav':
return browserNav(guest.session, guest.bus, nodeId, a.url, call.timeoutMs)
@@ -162,9 +176,19 @@ async function runAction(
selector: call.selector,
max: call.max
})
+ case 'click':
+ return browserClick(driver, refs, nodeId, a.target)
+ case 'type':
+ return browserType(driver, refs, nodeId, { text: a.text, into: call.into, clear: call.clear })
+ case 'press':
+ return browserPress(guest.session, nodeId, a.key, call.times ?? 1)
+ case 'scroll':
+ return browserScroll(driver, nodeId, a.where)
+ case 'wait':
+ return browserWait(guest.session, refs, nodeId, a.target, call.timeoutMs)
default:
- // Interaction (PR 8) and cookies/screenshot (PR 9) parse today but do not drive yet: a NAMED,
- // non-retryable refusal, never a silent success.
+ // cookies/screenshot (PR 9) parse today but do not drive yet: a NAMED, non-retryable refusal,
+ // never a silent success.
return { ok: false, message: `browser: --${a.kind} is not available yet (it lands in a later update)` }
}
}
diff --git a/src/main/browser-interaction.test.ts b/src/main/browser-interaction.test.ts
new file mode 100644
index 000000000..8de4b798d
--- /dev/null
+++ b/src/main/browser-interaction.test.ts
@@ -0,0 +1,327 @@
+import { describe, it, expect } from 'vitest'
+import { BrowserSession } from './browser-lease'
+import type { DebuggerLike } from './browser-cdp-send'
+import type { CdpContext } from './browser-cdp-allowlist'
+import { NT_SCRIPTS } from './browser-nt-scripts'
+import { RefTable, type RefItem } from './browser-refs'
+import {
+ browserClick,
+ browserType,
+ browserPress,
+ browserScroll,
+ browserWait,
+ browserReadMap,
+ type Driver
+} from './browser-actions'
+
+/**
+ * The PR 8 interaction verbs, driven through the REAL production stack — a real {@link BrowserSession},
+ * real `sendCdp`, the real CDP allowlist and the real frozen NT_SCRIPTS — against a fake
+ * `webContents.debugger` that returns canned page data and applies a wheel event to a mutable scroll
+ * offset. So EVERY command an action issues actually passes the allowlist gate: a method that were not
+ * allowlisted, or a bad-params send, would reject and fail the test. That is the security spine under
+ * test — the same one PR 7 established — and the click/type/press/scroll verbs all drive through it.
+ *
+ * The readers' in-page behaviour (a real <webview>) is deferred with the rest of the pointer harness
+ * (Global Constraint 8) — headless, no display; see the --scroll probe doc.
+ */
+
+interface FakePage {
+ width: number
+ height: number
+ scrollY: number
+ contentHeight: number
+ refCoords: Record<number, { x: number; y: number; tag: string } | null>
+ selectorCoords: Record<string, { x: number; y: number; tag: string } | null>
+ activeField: { tag: string; id: string } | null
+ visible: Record<string, boolean>
+ mapItems: RefItem[]
+}
+
+class FakeDebugger implements DebuggerLike {
+ attached = false
+ attachCount = 0
+ sends: { method: string; params: Record<string, unknown> }[] = []
+ private det: ((e: unknown, reason: string) => void)[] = []
+
+ constructor(public page: FakePage) {}
+
+ isAttached(): boolean {
+ return this.attached
+ }
+ attach(): void {
+ this.attached = true
+ this.attachCount++
+ }
+ detach(): void {
+ this.attached = false
+ for (const f of this.det) f({}, 'user')
+ }
+ on(event: 'detach' | 'message', listener: never): void {
+ if (event === 'detach') this.det.push(listener)
+ }
+ async sendCommand(method: string, params: object = {}): Promise<unknown> {
+ const p = params as Record<string, unknown>
+ this.sends.push({ method, params: p })
+ switch (method) {
+ case 'Page.getLayoutMetrics':
+ return {
+ cssLayoutViewport: { clientWidth: this.page.width, clientHeight: this.page.height },
+ cssVisualViewport: { clientWidth: this.page.width, clientHeight: this.page.height, pageX: 0, pageY: this.page.scrollY },
+ cssContentSize: { width: this.page.width, height: this.page.contentHeight }
+ }
+ case 'DOM.getDocument':
+ return { root: { nodeId: 1 } }
+ case 'DOM.resolveNode':
+ return { object: { objectId: 'doc-obj' } }
+ case 'Runtime.callFunctionOn':
+ return { result: { value: this.evalReader(p) } }
+ case 'Input.dispatchMouseEvent': {
+ if (p.type === 'mouseWheel') {
+ const max = Math.max(0, this.page.contentHeight - this.page.height)
+ this.page.scrollY = Math.min(Math.max(0, this.page.scrollY + (p.deltaY as number)), max)
+ }
+ return {}
+ }
+ default:
+ return {}
+ }
+ }
+
+ private evalReader(p: Record<string, unknown>): unknown {
+ const fn = p.functionDeclaration
+ const args = (p.arguments as { value: unknown }[] | undefined) ?? []
+ if (fn === NT_SCRIPTS.readMap) return this.page.mapItems
+ if (fn === NT_SCRIPTS.resolveRef) return this.page.refCoords[args[0]?.value as number] ?? null
+ if (fn === NT_SCRIPTS.resolveSelector) return this.page.selectorCoords[args[0]?.value as string] ?? null
+ if (fn === NT_SCRIPTS.activeField) return this.page.activeField
+ if (fn === NT_SCRIPTS.isVisible) return this.page.visible[args[0]?.value as string] === true
+ return null
+ }
+}
+
+const NODE = 'browser-3'
+
+function basePage(over: Partial<FakePage> = {}): FakePage {
+ return {
+ width: 1000,
+ height: 800,
+ scrollY: 0,
+ contentHeight: 4400,
+ refCoords: {},
+ selectorCoords: {},
+ activeField: null,
+ visible: {},
+ mapItems: [],
+ ...over
+ }
+}
+
+function make(page: FakePage): { s: Driver; dbg: FakeDebugger; refs: RefTable } {
+ const dbg = new FakeDebugger(page)
+ // The injected viewport is the 0×0 placeholder — refreshViewport() must override it, exactly as in
+ // production. If it did not, every bounded click would be refused.
+ const viewport = (): CdpContext => ({ viewport: { width: 0, height: 0 } })
+ const session = new BrowserSession({ nodeId: NODE, debugger: dbg, viewport })
+ return { s: session as unknown as Driver, dbg, refs: new RefTable() }
+}
+
+const mouseEvents = (dbg: FakeDebugger): Record<string, unknown>[] =>
+ dbg.sends.filter((x) => x.method === 'Input.dispatchMouseEvent').map((x) => x.params)
+const keyEvents = (dbg: FakeDebugger): Record<string, unknown>[] =>
+ dbg.sends.filter((x) => x.method === 'Input.dispatchKeyEvent').map((x) => x.params)
+
+const MAP = [
+ { ref: 0, tag: 'button', role: 'button', id: '', type: null, name: 'Sign in', href: null, filled: null },
+ { ref: 1, tag: 'input', role: 'input', id: 'email', type: 'email', name: '', href: null, filled: false }
+] as RefItem[]
+
+// ── 8.1 --click ─────────────────────────────────────────────────────────────────────────────────
+describe('--click', () => {
+ it('clicks a @ref at its current centre and names WHAT was clicked (not a coordinate)', async () => {
+ const page = basePage({ mapItems: MAP, refCoords: { 0: { x: 500, y: 100, tag: 'BUTTON' } } })
+ const { s, dbg, refs } = make(page)
+ await browserReadMap(s, refs, NODE) // mint @1,@2
+ const r = await browserClick(s, refs, NODE, '@1')
+ expect(r).toEqual({ ok: true, message: 'clicked @1 (button "Sign in") on browser-3' })
+ const me = mouseEvents(dbg)
+ expect(me.map((e) => e.type)).toEqual(['mousePressed', 'mouseReleased'])
+ expect(me[0]).toMatchObject({ x: 500, y: 100, button: 'left' })
+ })
+
+ it('clicks a raw CSS selector too (the derived-handle escape hatch)', async () => {
+ const page = basePage({ selectorCoords: { '#submit': { x: 400, y: 300, tag: 'BUTTON' } } })
+ const { s, refs } = make(page)
+ const r = await browserClick(s, refs, NODE, '#submit')
+ expect(r).toEqual({ ok: true, message: 'clicked #submit (button) on browser-3' })
+ })
+
+ it('a stale @ref (page navigated since the map) is REFUSED and dispatches NO click (PR 5)', async () => {
+ const page = basePage({ mapItems: MAP, refCoords: { 0: { x: 500, y: 100, tag: 'BUTTON' } } })
+ const { s, dbg, refs } = make(page)
+ await browserReadMap(s, refs, NODE)
+ refs.bumpGeneration(NODE) // Page.frameNavigated
+ const r = await browserClick(s, refs, NODE, '@1')
+ expect(r.ok).toBe(false)
+ expect(r.message).toContain('the page navigated since the last --read map')
+ expect(mouseEvents(dbg)).toEqual([]) // never clicked a re-resolved element
+ })
+
+ it('an off-screen target is refused and dispatches NO click', async () => {
+ const page = basePage({ mapItems: MAP, refCoords: { 0: { x: 5000, y: 100, tag: 'BUTTON' } } })
+ const { s, dbg, refs } = make(page)
+ await browserReadMap(s, refs, NODE)
+ const r = await browserClick(s, refs, NODE, '@1')
+ expect(r.ok).toBe(false)
+ expect(r.message).toContain('off-screen')
+ expect(mouseEvents(dbg)).toEqual([])
+ })
+
+ it('a selector matching nothing is a named refusal', async () => {
+ const { s, refs } = make(basePage())
+ const r = await browserClick(s, refs, NODE, '#missing')
+ expect(r).toEqual({ ok: false, message: 'browser: nothing matches #missing on browser-3' })
+ })
+})
+
+// ── 8.2 --type ──────────────────────────────────────────────────────────────────────────────────
+describe('--type', () => {
+ const SECRET = 'S3CR3T-pw'
+
+ it('focuses --into and inserts the text — the reply reports the COUNT, never the text', async () => {
+ const page = basePage({ mapItems: MAP, refCoords: { 1: { x: 500, y: 200, tag: 'INPUT' } } })
+ const { s, dbg, refs } = make(page)
+ await browserReadMap(s, refs, NODE)
+ const r = await browserType(s, refs, NODE, { text: SECRET, into: '@2', clear: false })
+ expect(r).toEqual({ ok: true, message: 'typed 9 chars into @2 (input#email) on browser-3' })
+ // The typed text is NEVER echoed anywhere in the reply.
+ expect(r.message).not.toContain(SECRET)
+ // It went to insertText (data), not to any expression/key event.
+ const inserts = dbg.sends.filter((x) => x.method === 'Input.insertText')
+ expect(inserts).toHaveLength(1)
+ expect(inserts[0].params).toEqual({ text: SECRET })
+ // Focused the field the way a user does.
+ expect(mouseEvents(dbg).map((e) => e.type)).toEqual(['mousePressed', 'mouseReleased'])
+ })
+
+ it('--clear true selects the field before inserting', async () => {
+ const page = basePage({ mapItems: MAP, refCoords: { 1: { x: 500, y: 200, tag: 'INPUT' } } })
+ const { s, dbg, refs } = make(page)
+ await browserReadMap(s, refs, NODE)
+ const r = await browserType(s, refs, NODE, { text: 'hi', into: '@2', clear: true })
+ expect(r.message).toBe('typed 2 chars into @2 (input#email) on browser-3')
+ expect(keyEvents(dbg).some((e) => Array.isArray(e.commands) && (e.commands as string[]).includes('selectAll'))).toBe(true)
+ })
+
+ it('--clear with empty text clears the field and says so (no insert)', async () => {
+ const page = basePage({ mapItems: MAP, refCoords: { 1: { x: 500, y: 200, tag: 'INPUT' } } })
+ const { s, dbg, refs } = make(page)
+ await browserReadMap(s, refs, NODE)
+ const r = await browserType(s, refs, NODE, { text: '', into: '@2', clear: true })
+ expect(r).toEqual({ ok: true, message: 'cleared @2 (input#email) on browser-3' })
+ expect(dbg.sends.some((x) => x.method === 'Input.insertText')).toBe(false)
+ const cmds = keyEvents(dbg).flatMap((e) => (Array.isArray(e.commands) ? (e.commands as string[]) : []))
+ expect(cmds).toEqual(['selectAll', 'deleteBackward'])
+ })
+
+ it('no --into and NOTHING focused is the exact named refusal', async () => {
+ const { s, refs } = make(basePage({ activeField: null }))
+ const r = await browserType(s, refs, NODE, { text: 'x', clear: false })
+ expect(r).toEqual({ ok: false, message: 'browser: --type needs --into, or a focused field (nothing is focused)' })
+ })
+
+ it('no --into but a field IS focused: types into it with no click', async () => {
+ const page = basePage({ activeField: { tag: 'input', id: 'email' } })
+ const { s, dbg, refs } = make(page)
+ const r = await browserType(s, refs, NODE, { text: SECRET, clear: false })
+ expect(r).toEqual({ ok: true, message: 'typed 9 chars into the focused input#email on browser-3' })
+ expect(r.message).not.toContain(SECRET)
+ expect(mouseEvents(dbg)).toEqual([]) // nothing to focus — no click
+ })
+})
+
+// ── 8.3 --press ─────────────────────────────────────────────────────────────────────────────────
+describe('--press', () => {
+ it('Enter is a keyDown+keyUp from the fixed table', async () => {
+ const { s, dbg } = make(basePage())
+ const r = await browserPress(s, NODE, 'Enter', 1)
+ expect(r).toEqual({ ok: true, message: 'pressed Enter on browser-3' })
+ const ke = keyEvents(dbg)
+ expect(ke.map((e) => e.type)).toEqual(['keyDown', 'keyUp'])
+ expect(ke[0]).toMatchObject({ key: 'Enter', windowsVirtualKeyCode: 13 })
+ })
+
+ it('--times repeats and is reported', async () => {
+ const { s, dbg } = make(basePage())
+ const r = await browserPress(s, NODE, 'ArrowDown', 3)
+ expect(r.message).toBe('pressed ArrowDown x3 on browser-3')
+ expect(keyEvents(dbg)).toHaveLength(6) // 3 × (down+up)
+ })
+
+ it('--times is capped so one verb cannot fire an unbounded storm', async () => {
+ const { s, dbg } = make(basePage())
+ const r = await browserPress(s, NODE, 'PageDown', 100)
+ expect(r.message).toBe('pressed PageDown x50 on browser-3')
+ expect(keyEvents(dbg)).toHaveLength(100)
+ })
+})
+
+// ── 8.4 --scroll ────────────────────────────────────────────────────────────────────────────────
+describe('--scroll', () => {
+ it('scrolls via a bounded mouseWheel and reports the ACTUAL delta read back, not the requested one', async () => {
+ const page = basePage({ scrollY: 0, height: 800, contentHeight: 4400 })
+ const { s, dbg } = make(page)
+ const r = await browserScroll(s, NODE, 'down')
+ // 0.9 × 800 = 720 requested; the fake applied it; the reply is the MEASURED result.
+ expect(r).toEqual({ ok: true, message: 'scrolled browser-3 down 720px (at 720/4400)' })
+ const wheel = mouseEvents(dbg).find((e) => e.type === 'mouseWheel')
+ expect(wheel).toMatchObject({ x: 500, y: 400, deltaY: 720 }) // centre of the viewport
+ })
+
+ it('a signed pixel count matches the design example shape', async () => {
+ const { s } = make(basePage({ scrollY: 0, height: 800, contentHeight: 4400 }))
+ const r = await browserScroll(s, NODE, '600')
+ expect(r.message).toBe('scrolled browser-3 down 600px (at 600/4400)')
+ })
+
+ it('a scroll that MOVES NOTHING shows as 0px — the worst failure shape cannot hide', async () => {
+ // A page no taller than the viewport cannot scroll: the reply must make that visible.
+ const { s } = make(basePage({ scrollY: 0, height: 800, contentHeight: 800 }))
+ const r = await browserScroll(s, NODE, 'down')
+ expect(r.message).toBe('scrolled browser-3 0px (at 0/800)')
+ })
+})
+
+// ── 8.5 --wait ──────────────────────────────────────────────────────────────────────────────────
+describe('--wait', () => {
+ it('a selector already visible returns at once, naming the wait', async () => {
+ const { s, refs } = make(basePage({ visible: { '#results': true } }))
+ const r = await browserWait(s, refs, NODE, '#results', 15_000, { now: () => 0, sleep: async () => {} })
+ expect(r).toEqual({ ok: true, message: '#results appeared on browser-3 after 0ms' })
+ })
+
+ it('a timeout is a NAMED refusal on our own clock', async () => {
+ let clock = 0
+ const now = (): number => clock
+ const sleep = async (ms: number): Promise<void> => {
+ clock += ms
+ }
+ const { s, refs } = make(basePage({ visible: { '#results': false } }))
+ const r = await browserWait(s, refs, NODE, '#results', 300, { now, sleep })
+ expect(r).toEqual({ ok: false, message: 'browser: #results did not appear on browser-3 within 300ms' })
+ })
+
+ it('reports how long a selector took to appear', async () => {
+ const page = basePage({ visible: { '#late': false } })
+ let clock = 0
+ const now = (): number => clock
+ const sleep = async (ms: number): Promise<void> => {
+ clock += ms
+ if (clock >= 300) page.visible['#late'] = true // appears mid-wait
+ }
+ const { s, refs } = make(page)
+ const r = await browserWait(s, refs, NODE, '#late', 15_000, { now, sleep })
+ expect(r.ok).toBe(true)
+ expect(r.message).toMatch(/^#late appeared on browser-3 after \d+ms$/)
+ })
+})