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): --nav and the --read family drive a real guest through the gate

Claude Code8596b03305c2
diff --git a/src/main/browser-actions.test.ts b/src/main/browser-actions.test.ts
new file mode 100644
index 000000000..9cacbdff2
--- /dev/null
+++ b/src/main/browser-actions.test.ts
@@ -0,0 +1,261 @@
+import { describe, it, expect, beforeEach } 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 } from './browser-refs'
+import {
+ CdpEventBus,
+ browserNav,
+ browserRead,
+ browserReadTitle,
+ browserReadLinks,
+ browserReadMap,
+ browserReadText
+} from './browser-actions'
+
+/**
+ * These drive the REAL production code — a real {@link BrowserSession}, real `sendCdp`, the real CDP
+ * allowlist and the real frozen NT_SCRIPTS readers — against a fake `webContents.debugger` whose
+ * `sendCommand` returns canned page data. So every command an action issues actually passes the
+ * allowlist gate (a disallowed method or bad params would reject and fail the test), and the readers
+ * used are the byte-for-byte frozen strings. The only thing faked is the guest's response.
+ *
+ * A real Electron `<webview>` end-to-end (Global Constraint 8) additionally proves the readers'
+ * in-page behaviour (the hidden-input / aria-hidden exclusion). That harness needs Electron + a
+ * display and is not run in this headless suite; see the PR body's deferral note.
+ */
+
+interface PageModel {
+ url: string
+ title: string
+ status: number
+ links: { href: string; text: string }[]
+ mapItems: Record<string, unknown>[]
+ bodyText: string
+ selectorText: Record<string, string | null>
+}
+
+class FakeDebugger implements DebuggerLike {
+ attached = false
+ attachCount = 0
+ sends: { method: string; params: Record<string, unknown> }[] = []
+ private msg: ((e: unknown, method: string, params: unknown) => void)[] = []
+ private det: ((e: unknown, reason: string) => void)[] = []
+ autoLoad = true
+
+ constructor(public page: PageModel) {}
+
+ 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)
+ else this.msg.push(listener)
+ }
+ emit(method: string, params: unknown): void {
+ for (const f of this.msg) f({}, method, params)
+ }
+ async sendCommand(method: string, params: object = {}): Promise<unknown> {
+ const p = params as Record<string, unknown>
+ this.sends.push({ method, params: p })
+ switch (method) {
+ 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 'Page.getNavigationHistory':
+ return { currentIndex: 0, entries: [{ url: this.page.url }] }
+ case 'Page.navigate':
+ if (this.autoLoad) {
+ // A macrotask, so it fires AFTER browserNav has reached `bus.once` — a real debugger's
+ // events arrive over IPC (a macrotask) too, never synchronously inside sendCommand.
+ setTimeout(() => {
+ this.emit('Network.responseReceived', { type: 'Document', response: { status: this.page.status } })
+ this.emit('Page.frameNavigated', { frame: { id: 'main' } })
+ this.emit('Page.loadEventFired', {})
+ }, 0)
+ }
+ return { frameId: 'main' }
+ 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.readTitle) return this.page.title
+ if (fn === NT_SCRIPTS.readLinks) return this.page.links
+ if (fn === NT_SCRIPTS.readMap) return this.page.mapItems
+ if (fn === NT_SCRIPTS.readText) {
+ const sel = args[0]?.value as string | undefined
+ const t = sel ? this.page.selectorText[sel] ?? null : this.page.bodyText
+ return t === null ? null : { text: t.slice(0, 60000), total: t.length }
+ }
+ return null
+ }
+}
+
+const viewport = (): CdpContext => ({ viewport: { width: 1280, height: 800 } })
+
+function makeSession(page: PageModel): { session: BrowserSession; dbg: FakeDebugger; bus: CdpEventBus; refs: RefTable } {
+ const dbg = new FakeDebugger(page)
+ const session = new BrowserSession({ nodeId: 'browser-3', debugger: dbg, viewport })
+ const refs = new RefTable()
+ const bus = new CdpEventBus(() => refs.bumpGeneration('browser-3'))
+ dbg.on('message', ((_e: unknown, m: string, prm: unknown) => bus.emit(m, prm)) as never)
+ return { session, dbg, bus, refs }
+}
+
+function basePage(over: Partial<PageModel> = {}): PageModel {
+ return {
+ url: 'https://example.com/login',
+ title: 'Sign in',
+ status: 200,
+ links: [],
+ mapItems: [],
+ bodyText: '',
+ selectorText: {},
+ ...over
+ }
+}
+
+describe('--nav', () => {
+ it('navigates, reads the main-frame status + final URL + title, and replies one line', async () => {
+ const { session, bus } = makeSession(basePage())
+ const r = await browserNav(session, bus, 'browser-3', 'https://example.com/login', 15_000)
+ expect(r).toEqual({ ok: true, message: 'navigated browser-3 → https://example.com/login (200, "Sign in")' })
+ })
+
+ it('a load that never fires is a NAMED timeout that names the URL it is still at — not a hang', async () => {
+ const { session, dbg, bus } = makeSession(basePage({ url: 'https://slow.test/' }))
+ dbg.autoLoad = false // never emit loadEventFired
+ const r = await browserNav(session, bus, 'browser-3', 'https://slow.test/', 20)
+ expect(r.ok).toBe(false)
+ expect(r.message).toBe('browser: browser-3 did not finish loading within 20ms (still at https://slow.test/)')
+ })
+
+ it('bumps the ref generation on the main-frame navigation (Task 5.5)', async () => {
+ const { session, bus, refs } = makeSession(basePage())
+ expect(refs.currentGeneration('browser-3')).toBe(0)
+ await browserNav(session, bus, 'browser-3', 'https://example.com/login', 15_000)
+ expect(refs.currentGeneration('browser-3')).toBe(1)
+ })
+
+ it('there is no passive channel out of the page — extra CDP events never reach the reply', async () => {
+ const { session, dbg, bus } = makeSession(basePage())
+ dbg.autoLoad = false
+ const navP = browserNav(session, bus, 'browser-3', 'https://example.com/login', 15_000)
+ await new Promise((r) => setTimeout(r, 0)) // let browserNav reach `bus.once`
+ // A firehose of events an S8-style forwarder would have streamed to the agent:
+ dbg.emit('Network.responseReceived', { type: 'Image', response: { status: 404, url: 'https://tracker.test/x.gif' } })
+ dbg.emit('Network.dataReceived', { dataLength: 999, secret: 'PAGE-DATA-LEAK' })
+ dbg.emit('Runtime.consoleAPICalled', { args: [{ value: 'CONSOLE-LEAK' }] })
+ dbg.emit('Network.responseReceived', { type: 'Document', response: { status: 200 } })
+ dbg.emit('Page.loadEventFired', {})
+ const r = await navP
+ expect(r.message).not.toContain('LEAK')
+ expect(r.message).not.toContain('404')
+ expect(r.message).toBe('navigated browser-3 → https://example.com/login (200, "Sign in")')
+ })
+})
+
+describe('--read family', () => {
+ let spySends: { method: string; params: Record<string, unknown> }[]
+
+ beforeEach(() => {
+ spySends = []
+ })
+
+ it('NO agent-derived character reaches an `expression` field — ever (Task 7.4)', async () => {
+ const page = basePage({
+ links: [{ href: 'https://example.com/pricing', text: 'Pricing' }],
+ mapItems: [{ ref: 0, tag: 'button', role: 'button', name: 'Sign in', filled: null }],
+ bodyText: 'hello world'
+ })
+ const { session, dbg, bus, refs } = makeSession(page)
+ for (const mode of ['title', 'links', 'map', 'text'] as const) {
+ await browserRead(session, bus, refs, 'browser-3', mode, { selector: 'main.injection"attempt' })
+ }
+ // The read chain uses ONLY functionDeclaration (identity-pinned) + our objectId + scalar args.
+ for (const s of dbg.sends) {
+ expect(s.params).not.toHaveProperty('expression')
+ }
+ // Runtime.evaluate is never issued at all.
+ expect(dbg.sends.some((s) => s.method === 'Runtime.evaluate')).toBe(false)
+ })
+
+ it('--read title: URL + title + status, one line', async () => {
+ const { session, bus } = makeSession(basePage())
+ // seed a status the way a prior nav would
+ bus.emit('Network.responseReceived', { type: 'Document', response: { status: 200 } })
+ const r = await browserReadTitle(session, bus)
+ expect(r).toEqual({ ok: true, message: 'https://example.com/login "Sign in" (200)' })
+ })
+
+ it('--read links: text → absolute url, one per line, deduped', async () => {
+ const page = basePage({
+ links: [
+ { href: 'https://example.com/a', text: 'A' },
+ { href: 'https://example.com/a', text: 'A again (dupe href)' },
+ { href: 'https://example.com/b', text: 'B' }
+ ]
+ })
+ const { session } = makeSession(page)
+ const r = await browserReadLinks(session)
+ expect(r.message).toBe('A → https://example.com/a\nB → https://example.com/b')
+ })
+
+ it('--read map: numbered, mints refs, reports FILL STATE never the value (Task 7.5)', async () => {
+ const page = basePage({
+ mapItems: [
+ { ref: 0, tag: 'a', role: 'link', name: 'Pricing', href: 'https://example.com/pricing', filled: null },
+ // A password field that IS filled — the reader returns `filled:true` and NEVER a value.
+ { ref: 1, tag: 'input', role: 'input', id: 'password', type: 'password', name: '', filled: true },
+ { ref: 2, tag: 'button', role: 'button', name: 'Sign in', filled: null }
+ ]
+ })
+ const { session, refs } = makeSession(page)
+ const r = await browserReadMap(session, refs, 'browser-3')
+ expect(r.message).toBe(
+ '@1 link "Pricing" → https://example.com/pricing\n@2 input#password (password, filled)\n@3 button "Sign in"'
+ )
+ // The value 'hunter2' is nowhere in the reply because the reader never returned it.
+ expect(r.message).not.toContain('hunter2')
+ // Refs were minted for this node at the current generation.
+ expect(refs.resolve('browser-3', refs.currentGeneration('browser-3'), '@2').ok).toBe(true)
+ })
+
+ it('--read text: capped by --max with an IN-BAND truncation announcement', async () => {
+ const big = 'x'.repeat(84213)
+ const { session } = makeSession(basePage({ bodyText: big }))
+ const r = await browserReadText(session, 'browser-3', undefined, 20_000)
+ expect(r.ok).toBe(true)
+ expect(r.message.endsWith('[truncated at 20000 of 84213 chars — narrow it with --selector]')).toBe(true)
+ expect(r.message.length).toBeLessThan(big.length)
+ })
+
+ it('--read text: --max is clamped to the 60000 ceiling', async () => {
+ const big = 'y'.repeat(70000)
+ const { session } = makeSession(basePage({ bodyText: big }))
+ const r = await browserReadText(session, 'browser-3', undefined, 999999)
+ expect(r.message).toContain('[truncated at 60000 of 70000 chars')
+ })
+
+ it('--read text: a selector matching nothing is a named refusal, not empty text', async () => {
+ const { session } = makeSession(basePage({ selectorText: { '#missing': null } }))
+ const r = await browserReadText(session, 'browser-3', '#missing', undefined)
+ expect(r).toEqual({ ok: false, message: 'browser: browser-3 has nothing matching #missing' })
+ })
+})
diff --git a/src/main/browser-actions.ts b/src/main/browser-actions.ts
new file mode 100644
index 000000000..395d6fcfb
--- /dev/null
+++ b/src/main/browser-actions.ts
@@ -0,0 +1,318 @@
+/**
+ * The CDP execution for the `browser` verb's PR-7 actions — `--nav` and the `--read` family. Every
+ * command here goes through the injected `send` (a {@link import('./browser-lease').BrowserSession}'s
+ * `send`, which routes through `sendCdp` → the allowlist), so this module cannot reach a CDP method
+ * the gate refuses. Main-side only (it reads a real page); never Server Edition.
+ *
+ * THE EVENT BOUNDARY (design §3.2, Task 7.3). We subscribe to a FIXED set of CDP events —
+ * Page.frameNavigated, Page.loadEventFired, Network.responseReceived (main frame),
+ * Runtime.executionContextsCleared — and NOTHING is streamed to the agent. S8 forwarded every CDP
+ * event to its client as a firehose; here events feed our own state (the {@link CdpEventBus}) only,
+ * and the agent sees verb REPLIES. `browser-actions.test.ts` asserts there is no passive channel out
+ * of the page: extra events emitted during a nav never appear in the reply.
+ *
+ * THE READ BOUNDARY (design §3.1, Task 7.4). Page-side logic runs ONLY as a frozen NT_SCRIPTS entry,
+ * by identity, through Runtime.callFunctionOn with returnByValue — NO agent-derived character ever
+ * reaches an `expression` field, because this module never issues Runtime.evaluate at all. A test
+ * spies on every send and fails on any `expression` key.
+ *
+ * CDP child-session bookkeeping and the wheel/scroll salvage come from PR #112's S8 (@Corvin,
+ * 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'
+
+/** A one-line agent-facing outcome. `ok:false` is a NAMED refusal, never a hang and never a raw
+ * Electron error. */
+export interface ActionResult {
+ ok: boolean
+ message: string
+}
+
+/** The one capability the actions need from a lease: send a (gated) CDP command. */
+export interface Sendable {
+ send(method: string, params: object): Promise<unknown>
+}
+
+/** 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
+const LIST_CAP = 200
+const LIST_BYTES = 8192
+
+type CdpEvent = { method: string; params: Record<string, unknown> }
+
+/**
+ * The fixed-set event sink for one guest. Fed by `debugger.on('message')` in index.ts; read by
+ * {@link browserNav}. It records only the main-frame document status and drives ref invalidation on
+ * a navigation — it has NO path that hands an event to an agent-facing channel.
+ */
+export class CdpEventBus {
+ private readonly waiters = new Set<{ match: (e: CdpEvent) => boolean; resolve: (e: CdpEvent | null) => void }>()
+ private mainFrameStatus: number | undefined
+
+ /** `onNavigation` bumps the node's ref generation (Task 5.5) — the single invalidation path both
+ * Page.frameNavigated and Runtime.executionContextsCleared funnel through. */
+ constructor(private readonly onNavigation?: () => void) {}
+
+ emit(method: string, rawParams: unknown): void {
+ const params = (rawParams && typeof rawParams === 'object' ? rawParams : {}) as Record<string, unknown>
+ if (method === 'Page.frameNavigated') {
+ const frame = params.frame as { parentId?: string } | undefined
+ // The MAIN frame only (no parent). A sub-frame navigation is not a page navigation.
+ if (frame && frame.parentId === undefined) this.onNavigation?.()
+ } else if (method === 'Runtime.executionContextsCleared') {
+ this.onNavigation?.()
+ } else if (method === 'Network.responseReceived') {
+ // Main-frame DOCUMENT response only — the status the agent means by "did it load".
+ if (params.type === 'Document') {
+ const resp = params.response as { status?: number } | undefined
+ if (resp && typeof resp.status === 'number') this.mainFrameStatus = resp.status
+ }
+ }
+ const e: CdpEvent = { method, params }
+ for (const w of [...this.waiters]) {
+ if (w.match(e)) {
+ this.waiters.delete(w)
+ w.resolve(e)
+ }
+ }
+ }
+
+ /** Await the next event matching `match`, or null after `timeoutMs`. Never throws, never hangs. */
+ once(match: (e: CdpEvent) => boolean, timeoutMs: number): Promise<CdpEvent | null> {
+ return new Promise((resolve) => {
+ const waiter = {
+ match,
+ resolve: (e: CdpEvent | null) => {
+ clearTimeout(timer)
+ resolve(e)
+ }
+ }
+ const timer = setTimeout(() => {
+ this.waiters.delete(waiter)
+ resolve(null)
+ }, timeoutMs)
+ this.waiters.add(waiter)
+ })
+ }
+
+ /** Forget the last main-frame status — called at the start of a nav so a stale status can't be
+ * reported for the new page. */
+ clearStatus(): void {
+ this.mainFrameStatus = undefined
+ }
+
+ mainStatus(): number | undefined {
+ return this.mainFrameStatus
+ }
+}
+
+/**
+ * The read chain, once: DOM.getDocument(depth:0) → DOM.resolveNode → Runtime.callFunctionOn(a FROZEN
+ * NT_SCRIPTS reader, returnByValue, scalar args) → Runtime.releaseObject. The nodeId and objectId are
+ * OURS (from our own getDocument/resolveNode), never the agent's; the only agent-derived data that
+ * ever reaches a reader is a scalar `arguments[].value`, checked by the allowlist.
+ */
+async function callReader(s: Sendable, fn: string, args: readonly (string | number)[] = []): Promise<unknown> {
+ const doc = (await s.send('DOM.getDocument', { depth: 0 })) as { root?: { nodeId?: number } }
+ const nodeId = doc?.root?.nodeId
+ if (typeof nodeId !== 'number') throw new Error('read: could not read the document root')
+ const resolved = (await s.send('DOM.resolveNode', { nodeId })) as { object?: { objectId?: string } }
+ const objectId = resolved?.object?.objectId
+ if (typeof objectId !== 'string' || !objectId) throw new Error('read: could not resolve the document node')
+ try {
+ const res = (await s.send('Runtime.callFunctionOn', {
+ objectId,
+ functionDeclaration: fn,
+ arguments: args.map((v) => ({ value: v })),
+ returnByValue: true
+ })) as { result?: { value?: unknown } }
+ return res?.result?.value
+ } finally {
+ // Best-effort release; a failed release must not turn a good read into an error.
+ await s.send('Runtime.releaseObject', { objectId }).catch(() => {})
+ }
+}
+
+/** The final URL after navigation/redirects, from OUR navigation-history read. */
+async function currentUrl(s: Sendable): Promise<string> {
+ const h = (await s.send('Page.getNavigationHistory', {})) as {
+ currentIndex?: number
+ entries?: { url?: string }[]
+ }
+ const idx = typeof h?.currentIndex === 'number' ? h.currentIndex : -1
+ const url = h?.entries?.[idx]?.url
+ return typeof url === 'string' ? url : ''
+}
+
+async function readTitleValue(s: Sendable): Promise<string> {
+ const v = await callReader(s, NT_SCRIPTS.readTitle)
+ return typeof v === 'string' ? v : ''
+}
+
+/**
+ * `--nav`. Navigate, wait for the load (main's own clock, never a hang), and report the final URL,
+ * the main-frame status and the title. The timeout message NAMES the URL it is still at, because the
+ * worst failure shape is a page that half-loaded and the agent not knowing where it is.
+ */
+export async function browserNav(
+ s: Sendable,
+ bus: CdpEventBus,
+ nodeId: string,
+ url: string,
+ timeoutMs: number
+): Promise<ActionResult> {
+ await s.send('Page.enable', {})
+ await s.send('Network.enable', {})
+ bus.clearStatus()
+ await s.send('Page.navigate', { url })
+ const loaded = await bus.once((e) => e.method === 'Page.loadEventFired', timeoutMs)
+ const finalUrl = await currentUrl(s)
+ if (!loaded) {
+ return {
+ ok: false,
+ message: `browser: ${nodeId} did not finish loading within ${timeoutMs}ms (still at ${finalUrl})`
+ }
+ }
+ const status = bus.mainStatus()
+ const title = await readTitleValue(s)
+ const statusPart = status !== undefined ? String(status) : '?'
+ return { ok: true, message: `navigated ${nodeId} → ${finalUrl} (${statusPart}, ${JSON.stringify(title)})` }
+}
+
+/** `--read title`: URL + document.title + HTTP status, one line. */
+export async function browserReadTitle(s: Sendable, bus: CdpEventBus): Promise<ActionResult> {
+ const title = await readTitleValue(s)
+ const url = await currentUrl(s)
+ const status = bus.mainStatus()
+ const statusPart = status !== undefined ? ` (${status})` : ''
+ return { ok: true, message: `${url} ${JSON.stringify(title)}${statusPart}`.trim() }
+}
+
+interface LinkItem {
+ href?: unknown
+ text?: unknown
+}
+
+/** `--read links`: `text → absolute url`, deduped, capped at 200 links / 8 KB. */
+export async function browserReadLinks(s: Sendable): Promise<ActionResult> {
+ const raw = (await callReader(s, NT_SCRIPTS.readLinks)) as LinkItem[] | null
+ const seen = new Set<string>()
+ const lines: string[] = []
+ let bytes = 0
+ for (const l of raw ?? []) {
+ const href = typeof l?.href === 'string' ? l.href : ''
+ if (!href || seen.has(href)) continue
+ seen.add(href)
+ const text = (typeof l?.text === 'string' ? l.text : '').replace(/\s+/g, ' ').trim()
+ const line = `${text || '(no text)'} → ${href}`
+ if (lines.length >= LIST_CAP || bytes + line.length + 1 > LIST_BYTES) break
+ lines.push(line)
+ bytes += line.length + 1
+ }
+ return { ok: true, message: lines.length ? lines.join('\n') : 'no links on this page' }
+}
+
+interface MapItem {
+ tag?: unknown
+ role?: unknown
+ id?: unknown
+ type?: unknown
+ name?: unknown
+ href?: unknown
+ filled?: unknown
+}
+
+function formatMapItem(label: string, it: MapItem): string {
+ const tag = typeof it.tag === 'string' ? it.tag : ''
+ const role = (typeof it.role === 'string' && it.role) || tag || 'element'
+ const name = (typeof it.name === 'string' ? it.name : '').replace(/\s+/g, ' ').trim()
+ if (tag === 'input' || tag === 'textarea' || tag === 'select') {
+ const id = typeof it.id === 'string' && it.id ? `#${it.id}` : ''
+ const type = (typeof it.type === 'string' && it.type) || tag
+ // The FILL STATE, never the value (design §2.4 / Task 7.5).
+ const state = it.filled ? 'filled' : 'empty'
+ return `${label} ${tag}${id} (${type}, ${state})`
+ }
+ if (tag === 'a') {
+ const href = typeof it.href === 'string' && it.href ? ` → ${it.href}` : ''
+ return `${label} ${role} ${JSON.stringify(name)}${href}`
+ }
+ return `${label} ${role} ${JSON.stringify(name)}`
+}
+
+/**
+ * `--read map`: a numbered inventory of INTERACTABLE elements only, capped 200 / 8 KB. Mints `@1…@n`
+ * bound to (nodeId, current navigation generation) so a later click can spend them (Task 5.5). Role,
+ * accessible name, and for a field its type and whether it is FILLED — never its value.
+ */
+export async function browserReadMap(s: Sendable, refs: RefTable, nodeId: string): Promise<ActionResult> {
+ const raw = (await callReader(s, NT_SCRIPTS.readMap)) as MapItem[] | null
+ const items = (raw ?? []).slice(0, LIST_CAP)
+ // Mint at the CURRENT generation — the one this page is on, which a navigation will have bumped.
+ refs.mint(nodeId, refs.currentGeneration(nodeId), items as Record<string, unknown>[])
+ const lines: string[] = []
+ let bytes = 0
+ for (let i = 0; i < items.length; i++) {
+ const line = formatMapItem(`@${i + 1}`, items[i])
+ if (bytes + line.length + 1 > LIST_BYTES) break
+ lines.push(line)
+ bytes += line.length + 1
+ }
+ return { ok: true, message: lines.length ? lines.join('\n') : 'no interactable elements found' }
+}
+
+/**
+ * `--read text`: rendered VISIBLE text (innerText semantics), whitespace as the page has it, scoped
+ * by `--selector`. Capped by `--max` (default 20 000, ceiling 60 000); a truncation is announced
+ * IN-BAND so the agent learns to narrow it. There is deliberately NO html/full-DOM mode.
+ */
+export async function browserReadText(
+ s: Sendable,
+ nodeId: string,
+ selector: string | undefined,
+ max: number | undefined
+): Promise<ActionResult> {
+ const res = (await callReader(s, NT_SCRIPTS.readText, selector ? [selector] : [])) as
+ | { text?: unknown; total?: unknown }
+ | null
+ if (res === null) {
+ return {
+ ok: false,
+ message: selector
+ ? `browser: ${nodeId} has nothing matching ${selector}`
+ : `browser: ${nodeId} has no readable document body`
+ }
+ }
+ const cap = Math.min(max ?? READ_TEXT_DEFAULT_MAX, READ_TEXT_CEILING)
+ const full = typeof res.text === 'string' ? res.text : ''
+ const total = typeof res.total === 'number' ? res.total : full.length
+ const text = full.slice(0, cap)
+ if (total > cap) {
+ return { ok: true, message: `${text}\n[truncated at ${cap} of ${total} chars — narrow it with --selector]` }
+ }
+ return { ok: true, message: text }
+}
+
+/** Dispatch the `--read <mode>` family. */
+export async function browserRead(
+ s: Sendable,
+ bus: CdpEventBus,
+ refs: RefTable,
+ nodeId: string,
+ mode: BrowserReadMode,
+ opts: { selector?: string; max?: number }
+): Promise<ActionResult> {
+ switch (mode) {
+ case 'title':
+ return browserReadTitle(s, bus)
+ case 'links':
+ return browserReadLinks(s)
+ case 'map':
+ return browserReadMap(s, refs, nodeId)
+ case 'text':
+ return browserReadText(s, nodeId, opts.selector, opts.max)
+ }
+}
diff --git a/src/main/browser-cdp-allowlist.test.ts b/src/main/browser-cdp-allowlist.test.ts
index 92418f1ed..56ca54661 100644
--- a/src/main/browser-cdp-allowlist.test.ts
+++ b/src/main/browser-cdp-allowlist.test.ts
@@ -73,21 +73,52 @@ describe('checkCdpCommand', () => {
// An allowlist that explains itself is a probing aid.
expect(checkCdpCommand('Made.Up', {}, ctx)).toBe(false)
})
+
+ it('the read/nav infra methods PR 7 adds are gated, not blanket-allowed', () => {
+ // Enabling the Network domain (needed for the main-frame status) is fine; it carries no read.
+ expect(checkCdpCommand('Network.enable', {}, ctx)).toBe(true)
+ expect(checkCdpCommand('Page.getNavigationHistory', {}, ctx)).toBe(true)
+ // resolveNode takes OUR document nodeId (a number), never an agent objectId.
+ expect(checkCdpCommand('DOM.resolveNode', { nodeId: 1 }, ctx)).toBe(true)
+ expect(checkCdpCommand('DOM.resolveNode', { objectId: 'agent-picked' }, ctx)).toBe(false)
+ expect(checkCdpCommand('DOM.resolveNode', {}, ctx)).toBe(false)
+ expect(checkCdpCommand('Runtime.releaseObject', { objectId: 'o1' }, ctx)).toBe(true)
+ expect(checkCdpCommand('Runtime.releaseObject', {}, ctx)).toBe(false)
+ })
+
+ it('the full-DOM read cannot arrive by another door (Task 7.6)', () => {
+ // `--read html` is refused in the verb parser; here we pin that the CDP methods an HTML/full-DOM
+ // read would need are refused by the allowlist too, so the same read cannot arrive by another
+ // door — deep getDocument, getOuterHTML and getAttributes are all default-denied.
+ expect(checkCdpCommand('DOM.getOuterHTML', { nodeId: 1 }, ctx)).toBe(false)
+ expect(checkCdpCommand('DOM.getAttributes', { nodeId: 1 }, ctx)).toBe(false)
+ expect(checkCdpCommand('DOM.getDocument', { depth: -1 }, ctx)).toBe(false) // -1 = whole tree
+ expect(checkCdpCommand('DOM.getDocument', { depth: 0 }, ctx)).toBe(true)
+ expect(checkCdpCommand('DOM.getDocument', { depth: 1, pierce: true }, ctx)).toBe(false)
+ })
})
/**
* Structural pin (the analogue of Task 4.4's second half). `checkCdpCommand` is only THE gate if it
- * is unbypassable: every `sendCommand(` in the main-side browser surface must live inside the one
- * wrapper, `browser-cdp-send.ts`, which calls this function. A direct `debugger.sendCommand` anywhere
- * else is arbitrary CDP that never met the allowlist.
+ * is unbypassable: every `sendCommand(` in `src/main` must live inside the one wrapper,
+ * `browser-cdp-send.ts`, which calls this function. A direct `debugger.sendCommand` anywhere else is
+ * arbitrary CDP that never met the allowlist.
+ *
+ * WIDENED IN PR 7 (carried obligation, PR 5/#306 MINOR-1). Until the `browser` VERB existed, the only
+ * CDP callers were `browser-*.ts` files and the grep scanned only those. PR 7 adds the drive path
+ * (`browser-drive.ts`, `browser-actions.ts`) and wires the real `webContents.debugger` into a
+ * `BrowserSession` from `index.ts` — so a stray `sendCommand` could now be introduced in a
+ * non-`browser-`prefixed main file too. The grep therefore scans ALL of `src/main`, so the single-gate
+ * property is enforced across the whole surface the verb path now touches, not just the files that
+ * happen to be named `browser-*`.
*/
-describe('debugger.sendCommand has exactly one call site', () => {
+describe('debugger.sendCommand has exactly one call site in ALL of src/main', () => {
const mainDir = path.resolve(__dirname)
- it('every sendCommand( in src/main/browser-*.ts is inside browser-cdp-send.ts', () => {
+ it('every sendCommand( in src/main is inside browser-cdp-send.ts', () => {
const offenders: string[] = []
for (const f of fs.readdirSync(mainDir)) {
- if (!/^browser-.*\.ts$/.test(f) || f.endsWith('.test.ts')) continue
+ if (!f.endsWith('.ts') || f.endsWith('.test.ts')) continue
if (f === 'browser-cdp-send.ts') continue
const src = fs.readFileSync(path.join(mainDir, f), 'utf8')
// Strip comments so a mention in prose is not a false positive; a real call is not a comment.
diff --git a/src/main/browser-cdp-allowlist.ts b/src/main/browser-cdp-allowlist.ts
index d5a438bf8..f690fd3b6 100644
--- a/src/main/browser-cdp-allowlist.ts
+++ b/src/main/browser-cdp-allowlist.ts
@@ -109,13 +109,15 @@ const ALLOW = new Map<string, Validator>([
p.selector.length <= MAX_SELECTOR
],
- // A shallow document read only (depth <= 1, no pierce) — the deep read is the full-DOM door that
- // getOuterHTML/getAttributes are excluded to keep shut.
+ // A shallow document read only (0 <= depth <= 1, no pierce) — the deep read is the full-DOM door
+ // that getOuterHTML/getAttributes are excluded to keep shut. NEGATIVE depth is refused too: in CDP
+ // `depth: -1` means the ENTIRE subtree, the same full-DOM read arriving by a signed-number door
+ // (Task 7.6). Our own read code passes depth:0; this is the belt.
[
'DOM.getDocument',
(p) =>
isRecord(p) &&
- (p.depth === undefined || (typeof p.depth === 'number' && p.depth <= 1)) &&
+ (p.depth === undefined || (typeof p.depth === 'number' && p.depth >= 0 && p.depth <= 1)) &&
p.pierce !== true
],
@@ -144,6 +146,18 @@ const ALLOW = new Map<string, Validator>([
['DOM.enable', () => true],
['Runtime.enable', () => true],
['Page.getLayoutMetrics', () => true],
+ // Enable the Network domain so `--nav` can read the MAIN-FRAME response status from
+ // Network.responseReceived (an event feeding our own state — nothing is streamed to the agent,
+ // asserted in browser-actions.test.ts). It carries no read power itself; getAllCookies stays out.
+ ['Network.enable', () => true],
+ // The final URL after a `--nav` (redirects resolved). Read-only, no parameters that matter.
+ ['Page.getNavigationHistory', () => true],
+ // The read family's chain: getDocument(depth<=1) → resolveNode(nodeId) → callFunctionOn → releaseObject.
+ // resolveNode turns OUR shallow document node into an execution-context object handle for the frozen
+ // NT_SCRIPTS reader; the nodeId comes from our own getDocument, never from the agent.
+ ['DOM.resolveNode', (p) => isRecord(p) && typeof p.nodeId === 'number'],
+ // Free the object handle callFunctionOn ran against. objectId is our own, from resolveNode.
+ ['Runtime.releaseObject', (p) => isRecord(p) && typeof p.objectId === 'string' && p.objectId.length > 0],
// Flat-mode child attach only (S8): a nested/auto-attach mode is a different, unaudited surface.
[
'Target.attachToTarget',
diff --git a/src/main/browser-nt-scripts.source.test.ts b/src/main/browser-nt-scripts.source.test.ts
index 445500228..e9064fbcd 100644
--- a/src/main/browser-nt-scripts.source.test.ts
+++ b/src/main/browser-nt-scripts.source.test.ts
@@ -40,6 +40,14 @@ describe('NT_SCRIPTS is a frozen table of literals', () => {
expect(isNtScript('function(){return 1}')).toBe(false)
})
+ it('readMap reports whether a field is FILLED but never returns its value (Task 7.5)', () => {
+ // The whole point of `--read map`: a password's fill STATE is useful, its value is a credential.
+ // The returned object literal must never carry a `value:` key. Reading `el.value` to compute the
+ // boolean is fine (no assignment); RETURNING it is the leak this pins against.
+ expect(NT_SCRIPTS.readMap).toContain('filled:')
+ expect(NT_SCRIPTS.readMap).not.toMatch(/value\s*:/)
+ })
+
it('every script is a pure reader — none clicks, navigates, submits or writes', () => {
// Every EFFECT goes through Input.* or Page.*, which is also why the effects are traceable.
for (const s of Object.values(NT_SCRIPTS)) {
diff --git a/src/main/browser-nt-scripts.ts b/src/main/browser-nt-scripts.ts
index 4574d41c6..3e83f18e3 100644
--- a/src/main/browser-nt-scripts.ts
+++ b/src/main/browser-nt-scripts.ts
@@ -26,18 +26,25 @@ export const NT_SCRIPTS = Object.freeze({
/** The document title. */
readTitle: 'function(){ return document.title }',
- /** A map of interactable elements: a ref index, a tag, a short label and the element centre in
- * viewport coordinates (what a later Input.dispatchMouseEvent aims at). Read-only. */
+ /** A map of interactable elements: a ref index, role, accessible NAME (never a field's value), id,
+ * input type, whether a field is FILLED (a boolean — never the value), a link's absolute href, and
+ * the element centre in viewport coordinates (what a later Input.dispatchMouseEvent aims at).
+ * Read-only. Off-screen (zero-box), display:none and aria-hidden elements are skipped by
+ * construction, which is what keeps a hidden CSRF input and an aria-hidden block out of the map. */
readMap:
- 'function(){ var els = document.querySelectorAll("a,button,input,textarea,select,[role=button],[role=link],[onclick]"); var out = []; for (var i = 0; i < els.length; i++) { var el = els[i]; var r = el.getBoundingClientRect(); if (r.width <= 0 || r.height <= 0) continue; out.push({ ref: i, tag: el.tagName, type: el.getAttribute("type"), text: (el.innerText || el.getAttribute("aria-label") || el.getAttribute("placeholder") || "").replace(/\\s+/g, " ").trim().slice(0, 80), x: r.left + r.width / 2, y: r.top + r.height / 2, w: r.width, h: r.height }); } return out }',
+ 'function(){ var els = document.querySelectorAll("a,button,input,textarea,select,[role=button],[role=link],[onclick]"); var out = []; for (var i = 0; i < els.length; i++) { var el = els[i]; var r = el.getBoundingClientRect(); if (r.width <= 0 || r.height <= 0) continue; if (el.closest && el.closest("[aria-hidden=true]")) continue; var tag = el.tagName.toLowerCase(); var role = el.getAttribute("role") || (tag === "a" ? "link" : tag === "button" ? "button" : tag); var isField = tag === "input" || tag === "textarea" || tag === "select"; var name = (el.innerText || el.getAttribute("aria-label") || el.getAttribute("placeholder") || "").replace(/\\s+/g, " ").trim().slice(0, 80); out.push({ ref: i, tag: tag, role: role, id: el.id || "", type: el.getAttribute("type"), name: name, href: tag === "a" ? el.href : null, filled: isField ? (el.value ? true : false) : null, x: r.left + r.width / 2, y: r.top + r.height / 2, w: r.width, h: r.height }); } return out }',
/** Every visible link as { href, text }. Read-only. */
readLinks:
'function(){ var as = document.querySelectorAll("a[href]"); var out = []; for (var i = 0; i < as.length; i++) { out.push({ href: as[i].href, text: (as[i].innerText || "").replace(/\\s+/g, " ").trim().slice(0, 120) }); } return out }',
- /** The visible text of a selector (or the whole body when none is given). Read-only, capped. */
+ /** The visible text of a selector (or the whole body when none is given), plus the untruncated
+ * length so main can announce an in-band truncation. Capped at the hard ceiling (60000) so a huge
+ * page never ships megabytes over CDP; main applies the caller's --max (<= ceiling) to the text.
+ * innerText semantics exclude <script>, <style>, display:none and aria-hidden BY CONSTRUCTION.
+ * Read-only. */
readText:
- 'function(sel){ var el = sel ? document.querySelector(sel) : document.body; return el ? (el.innerText || "").slice(0, 20000) : null }',
+ 'function(sel){ var el = sel ? document.querySelector(sel) : document.body; if (!el) return null; var t = el.innerText || ""; return { text: t.slice(0, 60000), total: t.length } }',
/** Re-locate a ref from readMap and return its current centre and tag, or null if it is gone. The
* ref is re-resolved against the SAME enumeration; generation staleness is enforced in main. */