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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(browser): interaction spine — dispatchKeyEvent gate, viewport refresh, ref spend
Claude Code1bf5dc660d9b
diff --git a/src/main/browser-cdp-allowlist.test.ts b/src/main/browser-cdp-allowlist.test.tsindex 56ca54661..c5a9b006f 100644--- a/src/main/browser-cdp-allowlist.test.ts+++ b/src/main/browser-cdp-allowlist.test.ts@@ -55,6 +55,27 @@ describe('checkCdpCommand', () => {expect(checkCdpCommand('Input.insertText', { text: 'x'.repeat(8193) }, ctx)).toBe(false)})+ it('Input.dispatchKeyEvent is a FIXED-TABLE key, or a fixed editing command — never free key injection (Tasks 8.2-8.3)', () => {+ // A --press key from the table (the same set the verb parser gates on).+ expect(checkCdpCommand('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter' }, ctx)).toBe(true)+ expect(checkCdpCommand('Input.dispatchKeyEvent', { type: 'keyUp', key: 'ArrowDown' }, ctx)).toBe(true)+ // A key OUTSIDE the table is refused — no arbitrary key injection.+ expect(checkCdpCommand('Input.dispatchKeyEvent', { type: 'keyDown', key: 'a' }, ctx)).toBe(false)+ expect(checkCdpCommand('Input.dispatchKeyEvent', { type: 'keyDown', key: 'F5' }, ctx)).toBe(false)+ // The two --clear editing commands are allowed; anything else is refused.+ expect(checkCdpCommand('Input.dispatchKeyEvent', { type: 'keyDown', commands: ['selectAll'] }, ctx)).toBe(true)+ expect(checkCdpCommand('Input.dispatchKeyEvent', { type: 'keyDown', commands: ['deleteBackward'] }, ctx)).toBe(true)+ expect(checkCdpCommand('Input.dispatchKeyEvent', { type: 'keyDown', commands: ['insertText'] }, ctx)).toBe(false)+ expect(checkCdpCommand('Input.dispatchKeyEvent', { type: 'keyDown', commands: ['delete', 'selectAll'] }, ctx)).toBe(false)+ expect(checkCdpCommand('Input.dispatchKeyEvent', { type: 'keyDown', commands: [] }, ctx)).toBe(false)+ // `text` is FORBIDDEN outright — a character that reaches the page is Input.insertText's job.+ expect(checkCdpCommand('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', text: '\r' }, ctx)).toBe(false)+ expect(checkCdpCommand('Input.dispatchKeyEvent', { type: 'char', text: 'q' }, ctx)).toBe(false)+ // A meaningless empty event (no key, no commands) is refused; a bad type is refused.+ expect(checkCdpCommand('Input.dispatchKeyEvent', { type: 'keyDown' }, ctx)).toBe(false)+ expect(checkCdpCommand('Input.dispatchKeyEvent', { type: 'keyDrag', key: 'Enter' }, ctx)).toBe(false)+ })+it('cookie READS take one explicit domain; the jar-emptying call does not exist here', () => {expect(checkCdpCommand('Network.getCookies', { urls: ['https://github.com/'] }, ctx)).toBe(true)expect(checkCdpCommand('Network.getCookies', {}, ctx)).toBe(false) // no domain ⇒ the whole jardiff --git a/src/main/browser-cdp-allowlist.ts b/src/main/browser-cdp-allowlist.tsindex f690fd3b6..79466fdef 100644--- a/src/main/browser-cdp-allowlist.ts+++ b/src/main/browser-cdp-allowlist.ts@@ -24,6 +24,7 @@*/import { isNtScript } from './browser-nt-scripts'import { normalizeAddress } from '@shared/browserUrl'+import { BROWSER_KEYS } from '../core/browser-verb'/** What the gate needs to know about the page beyond the command itself: the viewport from the last* `Page.getLayoutMetrics`, so a mouse coordinate can be bounded to what is actually on screen. */@@ -58,6 +59,16 @@ function valueOnlyArgs(args: unknown): boolean {const MAX_SELECTOR = 1024const MAX_INSERT_TEXT = 8192+/** The dispatch types a key event may carry — a key-down, a key-up, or a raw key-down. There is+ * deliberately NO `char` type: a character that types into the page belongs to `Input.insertText`+ * (its own capped, data-only path), never to a key event. */+const KEY_EVENT_TYPES = new Set(['keyDown', 'keyUp', 'rawKeyDown'])++/** The ONLY editing commands a key event may drive — the two `--type --clear true` needs (select the+ * field's contents, delete a selection). Anything else (`delete`, `insertText`, `moveToEndOfLine`…)+ * is a strange, unaudited effect and is default-denied. */+const EDIT_COMMANDS = new Set(['selectAll', 'deleteBackward'])+/*** The table. Every entry is a (method, validator) pair. A Map — not a plain object — so a method* named `__proto__` / `constructor` can never resolve a validator off Object.prototype.@@ -82,7 +93,10 @@ const ALLOW = new Map<string, Validator>([],// A synthesized mouse event must land inside the reported viewport — a coordinate off-screen is- // either a bug or an attempt to reach chrome the user cannot see.+ // either a bug or an attempt to reach chrome the user cannot see. This one entry covers the click+ // (mousePressed/mouseReleased, Task 8.1) AND the scroll (a `mouseWheel` at the viewport centre,+ // Task 8.4): `Input.synthesizeScrollGesture` stays EXCLUDED (it is in the refused list), so the+ // wheel translation is the only scroll door and it is bounded by the same viewport check.['Input.dispatchMouseEvent',(p, ctx) =>@@ -99,6 +113,33 @@ const ALLOW = new Map<string, Validator>([// Typed text is capped; the text goes to insertText, never to a shell and never spliced anywhere.['Input.insertText', (p) => isRecord(p) && typeof p.text === 'string' && p.text.length <= MAX_INSERT_TEXT],+ // A key event is NOT free key injection (PR 8, Tasks 8.2-8.3). It is default-deny in three ways at+ // once, and any one of them failing is a refusal:+ // - `key`, if present, must be one of the fixed BROWSER_KEYS `--press` accepts (the SAME table the+ // verb parser gates on — one source of truth) — never an arbitrary key;+ // - `commands`, if present, must be a NON-EMPTY subset of the two editing commands `--clear` needs+ // — never `insertText`/`delete`/a caret walk;+ // - `text` is FORBIDDEN outright: a character that reaches the page is `Input.insertText`'s+ // capped, data-only job, so a key event may never smuggle one.+ // At least one of key/commands must be present — an empty key event is meaningless — and the type+ // must be a real key-event type (no `char`).+ [+ 'Input.dispatchKeyEvent',+ (p) => {+ if (!isRecord(p)) return false+ if (typeof p.type !== 'string' || !KEY_EVENT_TYPES.has(p.type)) return false+ if (p.text !== undefined) return false+ const keyOk = p.key === undefined || (typeof p.key === 'string' && (BROWSER_KEYS as readonly string[]).includes(p.key))+ if (!keyOk) return false+ const cmds = p.commands+ const hasCmds = cmds !== undefined+ const cmdsOk =+ !hasCmds || (Array.isArray(cmds) && cmds.length > 0 && cmds.every((c) => typeof c === 'string' && EDIT_COMMANDS.has(c)))+ if (!cmdsOk) return false+ return p.key !== undefined || (Array.isArray(cmds) && cmds.length > 0)+ }+ ],+// A bounded selector against a known node.['DOM.querySelector',diff --git a/src/main/browser-lease.ts b/src/main/browser-lease.tsindex fb688453e..28f5391e5 100644--- a/src/main/browser-lease.ts+++ b/src/main/browser-lease.ts@@ -23,6 +23,7 @@* Electron-adjacent (holds a debugger on a page with real logins) → `src/main`, never Server Edition.*/import type { CdpContext } from './browser-cdp-allowlist'+import type { LayoutMetrics } from './browser-actions'import { type DebuggerLike, sendCdp } from './browser-cdp-send'// The indicator's linger now lives in `src/shared` (PR 6 consumes it from the renderer too, and a// renderer→main import is forbidden — global constraint 4). Re-exported here so the debugger-lease@@ -88,6 +89,14 @@ export class BrowserSession {private attached = falseprivate _leaseActiveUntil = 0+ /**+ * The last viewport measured from `Page.getLayoutMetrics` ({@link refreshViewport}). PR 8's pointer+ * verbs bound a mouse coordinate to what is actually on screen, and the constructor-injected+ * viewport is a 0×0 placeholder until then — so once a real measurement lands, it OVERRIDES the+ * injected closure at send time (see {@link currentCtx}). Reset on any detach: a released/re-navigated+ * page's old size must never bound a coordinate on the next one.+ */+ private _viewport: { width: number; height: number } | null = null/*** CDP child-session ids are scoped to the debugger attachment. They are invalid after either an* explicit detach or webContents teardown and must never survive a reattach.@@ -134,6 +143,36 @@ export class BrowserSession {return this.dispatch(method, params, undefined)}+ /**+ * Measure the page from `Page.getLayoutMetrics`, cache the viewport size so subsequent bounded+ * pointer events ({@link import('./browser-actions').browserClick}/`browserScroll`) validate against+ * the REAL page, and return the full scroll geometry (viewport + current scroll offset + content+ * size) the scroll reply reads back. A pointer verb calls this immediately before it dispatches, so+ * a resize/scroll between verbs is always reflected.+ */+ async refreshViewport(): Promise<LayoutMetrics> {+ const raw = (await this.send('Page.getLayoutMetrics', {})) as {+ cssLayoutViewport?: { clientWidth?: number; clientHeight?: number }+ cssVisualViewport?: { clientWidth?: number; clientHeight?: number; pageX?: number; pageY?: number }+ cssContentSize?: { width?: number; height?: number }+ }+ const num = (v: unknown): number | undefined => (typeof v === 'number' && Number.isFinite(v) ? v : undefined)+ const lv = raw?.cssLayoutViewport+ const vv = raw?.cssVisualViewport+ const cs = raw?.cssContentSize+ const width = num(lv?.clientWidth) ?? num(vv?.clientWidth) ?? 0+ const height = num(lv?.clientHeight) ?? num(vv?.clientHeight) ?? 0+ this._viewport = { width, height }+ return {+ width,+ height,+ scrollX: num(vv?.pageX) ?? 0,+ scrollY: num(vv?.pageY) ?? 0,+ contentWidth: num(cs?.width) ?? width,+ contentHeight: num(cs?.height) ?? height+ }+ }+/** Send a command to a flat-mode child target, using its LIVE session id (never a caller-supplied* one). Refused with a named outcome if the target has no live session. */sendToTarget(targetId: string, method: string, params: object): Promise<unknown> {@@ -201,7 +240,13 @@ export class BrowserSession {return Promise.reject(e)}this.extendLease()- return this.race(sendCdp(this.dbg, method, params, this.viewport(), sessionId))+ return this.race(sendCdp(this.dbg, method, params, this.currentCtx(), sessionId))+ }++ /** The viewport the allowlist bounds a coordinate against: the last real measurement when we have+ * one, else the injected placeholder. */+ private currentCtx(): CdpContext {+ return this._viewport ? { viewport: this._viewport } : this.viewport()}private ensureAttached(): void {@@ -236,6 +281,9 @@ export class BrowserSession {private onDetached(): void {this.attached = falsethis.targets.clear()+ // A measured viewport belongs to the page we were attached to; drop it so it can never bound a+ // coordinate on a different page after a reattach.+ this._viewport = nullthis.rejectInFlight()}diff --git a/src/main/browser-nt-scripts.ts b/src/main/browser-nt-scripts.tsindex 3e83f18e3..551d34929 100644--- a/src/main/browser-nt-scripts.ts+++ b/src/main/browser-nt-scripts.ts@@ -41,8 +41,10 @@ export const NT_SCRIPTS = Object.freeze({/** 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. */+ * innerText semantics exclude <script>, <style> and display:none BY CONSTRUCTION (they are the+ * RENDERED text). They do NOT drop aria-hidden content — that lives in the accessibility tree, not+ * in innerText — so this reader makes no aria-hidden promise; its real property is that no hidden+ * input value and no <script> body ride along. Read-only. */readText:'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 } }',@@ -65,7 +67,14 @@ export const NT_SCRIPTS = Object.freeze({/** A readiness probe: is the document loaded, and (optionally) is a selector present yet? */waitProbe:- 'function(s){ if (document.readyState !== "complete") return false; if (!s) return true; return document.querySelector(s) != null }'+ 'function(s){ if (document.readyState !== "complete") return false; if (!s) return true; return document.querySelector(s) != null }',++ /** The currently-focused EDITABLE field, or null — used by --type with no --into to tell "type into+ * the focused field" from "nothing is focused" (Task 8.2). Returns only the tag + id, never a+ * value: reading document.activeElement is a read, and a text/select/contenteditable focus is the+ * only thing that makes a bare --type well-defined. Read-only. */+ activeField:+ 'function(){ var el = document.activeElement; if (!el || el === document.body) return null; var tag = el.tagName ? el.tagName.toLowerCase() : ""; var editable = tag === "input" || tag === "textarea" || tag === "select" || el.isContentEditable === true; if (!editable) return null; return { tag: tag, id: el.id || "" } }'})export type NtScriptName = keyof typeof NT_SCRIPTSdiff --git a/src/main/browser-refs.test.ts b/src/main/browser-refs.test.tsindex 9a7cf245a..0bcb15e0c 100644--- a/src/main/browser-refs.test.ts+++ b/src/main/browser-refs.test.ts@@ -88,3 +88,53 @@ describe('RefTable — @refs are scoped to a node AND a navigation generation',if (!r.ok) expect(r.stale).toBe(false) // present generation, but no such ref — not a nav-stale})})++describe('RefTable.spend — how PR 8 verbs (--click/--type/--wait) redeem a ref', () => {+ it('spends a live ref against the generation its map was minted on', () => {+ const t = new RefTable()+ t.mint('browser-1', 0, items())+ const r = t.spend('browser-1', '@2')+ expect(r.ok).toBe(true)+ if (r.ok) expect(r.item).toMatchObject({ tag: 'BUTTON', text: 'Delete account' })+ })++ it('a ref spent AFTER a navigation is STALE — never re-resolved against a newer map (PR 5)', () => {+ // This is the property a --click must uphold: clicking @2 ("Delete account") after the page+ // navigated must be refused, not silently re-resolved to whatever is @2 on the new page.+ const t = new RefTable()+ t.mint('browser-1', 0, items())+ t.bumpGeneration('browser-1') // Page.frameNavigated+ const r = t.spend('browser-1', '@2')+ expect(r.ok).toBe(false)+ if (!r.ok) {+ expect(r.stale).toBe(true)+ expect(r.message).toBe(+ '@2 is not on the current page (the page navigated since the last --read map; re-read it)'+ )+ expect(r).not.toHaveProperty('item')+ }+ })++ it('a fresh map after the navigation makes its refs spendable again', () => {+ const t = new RefTable()+ t.mint('browser-1', 0, items())+ t.bumpGeneration('browser-1')+ t.mint('browser-1', 1, items()) // --read map at the new generation+ expect(t.spend('browser-1', '@2').ok).toBe(true)+ })++ it('a ref from ANOTHER node is refused, and a node that never read a map has nothing to spend', () => {+ const t = new RefTable()+ t.mint('browser-1', 0, items())+ expect(t.spend('browser-2', '@1').ok).toBe(false)+ expect(t.spend('never-read', '@1').ok).toBe(false)+ })++ it('an out-of-range label on the current page is a refusal, not a guess', () => {+ const t = new RefTable()+ t.mint('browser-1', 0, items())+ const r = t.spend('browser-1', '@99')+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.stale).toBe(false) // present, unknown — not nav-stale+ })+})diff --git a/src/main/browser-refs.ts b/src/main/browser-refs.tsindex de225f115..9ed01e822 100644--- a/src/main/browser-refs.ts+++ b/src/main/browser-refs.ts@@ -44,6 +44,10 @@ interface NodeRefs {export class RefTable {private readonly byNode = new Map<string, NodeRefs>()+ /** The generation each node's CURRENT labels were minted at. Kept alongside — and NOT cleared by a+ * bump — so a ref spent after a navigation resolves against the generation the agent read it on and+ * is therefore reported STALE (the page navigated), not merely "unknown". See {@link spend}. */+ private readonly mintedAt = new Map<string, number>()/** The generation the node is currently on (0 before anything is minted or bumped). */currentGeneration(nodeId: string): number {@@ -63,9 +67,23 @@ export class RefTable {map.set(label, items[i])}this.byNode.set(nodeId, { gen, items: map })+ this.mintedAt.set(nodeId, gen)return { gen, labels }}+ /**+ * SPEND a ref an agent is holding (`--click @7`, `--type --into @3`, `--wait @9`). It resolves the+ * label at the generation its CURRENT map was minted on — so a navigation since that read (which+ * bumped the generation) surfaces as the STALE refusal (`the page navigated … re-read it`), while a+ * label that was simply never minted on this page is the UNKNOWN refusal. Both are refusals; a stale+ * ref is NEVER silently re-resolved against a newer map (the correctness property PR 5 pins). A node+ * that never read a map at all resolves as stale-shaped (there is nothing to spend), which is still a+ * refusal.+ */+ spend(nodeId: string, label: string): RefResolution {+ return this.resolve(nodeId, this.mintedAt.get(nodeId) ?? 0, label)+ }+/*** Resolve a ref for a node at the generation the agent read it on. Returns the item ONLY when the* node's current generation still equals `gen` AND the label was minted then. Anything else is a@@ -99,5 +117,6 @@ export class RefTable {/** Forget a node entirely (its guest is gone / owner released). */forget(nodeId: string): void {this.byNode.delete(nodeId)+ this.mintedAt.delete(nodeId)}}diff --git a/src/main/index.ts b/src/main/index.tsindex 0344391a3..512844493 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2424,8 +2424,9 @@ app.whenReady().then(async () => {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.+ // A 0×0 placeholder: coordinates are unused by --nav/--read, and the pointer verbs (PR 8) call+ // BrowserSession.refreshViewport() from Page.getLayoutMetrics before every dispatch, which+ // OVERRIDES this at send time — so a bounded mouse event validates against the real page.viewport: () => ({ viewport: { width: 0, height: 0 } }),isDevToolsOpen: () => {try {