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(control): `browser` is answered in MAIN, and the renderer only says what it alone knows

Claude Code7a7fa929145f
diff --git a/src/main/browser-control-route.test.ts b/src/main/browser-control-route.test.ts
new file mode 100644
index 000000000..5286a6a5c
--- /dev/null
+++ b/src/main/browser-control-route.test.ts
@@ -0,0 +1,105 @@
+import { describe, it, expect } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+import {
+ resolveBrowserTarget,
+ browserResolveTimedOut,
+ type BrowserResolve
+} from './browser-drive'
+
+/**
+ * Task 7.2 — `browser` is answered in MAIN, and the renderer only says what it alone knows. The
+ * security decision (owner + capability + the CDP allowlist) is main-side; the renderer is asked
+ * three facts and NEVER runs a CDP command. These tests pin both halves: the resolve round-trip
+ * cannot hang the pending-control budget, and the renderer half holds no CDP surface.
+ */
+
+const repoRoot = path.resolve(__dirname, '..', '..')
+
+describe('the resolve round-trip is a NAMED failure, never a hang (does not eat the 120s budget)', () => {
+ it('a canvas that never answers times out to a named refusal well under the budget', async () => {
+ const never = () => new Promise<BrowserResolve>(() => {}) // hangs forever
+ const start = Date.now()
+ const r = await resolveBrowserTarget('browser-3', never, 30)
+ expect(Date.now() - start).toBeLessThan(1000)
+ expect(r).toEqual({ ok: false, refusal: browserResolveTimedOut('browser-3') })
+ })
+
+ it('a renderer that rejects (the window went away) is the same named failure', async () => {
+ const rejects = () => Promise.reject(new Error('window gone'))
+ const r = await resolveBrowserTarget('browser-3', rejects, 1000)
+ expect(r).toEqual({ ok: false, refusal: browserResolveTimedOut('browser-3') })
+ })
+
+ it('a prompt answer is passed straight through', async () => {
+ const answer: BrowserResolve = { ok: true, projectId: 'p', sourceControlCapable: true, capabilityOn: true }
+ const r = await resolveBrowserTarget('browser-3', () => Promise.resolve(answer), 1000)
+ expect(r).toEqual(answer)
+ })
+})
+
+describe("Canvas.tsx holds NO part of the CDP surface (it is the more attackable half)", () => {
+ const canvas = fs.readFileSync(path.join(repoRoot, 'src/renderer/canvas/Canvas.tsx'), 'utf8')
+ // Strip comments so a mention in prose is not a false positive.
+ const code = canvas.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '')
+
+ it('never calls sendCommand', () => {
+ expect(/\bsendCommand\s*\(/.test(code)).toBe(false)
+ })
+
+ it('never imports the NT_SCRIPTS table', () => {
+ expect(code.includes('browser-nt-scripts')).toBe(false)
+ expect(/\bNT_SCRIPTS\b/.test(code)).toBe(false)
+ })
+
+ it('never imports the CDP allowlist', () => {
+ expect(code.includes('browser-cdp-allowlist')).toBe(false)
+ expect(code.includes('browser-cdp-send')).toBe(false)
+ expect(/\bcheckCdpCommand\b/.test(code)).toBe(false)
+ })
+
+ it('never imports the main-side drive/gate module', () => {
+ // The allowlist and the ledger must not be reachable from the renderer at all.
+ expect(code.includes('browser-drive')).toBe(false)
+ expect(code.includes('browser-control-ledger')).toBe(false)
+ })
+})
+
+/**
+ * Carried obligation (PR 6/#307 MINOR-1): there is NO second global browser-control toggle — the ONLY
+ * gate is the per-project switch (`agentBrowserControl`). A machine-wide "browser control on/off"
+ * setting would be a second, coarser authority that could silently override the per-project consent
+ * the whole design is built on. This was true by grep but unguarded; here it is pinned.
+ */
+describe('there is exactly ONE browser-control gate — the per-project switch, no second global toggle', () => {
+ function walk(dir: string, out: string[] = []): string[] {
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
+ if (e.name === 'node_modules' || e.name.startsWith('.')) continue
+ const full = path.join(dir, e.name)
+ if (e.isDirectory()) walk(full, out)
+ else if (/\.(ts|tsx)$/.test(e.name) && !/\.test\.(ts|tsx)$/.test(e.name)) out.push(full)
+ }
+ return out
+ }
+
+ it('no settings/store key names a GLOBAL browser-control toggle', () => {
+ // A global toggle would surface as a settings key like these. The per-project field is
+ // `agentBrowserControl` (a project.json field), which is deliberately NOT matched here.
+ const globalTogglePatterns = [
+ /browserControlEnabled/i,
+ /enableBrowserControl/i,
+ /globalBrowserControl/i,
+ /browserControlGlobal/i,
+ /allowBrowserControl/i,
+ /disableBrowserControl/i
+ ]
+ const offenders: string[] = []
+ for (const f of walk(path.join(repoRoot, 'src'))) {
+ const src = fs.readFileSync(f, 'utf8')
+ for (const re of globalTogglePatterns) {
+ if (re.test(src)) offenders.push(`${path.relative(repoRoot, f)} :: ${re}`)
+ }
+ }
+ expect(offenders).toEqual([])
+ })
+})
diff --git a/src/main/browser-drive.test.ts b/src/main/browser-drive.test.ts
new file mode 100644
index 000000000..a7da0d180
--- /dev/null
+++ b/src/main/browser-drive.test.ts
@@ -0,0 +1,213 @@
+import { describe, it, expect, vi } from 'vitest'
+import { BrowserControlLedger, BROWSER_USER_STOPPED } from './browser-control-ledger'
+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, type Sendable } from './browser-actions'
+import { STRICT_CONTROL_REFUSAL } from '../core/agents/node-identity-policy'
+import { browserDiscardedMessage } from './browser-guest-registry'
+import {
+ driveBrowser,
+ gateBrowserDrive,
+ BROWSER_CAPABILITY_OFF_MESSAGE,
+ BROWSER_SOURCE_NOT_CAPABLE,
+ noDrivableNodeMessage,
+ type BrowserResolve,
+ type DriveDeps,
+ type LiveGuest
+} from './browser-drive'
+import { parseBrowserArgs, type BrowserCall } from '../core/browser-verb'
+
+const OWNER = 'claude-1'
+const NODE = 'browser-3'
+const okResolve: BrowserResolve = {
+ ok: true,
+ projectId: 'proj-1',
+ sourceControlCapable: true,
+ capabilityOn: true
+}
+
+/** A fake debugger that tracks whether it was ever ATTACHED — the whole point of "ledger.get before
+ * any attach" is that a refused caller causes zero attachments. */
+class FakeDebugger implements DebuggerLike {
+ attached = false
+ attachCount = 0
+ isAttached(): boolean {
+ return this.attached
+ }
+ attach(): void {
+ this.attached = true
+ this.attachCount++
+ }
+ detach(): void {
+ this.attached = false
+ }
+ on(): void {}
+ async sendCommand(method: string, params: object = {}): Promise<unknown> {
+ const p = params as Record<string, unknown>
+ switch (method) {
+ case 'DOM.getDocument':
+ return { root: { nodeId: 1 } }
+ case 'DOM.resolveNode':
+ return { object: { objectId: 'o' } }
+ case 'Runtime.callFunctionOn':
+ return { result: { value: p.functionDeclaration === NT_SCRIPTS.readTitle ? 'Home' : null } }
+ case 'Page.getNavigationHistory':
+ return { currentIndex: 0, entries: [{ url: 'https://x.test/' }] }
+ default:
+ return {}
+ }
+ }
+}
+
+function freshLedgerOwning(): BrowserControlLedger {
+ const ledger = new BrowserControlLedger()
+ ledger.claim(NODE, { ownerNodeId: OWNER, projectId: 'proj-1', partition: 'p', navGeneration: 0, leaseActiveUntil: 0, openedAt: 0 })
+ return ledger
+}
+
+function makeGuest(): { guest: LiveGuest; dbg: FakeDebugger } {
+ const dbg = new FakeDebugger()
+ const viewport = (): CdpContext => ({ viewport: { width: 800, height: 600 } })
+ const session = new BrowserSession({ nodeId: NODE, debugger: dbg, viewport })
+ return { guest: { session: session as Sendable, bus: new CdpEventBus() }, dbg }
+}
+
+function readTitleCall(): BrowserCall {
+ const c = parseBrowserArgs({ node: NODE, read: 'title' })
+ if ('error' in c) throw new Error(c.error)
+ return c
+}
+
+// ── the pure ordering ─────────────────────────────────────────────────────────────────────────
+describe('gateBrowserDrive — the refusal ORDER is the requirement', () => {
+ const base = () => ({
+ browserNodeId: NODE,
+ ownerNodeId: OWNER,
+ verified: true,
+ resolve: okResolve,
+ ledger: freshLedgerOwning(),
+ guestPresent: true
+ })
+
+ it('1. identity first — an unverified caller is refused before anything else', () => {
+ // Even with a broken everything-else, identity wins: nothing happened.
+ const g = gateBrowserDrive({ ...base(), verified: false, resolve: { ok: false, refusal: 'x' }, ledger: new BrowserControlLedger(), guestPresent: false })
+ expect(g).toEqual({ kind: 'refuse', message: STRICT_CONTROL_REFUSAL, revoke: false })
+ })
+
+ it('2. then canControlCanvas', () => {
+ const g = gateBrowserDrive({ ...base(), resolve: { ...okResolve, sourceControlCapable: false } })
+ expect(g).toEqual({ kind: 'refuse', message: BROWSER_SOURCE_NOT_CAPABLE, revoke: false })
+ })
+
+ it('3. then the per-project capability — verbatim sentence, and it REVOKES', () => {
+ const g = gateBrowserDrive({ ...base(), resolve: { ...okResolve, capabilityOn: false } })
+ expect(g).toEqual({ kind: 'refuse', message: BROWSER_CAPABILITY_OFF_MESSAGE, revoke: true })
+ })
+
+ it('4. then ledger ownership — "not yours" and "does not exist" are the SAME message', () => {
+ const notYours = gateBrowserDrive({ ...base(), ownerNodeId: 'claude-9' })
+ const notExist = gateBrowserDrive({ ...base(), browserNodeId: 'browser-9', ledger: freshLedgerOwning() })
+ expect(notYours).toEqual({ kind: 'refuse', message: noDrivableNodeMessage(NODE), revoke: false })
+ expect(notExist).toEqual({ kind: 'refuse', message: noDrivableNodeMessage('browser-9'), revoke: false })
+ })
+
+ it('5. finally discard — a released page is a lifecycle refusal, never a permissions one', () => {
+ const g = gateBrowserDrive({ ...base(), guestPresent: false })
+ expect(g).toEqual({ kind: 'refuse', message: browserDiscardedMessage(NODE), revoke: false })
+ })
+
+ it('all gates pass → drive, carrying the ledger entry', () => {
+ const g = gateBrowserDrive(base())
+ expect(g.kind).toBe('drive')
+ })
+})
+
+// ── carried obligation: ledger-gated ATTACH (PR 5/#306 MINOR-2) ─────────────────────────────────
+describe('the ledger gates the ATTACH, not just the reply', () => {
+ it('an unowned caller cannot drive AND never causes a debugger attach', async () => {
+ const ledger = new BrowserControlLedger() // nobody owns NODE
+ const { guest, dbg } = makeGuest()
+ const deps: DriveDeps = { ledger, refs: new RefTable(), sessionFor: () => guest, revoke: vi.fn() }
+ const r = await driveBrowser({ call: readTitleCall(), ownerNodeId: OWNER, verified: true, resolve: okResolve }, deps)
+ expect(r).toEqual({ ok: false, message: noDrivableNodeMessage(NODE) })
+ expect(dbg.attachCount).toBe(0) // the debugger was NEVER attached for a non-owner
+ })
+
+ it('the ledger-confirmed owner drives, and only THEN does the debugger attach', async () => {
+ const ledger = freshLedgerOwning()
+ const { guest, dbg } = makeGuest()
+ const deps: DriveDeps = { ledger, refs: new RefTable(), sessionFor: () => guest, revoke: vi.fn() }
+ const r = await driveBrowser({ call: readTitleCall(), ownerNodeId: OWNER, verified: true, resolve: okResolve }, deps)
+ expect(r.ok).toBe(true)
+ expect(dbg.attachCount).toBe(1)
+ })
+})
+
+// ── carried obligation: DRIVE-TIME live capability read + revoke (PR 6/#307 MINOR-2) ─────────────
+describe('capability is read LIVE at drive time and a now-off switch refuses AND revokes', () => {
+ it('a valid-at-attach lease is re-checked each drive; capability now off → refuse + revoke + no attach', async () => {
+ const ledger = freshLedgerOwning()
+ const { guest, dbg } = makeGuest()
+ const revoke = vi.fn()
+ const deps: DriveDeps = { ledger, refs: new RefTable(), sessionFor: () => guest, revoke }
+
+ // First drive: capability ON → drives.
+ const on = await driveBrowser({ call: readTitleCall(), ownerNodeId: OWNER, verified: true, resolve: { ...okResolve, capabilityOn: true } }, deps)
+ expect(on.ok).toBe(true)
+
+ // Same lease, next verb: a project.json hand-edit flipped the switch OFF (a FRESH resolve says so).
+ const off = await driveBrowser({ call: readTitleCall(), ownerNodeId: OWNER, verified: true, resolve: { ...okResolve, capabilityOn: false } }, deps)
+ expect(off).toEqual({ ok: false, message: BROWSER_CAPABILITY_OFF_MESSAGE })
+ expect(revoke).toHaveBeenCalledWith(NODE) // detaches + drops + tombstones
+ // The off-drive attempts no new attach of its own.
+ expect(dbg.attachCount).toBe(1)
+ })
+})
+
+// ── carried obligation: honor the #307 tombstone ────────────────────────────────────────────────
+describe('a user-Stopped node refuses to re-drive until a fresh verified claim (#307 tombstone)', () => {
+ it('after the USER stops control, its owner is refused with the named human act — not a retryable null', async () => {
+ const ledger = freshLedgerOwning()
+ ledger.stopByUser(NODE) // chip / menu / Settings / switch-off
+ const { guest, dbg } = makeGuest()
+ const deps: DriveDeps = { ledger, refs: new RefTable(), sessionFor: () => guest, revoke: vi.fn() }
+ const r = await driveBrowser({ call: readTitleCall(), ownerNodeId: OWNER, verified: true, resolve: okResolve }, deps)
+ expect(r).toEqual({ ok: false, message: BROWSER_USER_STOPPED })
+ expect(dbg.attachCount).toBe(0)
+ })
+
+ it('the tombstone clears ONLY via a fresh claim — then the same owner drives again', async () => {
+ const ledger = freshLedgerOwning()
+ ledger.stopByUser(NODE)
+ expect(ledger.wasStoppedByUser(NODE, OWNER)).toBe(true)
+ // A fresh, verified open-browser re-claims the node (ids are not reused in practice, but the
+ // tombstone-clear on claim is the contract).
+ ledger.claim(NODE, { ownerNodeId: OWNER, projectId: 'proj-1', partition: 'p', navGeneration: 0, leaseActiveUntil: 0, openedAt: 0 })
+ expect(ledger.wasStoppedByUser(NODE, OWNER)).toBe(false)
+ const { guest } = makeGuest()
+ const deps: DriveDeps = { ledger, refs: new RefTable(), sessionFor: () => guest, revoke: vi.fn() }
+ const r = await driveBrowser({ call: readTitleCall(), ownerNodeId: OWNER, verified: true, resolve: okResolve }, deps)
+ expect(r.ok).toBe(true)
+ })
+})
+
+describe('driveBrowser end-to-end refusals', () => {
+ it('a discarded guest (sessionFor → null) is the named discard refusal', async () => {
+ const ledger = freshLedgerOwning()
+ const deps: DriveDeps = { ledger, refs: new RefTable(), sessionFor: () => null, revoke: vi.fn() }
+ const r = await driveBrowser({ call: readTitleCall(), ownerNodeId: OWNER, verified: true, resolve: okResolve }, deps)
+ expect(r).toEqual({ ok: false, message: browserDiscardedMessage(NODE) })
+ })
+
+ it('an unverified caller is refused with the flat strict sentence', async () => {
+ const ledger = freshLedgerOwning()
+ const { guest } = makeGuest()
+ const deps: DriveDeps = { ledger, refs: new RefTable(), sessionFor: () => guest, revoke: vi.fn() }
+ const r = await driveBrowser({ call: readTitleCall(), ownerNodeId: OWNER, verified: false, resolve: okResolve }, deps)
+ expect(r).toEqual({ ok: false, message: STRICT_CONTROL_REFUSAL })
+ })
+})
diff --git a/src/main/browser-drive.ts b/src/main/browser-drive.ts
new file mode 100644
index 000000000..fb5b3e6b9
--- /dev/null
+++ b/src/main/browser-drive.ts
@@ -0,0 +1,201 @@
+/**
+ * THE drive gate and orchestration for the `browser` verb. This is where browser driving goes live:
+ * everything before PR 7 was inert machinery, and this module is the producer that attaches a lease
+ * and drives a real guest. So it is the highest-stakes security surface of the set, and its whole
+ * job is to REFUSE before it drives, in a fixed order, main-side, trusting no caller field.
+ *
+ * THE ORDER IS THE REQUIREMENT (design §2.3, Task 7.2), and every step fails closed:
+ * 1. IDENTITY — a non-`verified` caller is refused before anything else, because the promise of a
+ * refusal is that nothing happened. (`browser` is verified-only via STRICT_CONTROL_VERBS, which
+ * hook-server enforces before this handler; this is the belt.)
+ * 2. canControlCanvas — the source agent kind must be canvas-control-capable.
+ * 3. the PER-PROJECT capability, read LIVE at drive time — a switch on at attach but now off
+ * (including a project.json hand-edit) REFUSES and REVOKES (carried obligation, PR 6/#307
+ * MINOR-2). The message is the design's verbatim sentence: the agent cannot turn it on itself.
+ * 4. LEDGER OWNERSHIP — before ANY attach, `browser-control-ledger.get()` keyed on the
+ * cryptographically-verified caller node id must return this owner's entry (carried obligation,
+ * PR 5/#306 MINOR-2). "Does not exist" and "exists but is not yours" are the SAME message —
+ * a different one is a node-enumeration oracle. A node the USER stopped (#307 tombstone) is
+ * refused with the named human act and cannot re-drive until a fresh verified `claim()`.
+ * 5. DISCARD — a node whose page the memory saver released is a lifecycle refusal, never a
+ * permissions one.
+ *
+ * Only after all five does a debugger attach (lazily, on the first send inside {@link browserNav}/
+ * the reads), so a refused caller never causes an attachment. `src/main`, never Server Edition.
+ */
+import {
+ BrowserControlLedger,
+ BROWSER_USER_STOPPED,
+ type AgentBrowserEntry
+} 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 type { RefTable } from './browser-refs'
+import type { BrowserCall } from '../core/browser-verb'
+
+/** The design's verbatim capability-off sentence. The last clause STOPS an agent burning a turn
+ * trying to enable it. Exported so the wiring and the tests share the one string. */
+export const BROWSER_CAPABILITY_OFF_MESSAGE =
+ "Browser control is off for this project. The user can turn it on in the project's Agents settings; you cannot."
+
+/** The refusal when the source node is not a control-capable agent (step 2). Same wording every
+ * other verb's renderer path uses, so the caller learns the same way. */
+export const BROWSER_SOURCE_NOT_CAPABLE = 'source node is not a control-capable agent'
+
+/** "Does not exist" AND "exists but is not yours" — ONE message, adopted verbatim from S8's
+ * requireTab, because a distinct message is a node-enumeration oracle. */
+export const noDrivableNodeMessage = (id: string): string => `no drivable browser node "${id}"`
+
+/** What the renderer alone knows, answered over the resolve round-trip: the owning project of the
+ * source, whether the source is control-capable, and the LIVE per-project capability value. Main
+ * makes the security DECISION from this; the renderer never runs a CDP command. */
+export type BrowserResolve =
+ | { ok: true; projectId: string; projectCwd?: string; sourceControlCapable: boolean; capabilityOn: boolean }
+ | { ok: false; refusal: string }
+
+/** The resolve round-trip's own short ceiling. Kept far under main's 120s pending-control budget and
+ * the route's 130s ceiling: a canvas that does not answer is a NAMED failure in 2s, never a hang
+ * that eats the whole budget while the agent waits. */
+export const BROWSER_RESOLVE_TIMEOUT_MS = 2000
+
+/** The resolve failed to come back in time. A named, retryable refusal — not a hang, not a
+ * permissions verdict. */
+export const browserResolveTimedOut = (id: string): string =>
+ `browser: the canvas did not answer for ${id} in time — try again`
+
+/**
+ * Ask the renderer to resolve a browser target, but never let that round-trip hang: it races the
+ * renderer's answer against a 2s timeout, and a rejection (the window went away) is the same named
+ * failure. This is the piece that keeps a slow/absent canvas from consuming the 120s pending-control
+ * budget — injected `ask` so the timeout behaviour is unit-testable without Electron.
+ */
+export async function resolveBrowserTarget(
+ browserNodeId: string,
+ ask: () => Promise<BrowserResolve>,
+ timeoutMs: number = BROWSER_RESOLVE_TIMEOUT_MS
+): Promise<BrowserResolve> {
+ const timedOut: BrowserResolve = { ok: false, refusal: browserResolveTimedOut(browserNodeId) }
+ const timeout = new Promise<BrowserResolve>((resolve) => setTimeout(() => resolve(timedOut), timeoutMs))
+ const answer = ask().catch((): BrowserResolve => timedOut)
+ return Promise.race([answer, timeout])
+}
+
+export interface DriveGateInput {
+ browserNodeId: string
+ /** The cryptographically-verified caller node id (main's own verdict, #304). */
+ ownerNodeId: string
+ /** main's own `verdict === 'verified'` for THIS request — never a wire/caller field. */
+ verified: boolean
+ resolve: BrowserResolve
+ ledger: BrowserControlLedger
+ /** Is there a live canvas guest for this node (else the memory saver released it)? */
+ guestPresent: boolean
+}
+
+export type DriveGate =
+ | { kind: 'refuse'; message: string; revoke: boolean }
+ | { kind: 'drive'; entry: AgentBrowserEntry }
+
+/**
+ * The pure decision. Returns the single refusal (with whether to also revoke) or a go-ahead carrying
+ * the ledger entry. No I/O, no attach — so the ordering is unit-testable exactly.
+ */
+export function gateBrowserDrive(input: DriveGateInput): DriveGate {
+ // 1. identity
+ if (!input.verified) return { kind: 'refuse', message: STRICT_CONTROL_REFUSAL, revoke: false }
+ // (resolve failed → the source is not on an open canvas at all; a named, non-revoking refusal)
+ if (!input.resolve.ok) return { kind: 'refuse', message: input.resolve.refusal, revoke: false }
+ // 2. canControlCanvas
+ if (!input.resolve.sourceControlCapable) {
+ return { kind: 'refuse', message: BROWSER_SOURCE_NOT_CAPABLE, revoke: false }
+ }
+ // 3. per-project capability, LIVE — and a now-off switch revokes as well as refuses.
+ if (!input.resolve.capabilityOn) {
+ return { kind: 'refuse', message: BROWSER_CAPABILITY_OFF_MESSAGE, revoke: true }
+ }
+ // 4. ledger ownership — before any attach. Tombstone (user-Stopped) is named; everything else is
+ // the one non-enumerating message.
+ const entry = input.ledger.get(input.browserNodeId, input.ownerNodeId)
+ if (!entry) {
+ if (input.ledger.wasStoppedByUser(input.browserNodeId, input.ownerNodeId)) {
+ return { kind: 'refuse', message: BROWSER_USER_STOPPED, revoke: false }
+ }
+ return { kind: 'refuse', message: noDrivableNodeMessage(input.browserNodeId), revoke: false }
+ }
+ // 5. discard
+ if (!input.guestPresent) {
+ return { kind: 'refuse', message: browserDiscardedMessage(input.browserNodeId), revoke: false }
+ }
+ return { kind: 'drive', entry }
+}
+
+/** The live control session + event bus for a node's CANVAS guest (Task 2.2: the canvas surface is
+ * the only drivable one). Attaching is LAZY inside the session, so getting one costs no debugger
+ * attach — that is what keeps "ledger.get before any attach" true. */
+export interface LiveGuest {
+ session: Sendable
+ bus: CdpEventBus
+}
+
+export interface DriveDeps {
+ ledger: BrowserControlLedger
+ refs: RefTable
+ /** The canvas guest's session+bus, or null when its page was released (discard). MUST NOT attach. */
+ sessionFor(browserNodeId: string): LiveGuest | null
+ /** Detach + drop ownership + tombstone — invoked when a live capability read comes back OFF. */
+ revoke(browserNodeId: string): void
+}
+
+async function runAction(
+ call: BrowserCall,
+ guest: LiveGuest,
+ refs: RefTable,
+ nodeId: string
+): Promise<ActionResult> {
+ const a = call.action
+ switch (a.kind) {
+ case 'nav':
+ return browserNav(guest.session, guest.bus, nodeId, a.url, call.timeoutMs)
+ case 'read':
+ return browserRead(guest.session, guest.bus, refs, nodeId, a.mode, {
+ selector: call.selector,
+ max: call.max
+ })
+ 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.
+ return { ok: false, message: `browser: --${a.kind} is not available yet (it lands in a later update)` }
+ }
+}
+
+/**
+ * Gate, then drive. The one entry point main wires the verb to. A refusal that carries `revoke`
+ * detaches+drops first; a go-ahead runs the action, converting any thrown allowlist/lease refusal
+ * into a named `ok:false` (never a hang, never a raw Electron error).
+ */
+export async function driveBrowser(
+ input: { call: BrowserCall; ownerNodeId: string; verified: boolean; resolve: BrowserResolve },
+ deps: DriveDeps
+): Promise<ActionResult> {
+ const guest = deps.sessionFor(input.call.node)
+ const gate = gateBrowserDrive({
+ browserNodeId: input.call.node,
+ ownerNodeId: input.ownerNodeId,
+ verified: input.verified,
+ resolve: input.resolve,
+ ledger: deps.ledger,
+ guestPresent: guest !== null
+ })
+ if (gate.kind === 'refuse') {
+ if (gate.revoke) deps.revoke(input.call.node)
+ return { ok: false, message: gate.message }
+ }
+ // guestPresent was true, so `guest` is non-null; the check keeps the type honest.
+ if (!guest) return { ok: false, message: browserDiscardedMessage(input.call.node) }
+ try {
+ return await runAction(input.call, guest, deps.refs, input.call.node)
+ } catch (e) {
+ return { ok: false, message: e instanceof Error ? e.message : 'browser: the command failed' }
+ }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 1ea058c15..0344391a3 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -16,7 +16,17 @@ installLogSink(logBuffer)
import { writeFilesToClipboard } from './clipboard-files'
import { allowGuestNavigation } from './webview-nav'
import { BrowserControlLedger } from './browser-control-ledger'
-import { BrowserLeaseManager } from './browser-lease'
+import { BrowserLeaseManager, BrowserSession } from './browser-lease'
+import { CdpEventBus, type Sendable } from './browser-actions'
+import { RefTable } from './browser-refs'
+import {
+ driveBrowser,
+ resolveBrowserTarget,
+ type BrowserResolve,
+ type LiveGuest
+} from './browser-drive'
+import { parseBrowserArgs } from '../core/browser-verb'
+import { STRICT_CONTROL_REFUSAL } from '../core/agents/node-identity-policy'
import {
revokeBrowserNode,
revokeBrowserByOwner,
@@ -2346,7 +2356,104 @@ app.whenReady().then(async () => {
// automatic triggers) is fully live, because `release` is a no-op-safe detach for a node with no
// session. Owned here so all the wiring has one home. See browser-lease.ts / browser-revocation.ts.
const browserLeases = new BrowserLeaseManager()
- const browserRevocation: RevocationTargets = { leases: browserLeases, ledger: browserLedger }
+ // @ref bookkeeping (Task 5.5), one table for every driven node; nav bumps a node's generation.
+ const browserRefs = new RefTable()
+ // Per-node event bus (fixed CDP event set → our own state) and the `debugger.on('message')`
+ // listener we registered for it, kept so a teardown removes exactly that listener (a released and
+ // re-created session must not leave a duplicate listener firing on the same debugger).
+ const browserBuses = new Map<string, CdpEventBus>()
+ const browserMsgListeners = new Map<
+ string,
+ { dbg: { removeListener(event: string, fn: (...a: unknown[]) => void): void }; fn: (...a: unknown[]) => void }
+ >()
+ // Tear down the driver-side state for one node (its lease/session is being released). Removes the
+ // exact message listener and forgets the bus + refs, so nothing keeps driving a released node.
+ const browserDriverTeardown = (nodeId: string): void => {
+ const l = browserMsgListeners.get(nodeId)
+ if (l) {
+ try {
+ l.dbg.removeListener('message', l.fn)
+ } catch {
+ /* a destroyed debugger throws; the map cleanup below is what matters */
+ }
+ browserMsgListeners.delete(nodeId)
+ }
+ browserBuses.delete(nodeId)
+ browserRefs.forget(nodeId)
+ }
+ // Revocation releases the lease (detach + reject in-flight) AND tears down the driver state, in one
+ // place, whatever triggered it — so a Stop can never leave a page still drivable.
+ const browserRevocation: RevocationTargets = {
+ leases: {
+ release: (nodeId: string) => {
+ browserLeases.release(nodeId)
+ browserDriverTeardown(nodeId)
+ }
+ },
+ ledger: browserLedger
+ }
+ // The live control session + event bus for a node's CANVAS <webview> guest (Task 2.2: the canvas
+ // surface is the only drivable one — a modal guest is never driven). Attaching is LAZY inside the
+ // session, so getting one costs no debugger attach; that is what keeps "ledger.get() before any
+ // attach" literally true. Returns null when the guest's page is gone (the memory saver released
+ // it), which the drive gate turns into the named discard refusal.
+ const canvasGuestWcId = (browserNodeId: string): number | undefined => {
+ let unknownSurface: number | undefined
+ for (const [wcId, g] of browserGuests) {
+ if (g.nodeId !== browserNodeId) continue
+ if (g.surface === 'canvas') return wcId
+ // `surface` is `undefined` until both mount sites are threaded (guest-registry): treat it as
+ // the canvas fallback (the common case is one canvas guest), but NEVER drive a `'modal'` one.
+ if (g.surface === undefined) unknownSurface = wcId
+ }
+ return unknownSurface
+ }
+ const browserSessionFor = (browserNodeId: string): LiveGuest | null => {
+ const wcId = canvasGuestWcId(browserNodeId)
+ if (wcId === undefined) return null
+ const wc = webContents.fromId(wcId)
+ if (!wc || wc.isDestroyed()) return null
+ const existing = browserLeases.get(browserNodeId)
+ const existingBus = browserBuses.get(browserNodeId)
+ if (existing && existingBus) return { session: existing as unknown as Sendable, bus: existingBus }
+ // Fresh driver: the bus bumps this node's ref generation on a main-frame navigation / context
+ // clear (Task 5.5), the session pushes its lease to the ledger + renderer on every verb (which is
+ // what lights the driving chip), and the message listener feeds the fixed CDP event set into the
+ // bus — nothing is streamed to the agent.
+ const bus = new CdpEventBus(() => browserRefs.bumpGeneration(browserNodeId))
+ const session = new BrowserSession({
+ nodeId: browserNodeId,
+ debugger: wc.debugger,
+ // Coordinates are unused by --nav/--read; PR 8's pointer verbs refresh this from
+ // Page.getLayoutMetrics before dispatching a bounded mouse event.
+ viewport: () => ({ viewport: { width: 0, height: 0 } }),
+ isDevToolsOpen: () => {
+ try {
+ return wc.isDevToolsOpened()
+ } catch {
+ return false
+ }
+ },
+ onLeaseChange: (until) => {
+ browserLedger.touchLease(browserNodeId, until)
+ pushBrowserLeases()
+ }
+ })
+ const fn = (_e: unknown, method: string, params: unknown): void => bus.emit(method, params)
+ wc.debugger.on('message', fn)
+ browserLeases.set(browserNodeId, session)
+ browserBuses.set(browserNodeId, bus)
+ browserMsgListeners.set(browserNodeId, {
+ dbg: wc.debugger as unknown as { removeListener(e: string, f: (...a: unknown[]) => void): void },
+ fn: fn as unknown as (...a: unknown[]) => void
+ })
+ return { session: session as unknown as Sendable, bus }
+ }
+ // The 60s idle detach (browser-lease.ts): drop the debugger attachment on nodes gone quiet, so an
+ // attachment never outlives its usefulness. The session stays in the map and re-attaches on the
+ // next verb; only the debugger handle is released. Unref'd so it never holds the process open.
+ const browserIdleSweep = setInterval(() => browserLeases.sweepIdle(Date.now()), 30_000)
+ browserIdleSweep.unref?.()
// Push the current driven-lease set to the renderer (chip / rope / kill row). `stopped` ids drop
// from the chip immediately, skipping the anti-flicker linger — that is how an explicit Stop hides
// at once while a merely-idle lease fades.
@@ -2405,7 +2512,88 @@ app.whenReady().then(async () => {
pending.resolve(payload)
}
)
+ // The `browser` verb resolve round-trip (Task 7.2). Main asks the renderer to resolve a source
+ // node's owning project, control-capability and the LIVE per-project capability value; the renderer
+ // answers here. Modelled on `pendingControl`, but its own map with its own short (2s) timeout so a
+ // slow canvas can NEVER consume the 120s pending-control budget.
+ const pendingBrowserResolve = new Map<string, (r: BrowserResolve) => void>()
+ ipcMain.on(
+ IPC.browserControlResolveResult,
+ (
+ _e,
+ payload: {
+ requestId: string
+ ok: boolean
+ refusal?: string
+ projectId?: string
+ projectCwd?: string
+ sourceControlCapable?: boolean
+ capabilityOn?: boolean
+ }
+ ) => {
+ const resolve = pendingBrowserResolve.get(payload.requestId)
+ if (!resolve) return
+ pendingBrowserResolve.delete(payload.requestId)
+ resolve(
+ payload.ok
+ ? {
+ ok: true,
+ projectId: payload.projectId ?? '',
+ projectCwd: payload.projectCwd,
+ sourceControlCapable: payload.sourceControlCapable === true,
+ capabilityOn: payload.capabilityOn === true
+ }
+ : { ok: false, refusal: payload.refusal ?? 'source node is not on an open canvas' }
+ )
+ }
+ )
+ // Ask the renderer to resolve a source node — the `ask` closure `resolveBrowserTarget` races
+ // against its own 2s timeout. The renderer NEVER runs a CDP command; it answers existence + project
+ // + capability only.
+ const askRendererResolve = (sourceNodeId: string): Promise<BrowserResolve> => {
+ const w = getMainWindow()
+ if (!w || w.isDestroyed()) {
+ return Promise.resolve({ ok: false, refusal: 'source node is not on an open canvas' })
+ }
+ const requestId = randomUUID()
+ const answered = new Promise<BrowserResolve>((resolve) => {
+ pendingBrowserResolve.set(requestId, resolve)
+ })
+ w.webContents.send(IPC.browserControlResolve, { requestId, sourceNodeId })
+ return answered.finally(() => pendingBrowserResolve.delete(requestId))
+ }
+ // The `browser` verb's whole main-side drive: parse (pure), identity belt, resolve round-trip, then
+ // the gate + drive (owner + LIVE capability + CDP allowlist all decided here in MAIN). A capability
+ // read that comes back OFF revokes as it refuses (detach + drop + tombstone). See browser-drive.ts.
+ const handleBrowserVerb = async (
+ nodeId: string,
+ args: Record<string, string>,
+ verified: boolean
+ ): Promise<{ ok: boolean; message?: string; error?: string }> => {
+ const parsed = parseBrowserArgs(args)
+ if ('error' in parsed) return { ok: false, error: parsed.error, message: parsed.error }
+ // Identity is checked first (the belt to hook-server's verified-only gate for STRICT verbs): a
+ // non-verified caller learns nothing, and no resolve round-trip is even made.
+ if (!verified) return { ok: false, error: STRICT_CONTROL_REFUSAL, message: STRICT_CONTROL_REFUSAL }
+ const resolve = await resolveBrowserTarget(parsed.node, () => askRendererResolve(nodeId))
+ const result = await driveBrowser(
+ { call: parsed, ownerNodeId: nodeId, verified, resolve },
+ {
+ ledger: browserLedger,
+ refs: browserRefs,
+ sessionFor: browserSessionFor,
+ revoke: (id) => pushBrowserLeases(revokeBrowserNode(id, browserRevocation, { userStopped: true }))
+ }
+ )
+ return result.ok
+ ? { ok: true, message: result.message }
+ : { ok: false, error: result.message, message: result.message }
+ }
hookServer.setControlHandler(async ({ verb, nodeId, args, verified }) => {
+ // `browser` is answered in MAIN and never forwarded to the renderer's agent-control dispatch:
+ // the debugger handle and the CDP allowlist are main-side, and the renderer is the more
+ // attackable half. Every other verb still round-trips to the renderer below.
+ if (verb === 'browser') return handleBrowserVerb(nodeId, args, verified)
const target = getMainWindow()
if (!target) return { ok: false, error: 'window unavailable' }
const requestId = randomUUID()
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 13b73d70c..45e1fdf5c 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -650,6 +650,15 @@ const api: NodeTerminalApi = {
return () => ipcRenderer.removeListener(IPC.agentControl, handler)
},
sendAgentControlResult: (payload) => ipcRenderer.send(IPC.agentControlResult, payload),
+ // The `browser` verb resolve round-trip (S8 PR 7): main asks the renderer which project owns the
+ // source, whether it is control-capable, and whether the capability is on right now — the renderer
+ // NEVER runs a CDP command.
+ onBrowserControlResolve: (listener) => {
+ const handler = (_e: unknown, req: unknown) => listener(req as never)
+ ipcRenderer.on(IPC.browserControlResolve, handler)
+ return () => ipcRenderer.removeListener(IPC.browserControlResolve, handler)
+ },
+ sendBrowserControlResolveResult: (payload) => ipcRenderer.send(IPC.browserControlResolveResult, payload),
agentMessage: {
deliver: (req) => ipcRenderer.invoke(IPC.agentMessageDeliver, req)
}
diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.ts
index 32f45cbeb..b15276571 100644
--- a/src/renderer/bridge/relay-api.ts
+++ b/src/renderer/bridge/relay-api.ts
@@ -149,6 +149,9 @@ export function buildRelayApi(connectionId: string, transport?: FrameTransport):
// Edition); inert no-ops rather than a local subscription that never carries the host's events.
onAgentControl: stub.onAgentControl,
sendAgentControlResult: stub.sendAgentControlResult,
+ // Browser control never rides the relay either (no CDP off the desktop) — inert no-ops.
+ onBrowserControlResolve: stub.onBrowserControlResolve,
+ sendBrowserControlResolveResult: stub.sendBrowserControlResolveResult,
// Messaging rides the same decision: the browser client is never a sender (constraint 5 of
// the messaging plan — the phone drives canvas control over relay→IPC, not /control/*).
agentMessage: stub.agentMessage
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 244ea190b..6188df37a 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -407,6 +407,10 @@ export function buildStubApi(): Omit<
}),
onAgentControl: noopUnsub,
sendAgentControlResult: noop,
+ // Browser control is desktop-only (no <webview>, no CDP on the Server Edition / relay), so the
+ // resolve round-trip is inert here — the verb is refused by name before it reaches a handler.
+ onBrowserControlResolve: noopUnsub,
+ sendBrowserControlResolveResult: noop,
// Messaging never runs in the browser: `onAgentControl` above is inert here, so no dispatch
// can ever reach this. It answers the honest terminal refusal all the same, so a stray call
// can never look like it delivered.
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 8045f411b..cd19af59d 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -183,7 +183,9 @@ import {
routeControlSource,
needsLiveCanvas,
sourceIsControlCapable,
- storedNodeListing
+ storedNodeListing,
+ answerBrowserResolve,
+ type BrowserResolveProject
} from '../lib/controlRouting'
import { applyStickyWrite, parseStickyArgs, resolveStickyRef } from '../lib/stickyWrite'
import {
@@ -6382,6 +6384,27 @@ export function Canvas() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
+ // The `browser` verb's resolve round-trip (S8 PR 7). Main intercepts `browser` and asks us the
+ // two-and-a-half things ONLY the renderer knows: which project owns the source node, whether that
+ // source is a control-capable agent, and whether the per-project browser-control capability is on
+ // RIGHT NOW (read live via projectCapabilityGrantedFor). We answer over the SAME source routing
+ // every verb uses — travelling to the owning project so its <webview> guest is live for main to
+ // drive — and we NEVER run a CDP command. Main makes the security decision (owner + capability +
+ // the CDP allowlist) and does the driving itself (browser-drive.ts / browser-actions.ts).
+ useEffect(() => {
+ return api.onBrowserControlResolve(({ requestId, sourceNodeId }) => {
+ const { projects, activeProjectId } = useProjects.getState()
+ const route = routeControlSource(projects, activeProjectId, sourceNodeId)
+ // Bring the owning project's canvas up so main can find the live guest (needsLiveCanvas is true
+ // for `browser`). A closed/blocked/unknown owner just yields the refusal below.
+ if (route.kind === 'switch' || route.kind === 'reopen') travelToProjectRef.current(route.projectId)
+ const owner = projects.find((p) => p.nodes.some((n) => n.id === sourceNodeId))
+ const answer = answerBrowserResolve(owner as unknown as BrowserResolveProject | undefined, sourceNodeId)
+ api.sendBrowserControlResolveResult({ requestId, ...answer })
+ })
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+
// Apply canvas-control commands issued by a control-capable agent's `nodeterm` CLI. Reads the
// LATEST nodes via nodesRef (so the effect deps stay []), validates the source as the real
// authorization boundary, then applies the verb. Non-destructive verbs (list/open-*/show-*)
diff --git a/src/renderer/lib/controlRouting.test.ts b/src/renderer/lib/controlRouting.test.ts
index 2e6e8d83c..a29cb5e22 100644
--- a/src/renderer/lib/controlRouting.test.ts
+++ b/src/renderer/lib/controlRouting.test.ts
@@ -4,7 +4,9 @@ import {
needsLiveCanvas,
sourceIsControlCapable,
storedNodeListing,
- type ControlProject
+ answerBrowserResolve,
+ type ControlProject,
+ type BrowserResolveProject
} from './controlRouting'
const P = (
@@ -107,6 +109,64 @@ describe('sourceIsControlCapable', () => {
})
})
+describe('the `browser` verb needs the LIVE canvas', () => {
+ it('needsLiveCanvas(browser) is true — the node lives in a specific project canvas, like open-browser', () => {
+ // It drives a real <webview> that only exists on the live canvas; it is NOT store-answerable.
+ expect(needsLiveCanvas('browser')).toBe(true)
+ expect(needsLiveCanvas('open-browser')).toBe(true)
+ // Contrast with the store-answered verbs.
+ expect(needsLiveCanvas('list')).toBe(false)
+ expect(needsLiveCanvas('send')).toBe(false)
+ })
+})
+
+describe('answerBrowserResolve — the renderer answers ONLY what it alone knows', () => {
+ const proj = (over: Partial<BrowserResolveProject> = {}): BrowserResolveProject => ({
+ id: 'proj-1',
+ cwd: '/home/u/p',
+ nodes: [{ id: 'claude-1', agentId: 'claude' }],
+ ...over
+ })
+
+ it('a missing project or an off-canvas source is a named, non-CDP refusal', () => {
+ expect(answerBrowserResolve(undefined, 'claude-1')).toEqual({
+ ok: false,
+ refusal: 'source node is not on an open canvas'
+ })
+ expect(answerBrowserResolve(proj(), 'ghost-9')).toEqual({
+ ok: false,
+ refusal: 'source node is not on an open canvas'
+ })
+ })
+
+ it('reports project, cwd, source-capability and the LIVE per-project capability value', () => {
+ // Switch on in the file AND kept on this machine ⇒ granted.
+ const granted = proj({ agentBrowserControl: true, capabilityAck: { agentBrowserControl: 'kept' } })
+ expect(answerBrowserResolve(granted, 'claude-1')).toEqual({
+ ok: true,
+ projectId: 'proj-1',
+ projectCwd: '/home/u/p',
+ sourceControlCapable: true,
+ capabilityOn: true
+ })
+ })
+
+ it('a switch that is ON in the file but only PENDING (never kept) is not on — a pending notice is a refusal', () => {
+ const pending = proj({ agentBrowserControl: true })
+ expect(answerBrowserResolve(pending, 'claude-1')).toMatchObject({ ok: true, capabilityOn: false })
+ })
+
+ it('a DECLINED switch is off even when the file says true (C1: the hostile clone must not grant)', () => {
+ const declined = proj({ agentBrowserControl: true, capabilityAck: { agentBrowserControl: 'declined' } })
+ expect(answerBrowserResolve(declined, 'claude-1')).toMatchObject({ ok: true, capabilityOn: false })
+ })
+
+ it('a non-control-capable source is reported as such (main turns it into the refusal)', () => {
+ const p = proj({ nodes: [{ id: 'x-1', agentId: 'cursor' }], agentBrowserControl: true, capabilityAck: { agentBrowserControl: 'kept' } })
+ expect(answerBrowserResolve(p, 'x-1')).toMatchObject({ ok: true, sourceControlCapable: false })
+ })
+})
+
describe('storedNodeListing', () => {
it('renders serialized nodes in the same shape the live canvas answers `list` with', () => {
expect(
diff --git a/src/renderer/lib/controlRouting.ts b/src/renderer/lib/controlRouting.ts
index a256fa769..e802ddaef 100644
--- a/src/renderer/lib/controlRouting.ts
+++ b/src/renderer/lib/controlRouting.ts
@@ -15,6 +15,10 @@
import { canControlCanvas, type AgentId } from '@shared/agents/config'
import { projectTravel } from './presenceTravel'
+import {
+ projectCapabilityGrantedFor,
+ type CapabilityAckMap
+} from '@shared/project-capability-consent'
/** The little the routing needs to know about a project (a structural subset of `Project`). */
export interface ControlProject {
@@ -119,6 +123,60 @@ export function sourceIsControlCapable(agentId: unknown): boolean {
return canControlCanvas(id as AgentId)
}
+/**
+ * The `browser` verb's resolve answer — the two things ONLY the renderer knows, computed purely so
+ * Canvas.tsx's IPC handler is a thin wrapper testable here. Main asks over `browserControlResolve`,
+ * makes the security decision itself (owner + capability + CDP gate), and does the CDP work; this
+ * function NEVER touches a debugger.
+ *
+ * WHY MAIN STILL DECIDES from these facts: an XSS-in-a-node-title-style bug lands in the renderer,
+ * the more attackable half, so the allowlist and the ledger stay main-side. The renderer reports
+ * facts (does this node's project exist, is the source control-capable, is the capability on right
+ * now — read LIVE via `projectCapabilityGrantedFor`, never cached); main re-orders them into the
+ * refusal decision in `browser-drive.ts`.
+ */
+export interface BrowserResolveNode {
+ id: string
+ agentId?: unknown
+}
+export interface BrowserResolveProject {
+ id: string
+ cwd?: string
+ agentBrowserControl?: boolean
+ capabilityAck?: CapabilityAckMap
+ nodes: readonly BrowserResolveNode[]
+}
+export type BrowserResolveAnswer =
+ | { ok: false; refusal: string }
+ | {
+ ok: true
+ projectId: string
+ projectCwd?: string
+ sourceControlCapable: boolean
+ capabilityOn: boolean
+ }
+
+export function answerBrowserResolve(
+ project: BrowserResolveProject | undefined,
+ sourceNodeId: string
+): BrowserResolveAnswer {
+ // No open project owns the source, or the node is not on its canvas: a named, non-revoking
+ // refusal. (Same class as every other verb's "source node is not on an open canvas".)
+ if (!project) return { ok: false, refusal: 'source node is not on an open canvas' }
+ const node = project.nodes.find((n) => n.id === sourceNodeId)
+ if (!node) return { ok: false, refusal: 'source node is not on an open canvas' }
+ return {
+ ok: true,
+ projectId: project.id,
+ projectCwd: project.cwd,
+ sourceControlCapable: sourceIsControlCapable(node.agentId),
+ // LIVE read — the drive-time capability check the whole feature's safety rests on. A project.json
+ // hand-edit that flipped the switch off is reflected here the next time an agent drives, which is
+ // exactly drive time.
+ capabilityOn: projectCapabilityGrantedFor(project, 'agentBrowserControl')
+ }
+}
+
/** `list`'s rows, built from serialized nodes — the same shape the live canvas answers with
* (`n.type` is the persisted `kind`, `n.data.title` the persisted `title`). */
export function storedNodeListing(
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index d3e05deb9..b815d7bf1 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -364,6 +364,13 @@ export const IPC = {
browserStop: 'browser:stop-control',
browserStopAll: 'browser:stop-control-all',
browserStopProject: 'browser:stop-control-project',
+ // The `browser` VERB resolve round-trip (S8 PR 7). Main intercepts `browser` and asks the renderer
+ // the two things ONLY it knows — which project owns the source node, whether that source is a
+ // control-capable agent, and whether the per-project capability is on RIGHT NOW — over the same
+ // routing every verb uses. Main makes the security decision (owner + capability + CDP gate) and
+ // does the CDP work itself; the renderer never runs a CDP command.
+ browserControlResolve: 'browser:control-resolve',
+ browserControlResolveResult: 'browser:control-resolve-result',
remoteHostStart: 'remote:host:start',
remoteHostStop: 'remote:host:stop',
// Connection approval gate: main → renderer when a client finishes the handshake (carries the
diff --git a/src/shared/types.ts b/src/shared/types.ts
index f906cad00..9d3b551c5 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2589,6 +2589,21 @@ export interface NodeTerminalApi {
result?: unknown
error?: string
}): void
+ /** The `browser` verb resolve round-trip (S8 PR 7): main asks the renderer to resolve a source
+ * node's owning project, control-capability and the LIVE per-project capability value. The
+ * renderer answers over `sendBrowserControlResolveResult` and NEVER runs a CDP command. */
+ onBrowserControlResolve(listener: (req: { requestId: string; sourceNodeId: string }) => void): () => void
+ /** Answer a browser-control resolve. `ok:false` carries a named refusal; `ok:true` carries the
+ * facts main turns into its own (owner + capability + CDP-gate) decision. */
+ sendBrowserControlResolveResult(payload: {
+ requestId: string
+ ok: boolean
+ refusal?: string
+ projectId?: string
+ projectCwd?: string
+ sourceControlCapable?: boolean
+ capabilityOn?: boolean
+ }): void
/** Agent messaging (the `send`/`reply` control verbs): run one delivery in main, where the
* scope check, the per-project switch, flow control and the pane probes all live. The reply is
* already rendered as a control reply — Canvas forwards it verbatim. */