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(main): an in-memory ownership ledger for agent-opened browser nodes
Claude Codece5d08c95a86
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex b2fcdc86f..373c04a62 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -217,7 +217,17 @@ class HookServer {/** Node ids the materialiser refuses to mint for (see `markNodeIdentityUnmintable`). */private unmintableNodes = new Set<string>()private controlHandler:- | ((cmd: { verb: string; nodeId: string; args: Record<string, string> }) => Promise<{+ | ((cmd: {+ verb: string+ nodeId: string+ args: Record<string, string>+ // The caller's IDENTITY verdict for THIS request, decided at the gate above and passed on+ // rather than re-derived in main. `true` only when the caller presented a per-node token+ // this instance minted for this node id. The browser ownership ledger (PR 4 Task 4.3)+ // claims a node ONLY when this is true — a `legacy`/warned caller opens a browser but owns+ // nothing, so it can drive nothing. `browser-ownership-source.test.ts` guards the source.+ verified: boolean+ }) => Promise<{ok: booleanmessage?: stringresult?: unknown@@ -536,7 +546,7 @@ class HookServer {return}const result = this.controlHandler- ? await this.controlHandler({ verb, nodeId, args })+ ? await this.controlHandler({ verb, nodeId, args, verified: verdict === 'verified' }): { ok: false, error: 'control unavailable' }// Which note, not whether: an unmintable node warned with the restart line is sent round// the same loop the refusal path already knows better than to send it round.diff --git a/src/main/browser-control-ledger.test.ts b/src/main/browser-control-ledger.test.tsnew file mode 100644index 000000000..2d5619e73--- /dev/null+++ b/src/main/browser-control-ledger.test.ts@@ -0,0 +1,107 @@+import { describe, it, expect } from 'vitest'+import { BrowserControlLedger, type AgentBrowserEntry } from './browser-control-ledger'++function entry(over: Partial<AgentBrowserEntry> = {}): AgentBrowserEntry {+ return {+ ownerNodeId: 'claude-1',+ projectId: 'p-1',+ partition: 'persist:nt-agent-browser-p-1',+ navGeneration: 0,+ leaseActiveUntil: 0,+ openedAt: 1,+ ...over+ }+}++describe('BrowserControlLedger', () => {+ it('get() requires the SAME owner, and a stranger is indistinguishable from absent', () => {+ // Rule from S8's requireTab, adopted verbatim: the identical answer for "does not exist" and+ // "exists but is not yours". A different message is a node-enumeration oracle.+ const l = new BrowserControlLedger()+ l.claim('browser-3', entry({ ownerNodeId: 'claude-1' }))+ expect(l.get('browser-3', 'claude-2')).toBe(null)+ expect(l.get('browser-9', 'claude-2')).toBe(null)+ })++ it('get() returns the entry ONLY for the owner that opened it', () => {+ const l = new BrowserControlLedger()+ l.claim('browser-3', entry({ ownerNodeId: 'claude-1' }))+ expect(l.get('browser-3', 'claude-1')?.ownerNodeId).toBe('claude-1')+ })++ it('a second claim on a live id is refused — there is NO handoff, claim or transfer', () => {+ // S8 had claimUserTab. Dropped: an agent drives only what it itself opened, and there is no+ // verb by which the user's own browsing becomes an agent's. Deleting the feature also deletes+ // S8's child-session-invalidation-on-handoff case.+ const l = new BrowserControlLedger()+ expect(l.claim('browser-3', entry({ ownerNodeId: 'claude-1' }))).toBe(true)+ expect(l.claim('browser-3', entry({ ownerNodeId: 'claude-2' }))).toBe(false)+ // The original owner still owns it; the second claimant owns nothing.+ expect(l.get('browser-3', 'claude-1')?.ownerNodeId).toBe('claude-1')+ expect(l.get('browser-3', 'claude-2')).toBe(null)+ })++ it('claim refuses a blank browser id or a blank owner — there is no anonymous owner', () => {+ const l = new BrowserControlLedger()+ expect(l.claim('', entry())).toBe(false)+ expect(l.claim('browser-3', entry({ ownerNodeId: '' }))).toBe(false)+ expect(l.get('browser-3', '')).toBe(null)+ })++ it('release drops ownership — a released id is undrivable and re-claimable', () => {+ const l = new BrowserControlLedger()+ l.claim('browser-3', entry({ ownerNodeId: 'claude-1' }))+ l.release('browser-3')+ expect(l.get('browser-3', 'claude-1')).toBe(null)+ // Re-claimable by anyone now (its session ended); ownership is not sticky past release.+ expect(l.claim('browser-3', entry({ ownerNodeId: 'claude-2' }))).toBe(true)+ })++ it('releaseByOwner / releaseByProject / releaseAll return what they released, for detach', () => {+ const l = new BrowserControlLedger()+ l.claim('b-1', entry({ ownerNodeId: 'claude-1', projectId: 'p-1' }))+ l.claim('b-2', entry({ ownerNodeId: 'claude-1', projectId: 'p-2' }))+ l.claim('b-3', entry({ ownerNodeId: 'claude-9', projectId: 'p-2' }))++ expect(l.releaseByOwner('claude-1').sort()).toEqual(['b-1', 'b-2'])+ // b-1/b-2 gone, b-3 remains.+ expect(l.get('b-1', 'claude-1')).toBe(null)+ expect(l.get('b-3', 'claude-9')?.projectId).toBe('p-2')++ expect(l.releaseByProject('p-2')).toEqual(['b-3'])+ expect(l.get('b-3', 'claude-9')).toBe(null)++ l.claim('b-4', entry({ ownerNodeId: 'claude-1' }))+ expect(l.releaseAll()).toEqual(['b-4'])+ expect(l.releaseAll()).toEqual([])+ })++ it('activeLeases reports only nodes whose lease is live at now, with their owner', () => {+ const l = new BrowserControlLedger()+ l.claim('b-live', entry({ ownerNodeId: 'claude-1', leaseActiveUntil: 0 }))+ l.claim('b-dead', entry({ ownerNodeId: 'claude-2', leaseActiveUntil: 0 }))+ l.touchLease('b-live', 1000)+ l.touchLease('b-missing', 5000) // no-op: unclaimed+ expect(l.activeLeases(500)).toEqual([{ browserNodeId: 'b-live', ownerNodeId: 'claude-1' }])+ // Exactly AT the deadline the lease has lapsed — `until > now`, not `>=` (a lease is live up to+ // but not including its expiry, or a stale lease leaks one tick past its end).+ expect(l.activeLeases(1000)).toEqual([])+ // And well after.+ expect(l.activeLeases(2000)).toEqual([])+ })++ it('nothing is persisted: a fresh ledger owns nothing', () => {+ // Ownership does not survive a restart, by design. See the ropes test in Task 4.4 for why.+ expect(new BrowserControlLedger().get('browser-3', 'claude-1')).toBe(null)+ })++ it('claim stores a COPY — mutating the caller\'s entry afterwards cannot rewrite ownership', () => {+ // The owner arriving by reference would let a later caller flip ownerNodeId post-claim.+ const l = new BrowserControlLedger()+ const e = entry({ ownerNodeId: 'claude-1' })+ l.claim('browser-3', e)+ e.ownerNodeId = 'claude-evil'+ expect(l.get('browser-3', 'claude-1')?.ownerNodeId).toBe('claude-1')+ expect(l.get('browser-3', 'claude-evil')).toBe(null)+ })+})diff --git a/src/main/browser-control-ledger.ts b/src/main/browser-control-ledger.tsnew file mode 100644index 000000000..223655657--- /dev/null+++ b/src/main/browser-control-ledger.ts@@ -0,0 +1,114 @@+/**+ * Who may drive which browser node, for THIS APP RUN ONLY.+ *+ * IN MEMORY, IN MAIN, NEVER PERSISTED, AND NEVER READ FROM project.json. The obvious+ * implementation — "the agent may drive the browser node it opened, so read the rope" — is the same+ * supply-chain class as bypassPermissions, which the owner already ruled out for exactly this+ * reason. `Project.ropes` is documented as DISPLAY-ONLY but PERSISTED (shared/types.ts), so a+ * hostile cloned project.json can ship a pre-declared rope from claude-1 to browser-1, and any+ * ownership check that reads `ropes` grants on it. `browser-ownership-source.test.ts` (Task 4.4)+ * fails if any ownership path ever reads `ropes`.+ *+ * The cost is real and is paid deliberately: browser control does not survive an app restart. An+ * agent mid-task across a restart must open-browser again and log in again.+ *+ * Only a successful `open-browser` from a VERIFIED caller creates an entry (`claim`, called on the+ * renderer's `{ id }` reply, gated on the request's `verified` verdict in main). A node the user+ * opened is never in here and is therefore invisible and undrivable — including the "New browser"+ * menu item, a pop-up captured from a user-opened node, and EVERY browser node restored from+ * project.json at load. Kept from S8, which had this one property right.+ *+ * This is the browser sibling of `core/agents/pane-ownership.ts` (messaging's runtime ledger): same+ * shape, same fail-closed lessons — record at CREATE from a non-forgeable source (main's own+ * `verified` verdict, not the file), an absent entry and a disagreement are both REFUSED, and+ * `get` deliberately cannot distinguish "not yours" from "does not exist". It lives in `src/main`,+ * not `src/core`, because its clients are Electron-adjacent (webContents leases, PR 5/6) and it is+ * never needed on the Server Edition, where browser control cannot exist.+ */++export interface AgentBrowserEntry {+ /** The agent node that ran open-browser. Drives are admitted only for THIS owner. */+ ownerNodeId: string+ /** The project that owned the open. */+ projectId: string+ /** The session jar the guest attached on (`persist:nt-agent-browser-<projectId>`). */+ partition: string+ /** Bumped by Page.frameNavigated; invalidates every @ref (PR 5 Task 5.5). */+ navGeneration: number+ /** Drives the indicator (PR 6) and the discard suppression (PR 5 Task 5.4). */+ leaseActiveUntil: number+ openedAt: number+}++export class BrowserControlLedger {+ /** browserNodeId → its ownership entry, for browser nodes an agent opened THIS run. */+ private readonly entries = new Map<string, AgentBrowserEntry>()++ /**+ * Record ownership of a freshly opened browser node. Returns false — and changes NOTHING — if the+ * id is already claimed: there is NO handoff, claim or transfer (S8's `claimUserTab` is dropped),+ * so a live browser node's owner never changes and the user's own browsing never becomes an+ * agent's. A blank `browserNodeId` or `ownerNodeId` is refused (there is no anonymous owner).+ */+ claim(browserNodeId: string, e: AgentBrowserEntry): boolean {+ if (!browserNodeId || !e.ownerNodeId) return false+ if (this.entries.has(browserNodeId)) return false+ this.entries.set(browserNodeId, { ...e })+ return true+ }++ /**+ * The entry IF this exact owner opened this exact node this run, else null. The answer for "does+ * not exist" and "exists but is not yours" is IDENTICAL by design (both null): a distinct message+ * would be a node-enumeration oracle. Rule adopted verbatim from S8's requireTab.+ */+ get(browserNodeId: string, ownerNodeId: string): AgentBrowserEntry | null {+ const entry = this.entries.get(browserNodeId)+ if (!entry || entry.ownerNodeId !== ownerNodeId) return null+ return entry+ }++ /** Drop one node's ownership — its session is ending. Undrivable again until a fresh claim. */+ release(browserNodeId: string): void {+ this.entries.delete(browserNodeId)+ }++ /** Release every node this owner opened (the owner node was deleted/detached); returns their ids. */+ releaseByOwner(ownerNodeId: string): string[] {+ return this.releaseWhere((e) => e.ownerNodeId === ownerNodeId)+ }++ /** Release every node opened under this project (the project closed); returns their ids. */+ releaseByProject(projectId: string): string[] {+ return this.releaseWhere((e) => e.projectId === projectId)+ }++ /** Release everything (app teardown); returns every released id. */+ releaseAll(): string[] {+ return this.releaseWhere(() => true)+ }++ /** Extend a node's lease (drives the indicator + discard suppression). No-op if unclaimed. */+ touchLease(browserNodeId: string, until: number): void {+ const entry = this.entries.get(browserNodeId)+ if (entry) entry.leaseActiveUntil = until+ }++ /** Nodes whose lease is still live at `now` — the indicator (PR 6) and discard-suppression set. */+ activeLeases(now: number): { browserNodeId: string; ownerNodeId: string }[] {+ const live: { browserNodeId: string; ownerNodeId: string }[] = []+ for (const [browserNodeId, e] of this.entries) {+ if (e.leaseActiveUntil > now) live.push({ browserNodeId, ownerNodeId: e.ownerNodeId })+ }+ return live+ }++ private releaseWhere(pred: (e: AgentBrowserEntry) => boolean): string[] {+ const released: string[] = []+ for (const [browserNodeId, e] of this.entries) {+ if (pred(e)) released.push(browserNodeId)+ }+ for (const id of released) this.entries.delete(id)+ return released+ }+}diff --git a/src/main/index.ts b/src/main/index.tsindex 78fc36834..3c71f55de 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -15,6 +15,7 @@ const logBuffer = new LogBuffer()installLogSink(logBuffer)import { writeFilesToClipboard } from './clipboard-files'import { allowGuestNavigation } from './webview-nav'+import { BrowserControlLedger } from './browser-control-ledger'import { registerFsHandlers } from '../core/fs-handlers'import { LogBuffer } from '../core/log-buffer'import { installLogSink, splitTag } from '../core/log-sink'@@ -2322,6 +2323,9 @@ app.whenReady().then(async () => {timer: NodeJS.Timeout}>()+ // Who owns which agent-opened browser node, THIS app run only. In-memory, never persisted, never+ // read from project.json (Task 4.3/4.4). Consumed by PR 5 (attach/lease), PR 6 (indicator/Stop).+ const browserLedger = new BrowserControlLedger()ipcMain.on(IPC.agentControlResult,(@@ -2335,11 +2339,11 @@ app.whenReady().then(async () => {pending.resolve(payload)})- hookServer.setControlHandler(async ({ verb, nodeId, args }) => {+ hookServer.setControlHandler(async ({ verb, nodeId, args, verified }) => {const target = getMainWindow()if (!target) return { ok: false, error: 'window unavailable' }const requestId = randomUUID()- return await new Promise((resolve) => {+ const result = await new Promise<{ ok: boolean; message?: string; result?: unknown; error?: string }>((resolve) => {const timer = setTimeout(() => {pendingControl.delete(requestId)resolve({ ok: false, error: 'timed out (no response / not confirmed)' })@@ -2347,6 +2351,27 @@ app.whenReady().then(async () => {pendingControl.set(requestId, { resolve, timer })target.webContents.send(IPC.agentControl, { requestId, sourceNodeId: nodeId, verb, args })})+ // Record browser ownership the moment an open-browser succeeds — and ONLY when the caller's+ // identity verdict for THIS request was `verified` (main's own verdict, not anything off the+ // wire or project.json). A `legacy`/warned caller may open a browser but owns nothing, so it+ // can drive nothing. The owner is the verified caller (`nodeId`); the project id + partition+ // ride along from the renderer's reply for release-by-project and the indicator. This is the+ // browser sibling of pane-ownership's record-at-fresh-spawn. See browser-control-ledger.ts and+ // browser-ownership-source.test.ts (ownership is NEVER read from Project.ropes).+ if (verb === 'open-browser' && verified && result.ok) {+ const opened = result.result as { id?: string; projectId?: string; partition?: string } | undefined+ if (opened?.id && opened.partition) {+ browserLedger.claim(opened.id, {+ ownerNodeId: nodeId,+ projectId: opened.projectId ?? '',+ partition: opened.partition,+ navGeneration: 0,+ leaseActiveUntil: 0,+ openedAt: Date.now()+ })+ }+ }+ return result})initMediaProtocol()diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 26f8b2215..29287927c 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -6960,7 +6960,11 @@ export function Canvas() {return}const id = addAndConnect(createBrowserNode(nodesRef.current.length, browserUrl, placeBelow(), partition))- reply({ ok: true, message: `opened browser ${id}`, result: { id } })+ // Return the project id + partition so main can record ownership in its in-memory+ // ledger (browser-control-ledger.ts). Main gates the claim on its OWN `verified` verdict+ // and keys it to the verified caller — these fields are descriptive (release-by-project,+ // the indicator), never the authorization boundary.+ reply({ ok: true, message: `opened browser ${id}`, result: { id, projectId: ctlProject?.id, partition } })return}case 'group': {