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): a debugger lease — attach on the first verb, detach after 60s idle

enesb509094263c2
diff --git a/src/main/browser-cdp-send.test.ts b/src/main/browser-cdp-send.test.ts
new file mode 100644
index 000000000..fe495abfd
--- /dev/null
+++ b/src/main/browser-cdp-send.test.ts
@@ -0,0 +1,45 @@
+import { describe, it, expect } from 'vitest'
+import { sendCdp, cdpRefusedMessage, type DebuggerLike } from './browser-cdp-send'
+import type { CdpContext } from './browser-cdp-allowlist'
+
+const ctx: CdpContext = { viewport: { width: 1280, height: 800 } }
+
+function fakeDebugger(): DebuggerLike & { sent: string[] } {
+ const sent: string[] = []
+ return {
+ sent,
+ isAttached: () => true,
+ attach: () => {},
+ detach: () => {},
+ sendCommand: (method: string) => {
+ sent.push(method)
+ return Promise.resolve({ ok: true })
+ },
+ on: () => {}
+ }
+}
+
+describe('sendCdp — the one gate every command passes', () => {
+ it('an allowed command reaches the debugger', async () => {
+ const dbg = fakeDebugger()
+ await sendCdp(dbg, 'Page.navigate', { url: 'https://x.test/' }, ctx)
+ expect(dbg.sent).toEqual(['Page.navigate'])
+ })
+
+ it('a refused command NEVER reaches the debugger, and rejects with a named message', async () => {
+ const dbg = fakeDebugger()
+ await expect(sendCdp(dbg, 'Runtime.evaluate', { expression: '1' }, ctx)).rejects.toThrow(
+ cdpRefusedMessage('Runtime.evaluate')
+ )
+ // The refusal is a rejected promise, not a hang and not a silent drop.
+ expect(dbg.sent).toEqual([])
+ })
+
+ it('a refused parameter is caught even on an allowed method', async () => {
+ const dbg = fakeDebugger()
+ await expect(sendCdp(dbg, 'Page.navigate', { url: 'javascript:alert(1)' }, ctx)).rejects.toThrow(
+ /not permitted/
+ )
+ expect(dbg.sent).toEqual([])
+ })
+})
diff --git a/src/main/browser-cdp-send.ts b/src/main/browser-cdp-send.ts
new file mode 100644
index 000000000..cf4115e97
--- /dev/null
+++ b/src/main/browser-cdp-send.ts
@@ -0,0 +1,44 @@
+/**
+ * The ONE wrapper around `debugger.sendCommand`. Every CDP command the app ever issues to a guest
+ * goes through here and through `checkCdpCommand` first — that is what makes the allowlist THE gate
+ * rather than one of several. A structural test (browser-cdp-allowlist.test.ts) fails the build if a
+ * `sendCommand(` appears in any other `src/main/browser-*.ts`.
+ *
+ * Default-deny: a command the allowlist refuses never reaches the debugger; the caller gets a NAMED
+ * rejection, not a silent drop and not a raw Electron error.
+ */
+import { checkCdpCommand, type CdpContext } from './browser-cdp-allowlist'
+
+/** The slice of Electron's `webContents.debugger` this layer needs, injected so the wrapper and the
+ * lease are unit-testable without Electron (`src/main` cannot import the real module under vitest). */
+export interface DebuggerLike {
+ isAttached(): boolean
+ attach(protocolVersion?: string): void
+ detach(): void
+ sendCommand(method: string, commandParams?: object, sessionId?: string): Promise<unknown>
+ on(event: 'detach', listener: (event: unknown, reason: string) => void): void
+ on(event: 'message', listener: (event: unknown, method: string, params: unknown) => void): void
+}
+
+/** A refused command names the method — but never WHY, and never per-method detail: an allowlist
+ * that explains itself is a probing aid. One line, like every control reply. */
+export const cdpRefusedMessage = (method: string): string =>
+ `browser: the command ${method} is not permitted for agent control`
+
+/**
+ * Check, then send. The single choke point. `sessionId` targets a flat-mode child session; omitting
+ * it targets the root. Throws `Error(cdpRefusedMessage(method))` — a rejected promise, never a hang —
+ * when the allowlist refuses, so the refusal is a first-class outcome the caller must handle.
+ */
+export function sendCdp(
+ dbg: DebuggerLike,
+ method: string,
+ params: object,
+ ctx: CdpContext,
+ sessionId?: string
+): Promise<unknown> {
+ if (!checkCdpCommand(method, params, ctx)) {
+ return Promise.reject(new Error(cdpRefusedMessage(method)))
+ }
+ return dbg.sendCommand(method, params, sessionId)
+}
diff --git a/src/main/browser-lease.test.ts b/src/main/browser-lease.test.ts
new file mode 100644
index 000000000..3c6a3dd8d
--- /dev/null
+++ b/src/main/browser-lease.test.ts
@@ -0,0 +1,237 @@
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import {
+ BrowserSession,
+ BrowserLeaseManager,
+ leaseIsActive,
+ LEASE_IDLE_MS,
+ INDICATOR_LINGER_MS,
+ BROWSER_LEASE_DETACHED,
+ BROWSER_NO_LIVE_SESSION,
+ browserAttachFailedMessage,
+ browserDevToolsOpenMessage
+} from './browser-lease'
+import type { DebuggerLike } from './browser-cdp-send'
+import type { CdpContext } from './browser-cdp-allowlist'
+
+class FakeDebugger implements DebuggerLike {
+ attached = false
+ attachCalls = 0
+ detachCalls = 0
+ sends: { method: string; params?: object; sessionId?: string }[] = []
+ attachThrows = false
+ hangNext = false
+ private sessionSeq = 0
+ private detachListener: ((e: unknown, reason: string) => void) | null = null
+
+ isAttached(): boolean {
+ return this.attached
+ }
+ attach(): void {
+ this.attachCalls++
+ if (this.attachThrows) throw new Error('Another debugger is already attached')
+ this.attached = true
+ }
+ detach(): void {
+ this.detachCalls++
+ this.attached = false
+ }
+ sendCommand(method: string, params?: object, sessionId?: string): Promise<unknown> {
+ this.sends.push({ method, params, sessionId })
+ if (this.hangNext) {
+ this.hangNext = false
+ return new Promise<never>(() => {}) // never settles — models an in-flight command
+ }
+ if (method === 'Target.attachToTarget') {
+ return Promise.resolve({ sessionId: `sess-${++this.sessionSeq}` })
+ }
+ return Promise.resolve({ ok: true })
+ }
+ on(event: 'detach' | 'message', listener: (...a: never[]) => void): void {
+ if (event === 'detach') this.detachListener = listener as (e: unknown, reason: string) => void
+ }
+ fireDetach(reason = 'target closed'): void {
+ this.detachListener?.(null, reason)
+ }
+}
+
+const VIEWPORT: CdpContext = { viewport: { width: 1280, height: 800 } }
+
+function makeSession(overrides: Partial<{ isDevToolsOpen: () => boolean }> = {}): {
+ session: BrowserSession
+ dbg: FakeDebugger
+ setNow: (n: number) => void
+} {
+ const dbg = new FakeDebugger()
+ let now = 1_000_000
+ const session = new BrowserSession({
+ nodeId: 'browser-3',
+ debugger: dbg,
+ viewport: () => VIEWPORT,
+ now: () => now,
+ isDevToolsOpen: overrides.isDevToolsOpen
+ })
+ return { session, dbg, setNow: (n) => (now = n) }
+}
+
+const nav = (url = 'https://x.test/'): ['Page.navigate', { url: string }] => ['Page.navigate', { url }]
+
+describe('leaseIsActive + constants', () => {
+ it('is active only while now < leaseActiveUntil', () => {
+ expect(leaseIsActive(100, 200)).toBe(true)
+ expect(leaseIsActive(200, 200)).toBe(false)
+ expect(leaseIsActive(300, 200)).toBe(false)
+ })
+ it('the timings are the design values', () => {
+ expect(LEASE_IDLE_MS).toBe(60_000)
+ expect(INDICATOR_LINGER_MS).toBe(5_000)
+ })
+})
+
+describe('BrowserSession attach lifecycle', () => {
+ it('the first verb attaches; a second within LEASE_IDLE_MS does NOT re-attach', async () => {
+ const { session, dbg, setNow } = makeSession()
+ await session.send(...nav())
+ expect(dbg.attachCalls).toBe(1)
+ expect(dbg.sends.map((s) => s.method)).toEqual(['Page.navigate'])
+
+ setNow(1_000_000 + LEASE_IDLE_MS - 1)
+ await session.send(...nav('https://y.test/'))
+ expect(dbg.attachCalls).toBe(1) // still one attachment
+ })
+
+ it('no verb for LEASE_IDLE_MS detaches; the next verb re-attaches cleanly', async () => {
+ const { session, dbg, setNow } = makeSession()
+ await session.send(...nav())
+ expect(session.isAttached()).toBe(true)
+
+ // Idle past the window: the sweep detaches.
+ const idle = 1_000_000 + LEASE_IDLE_MS + 1
+ expect(session.maybeDetachIdle(idle)).toBe(true)
+ expect(dbg.detachCalls).toBe(1)
+ expect(session.isAttached()).toBe(false)
+
+ // A verb still inside the window does NOT detach.
+ setNow(idle)
+ await session.send(...nav())
+ expect(dbg.attachCalls).toBe(2) // re-attached
+ setNow(idle + 10)
+ expect(session.maybeDetachIdle(idle + 10)).toBe(false)
+ })
+
+ it('release() detaches, and a send in flight rejects with a NAMED outcome, not a hang', async () => {
+ const { session, dbg } = makeSession()
+ dbg.hangNext = true
+ const inFlight = session.send(...nav('https://hang.test/'))
+ expect(session.isAttached()).toBe(true)
+
+ session.release()
+ await expect(inFlight).rejects.toThrow(BROWSER_LEASE_DETACHED)
+ expect(dbg.detachCalls).toBe(1)
+ expect(session.leaseActiveUntil).toBe(0)
+ })
+
+ it('a webContents teardown (the debugger `detach` event) invalidates everything', async () => {
+ const { session, dbg } = makeSession()
+ await session.send(...nav())
+ dbg.hangNext = true
+ const inFlight = session.send(...nav('https://hang.test/'))
+ dbg.fireDetach('target closed') // Electron fires this on teardown
+ expect(session.isAttached()).toBe(false)
+ await expect(inFlight).rejects.toThrow(BROWSER_LEASE_DETACHED)
+ })
+})
+
+describe('BrowserSession attach failure', () => {
+ it('a generic attach failure is NAMED, never "not drivable"', async () => {
+ const { session, dbg } = makeSession()
+ dbg.attachThrows = true
+ await expect(session.send(...nav())).rejects.toThrow(browserAttachFailedMessage('browser-3'))
+ })
+
+ it('attach failure while DevTools is open names DevTools (unreachable on 42.8.1 — see the probe)', async () => {
+ const { session, dbg } = makeSession({ isDevToolsOpen: () => true })
+ dbg.attachThrows = true
+ await expect(session.send(...nav())).rejects.toThrow(browserDevToolsOpenMessage('browser-3'))
+ })
+})
+
+describe('BrowserSession child sessions (salvaged from S8, with credit)', () => {
+ it('attachToTarget records a flat-mode session id under (target)', async () => {
+ const { session, dbg } = makeSession()
+ const id = await session.attachTarget('t1')
+ expect(id).toBe('sess-1')
+ expect(session.sessionFor('t1')).toBe('sess-1')
+ expect(session.isValidSession('t1', 'sess-1')).toBe(true)
+ // It went out in flat mode.
+ const attach = dbg.sends.find((s) => s.method === 'Target.attachToTarget')
+ expect(attach?.params).toMatchObject({ targetId: 't1', flatten: true })
+ })
+
+ it('an explicit detach (idle) clears child sessions; a reused post-reattach id is REFUSED', async () => {
+ const { session, setNow } = makeSession()
+ await session.attachTarget('t1')
+ expect(session.isValidSession('t1', 'sess-1')).toBe(true)
+
+ // Idle detach — the attachment and its session ids die.
+ const idle = 1_000_000 + LEASE_IDLE_MS + 1
+ session.maybeDetachIdle(idle)
+ expect(session.sessionFor('t1')).toBeUndefined()
+ expect(session.isValidSession('t1', 'sess-1')).toBe(false)
+
+ // Re-attach and re-attach the target: a NEW id. The OLD id stays refused.
+ setNow(idle)
+ const fresh = await session.attachTarget('t1')
+ expect(fresh).toBe('sess-2')
+ expect(session.isValidSession('t1', 'sess-1')).toBe(false)
+ expect(session.isValidSession('t1', 'sess-2')).toBe(true)
+ })
+
+ it('a webContents teardown clears child sessions too', async () => {
+ const { session, dbg } = makeSession()
+ await session.attachTarget('t1')
+ session.handleTeardown()
+ expect(session.sessionFor('t1')).toBeUndefined()
+ // handleTeardown must NOT call detach() on a gone target.
+ expect(dbg.detachCalls).toBe(0)
+ })
+
+ it('sendToTarget refuses when the target has no live session', async () => {
+ const { session } = makeSession()
+ await expect(session.sendToTarget('t1', 'Page.getLayoutMetrics', {})).rejects.toThrow(
+ BROWSER_NO_LIVE_SESSION
+ )
+ })
+})
+
+describe('there is NO handoff-invalidation path (the feature was removed, not the care)', () => {
+ it('the source states the third S8 trigger is designed away', () => {
+ const src = readFileSync(new URL('./browser-lease.ts', import.meta.url), 'utf8')
+ expect(src).toMatch(/no handoff/i)
+ expect(src).toMatch(/removed the feature that[\s*/]+needed the care/i)
+ expect(src).toMatch(/designed away/i)
+ // And there is no handoff/claim machinery — the S8 names for it are gone.
+ expect(src).not.toMatch(/invalidateOnHandoff|onHandoff|claimUserTab|transferControl/)
+ })
+})
+
+describe('BrowserLeaseManager', () => {
+ it('owns sessions by node id, sweeps idle ones, and releases all on teardown', async () => {
+ const mgr = new BrowserLeaseManager()
+ const dbg = new FakeDebugger()
+ let now = 500
+ const s = new BrowserSession({ nodeId: 'browser-1', debugger: dbg, viewport: () => VIEWPORT, now: () => now })
+ mgr.set('browser-1', s)
+ expect(mgr.get('browser-1')).toBe(s)
+
+ await s.send(...nav())
+ expect(s.isAttached()).toBe(true)
+
+ now = 500 + LEASE_IDLE_MS + 1
+ mgr.sweepIdle(now)
+ expect(s.isAttached()).toBe(false)
+
+ mgr.releaseAll()
+ expect(mgr.get('browser-1')).toBeUndefined()
+ })
+})
diff --git a/src/main/browser-lease.ts b/src/main/browser-lease.ts
new file mode 100644
index 000000000..06aee7763
--- /dev/null
+++ b/src/main/browser-lease.ts
@@ -0,0 +1,293 @@
+/**
+ * The debugger LEASE: attach on the first verb, detach after {@link LEASE_IDLE_MS} of idleness,
+ * re-attach on the next verb. The attachment is deliberately NOT the indicator — an attach is
+ * invisible by itself and a detach-on-idle would blank a chip for a lease that is still live — so the
+ * chip binds to the ledger's `leaseActiveUntil` instead (PR 6). Every command routes through the one
+ * send wrapper ({@link import('./browser-cdp-send').sendCdp}) and therefore through the allowlist.
+ *
+ * PROBE (Task 5.0, docs/superpowers/probes/2026-08-browser-debugger.md), measured on Electron 42.8.1:
+ * a programmatic `webContents.debugger.attach()` and a user-opened DevTools window on the same
+ * <webview> guest are NOT mutually exclusive — attach succeeds with DevTools already open, and
+ * DevTools opens while a programmatic attachment stays live. So on this version the DevTools-specific
+ * attach-failure sentence ({@link browserDevToolsOpenMessage}) is UNREACHABLE: it stays wired behind
+ * an injected `isDevToolsOpen` check (design §2.3 rule 1 — name the cause, never "not drivable") in
+ * case a future Electron bump reintroduces the single-client rule, but attach does not fail for that
+ * reason today. The generic named attach-failure path is the one that runs.
+ *
+ * CDP child-session bookkeeping is lifted from PR #112's S8 with credit to @Corvin (proteus-dev) —
+ * the flat-mode `Target.attachToTarget`, the per-target session map, and BOTH invalidation points.
+ * Its THIRD invalidation trigger — a handoff to a different controlling session — is designed away
+ * rather than reimplemented: there is no handoff in this design (Task 4.3), so removing the feature
+ * that needed the care beats reimplementing the care.
+ *
+ * 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 DebuggerLike, sendCdp } from './browser-cdp-send'
+
+/** The lease outlives the last verb by this long; a verb within the window does not re-attach. */
+export const LEASE_IDLE_MS = 60_000
+/** How long the indicator (PR 6) lingers after a lease ends, so a burst of verbs does not flicker
+ * the chip off between them. Consumed by PR 6, exported here so the two constants live together. */
+export const INDICATOR_LINGER_MS = 5_000
+
+/** Pure, so the ledger, the indicator and the discard-suppression sweep all agree on "still live". */
+export function leaseIsActive(now: number, leaseActiveUntil: number): boolean {
+ return leaseActiveUntil > now
+}
+
+/** Name the cause — a DevTools window, not a permissions failure. UNREACHABLE on Electron 42.8.1
+ * (see the probe above); kept for a future Electron that restores the single-client rule. */
+export const browserDevToolsOpenMessage = (id: string): string =>
+ `browser: ${id} has DevTools open; close them to let an agent drive it`
+
+/** A generic, NAMED attach failure — the page likely just closed. Never "not drivable" (that reads
+ * as a permissions verdict and sends the next debugger to the identity code). */
+export const browserAttachFailedMessage = (id: string): string =>
+ `browser: ${id} could not be attached for control (its page may have just closed); ` +
+ `bring it on screen or open a new one`
+
+/** The named outcome for a command still in flight when the lease detaches — never a hang. */
+export const BROWSER_LEASE_DETACHED =
+ 'browser: the control lease detached while a command was in flight; the page was released — try again'
+
+/** The named outcome for a child-target command with no live session (invalid after a detach). */
+export const BROWSER_NO_LIVE_SESSION =
+ 'browser: that page target is no longer attached (the page navigated or was released); re-read it'
+
+export interface BrowserSessionOpts {
+ /** The browser node this session drives (validated upstream in the guest registry). */
+ nodeId: string
+ /** Injected `webContents.debugger`. */
+ debugger: DebuggerLike
+ /** The current viewport, refreshed by PR 7 from `Page.getLayoutMetrics`; read at send time so a
+ * resize between verbs is reflected in the coordinate bound. */
+ viewport: () => CdpContext
+ /** Clock, injected for tests. */
+ now?: () => number
+ /** Does the user have DevTools open on this guest? Only consulted on an attach failure. */
+ isDevToolsOpen?: () => boolean
+ /** Push the new `leaseActiveUntil` to the ledger (drives the indicator + discard suppression). */
+ onLeaseChange?: (leaseActiveUntil: number) => void
+}
+
+/**
+ * One guest's control session. Owns the attach lifecycle, the flat-mode child sessions, and the
+ * in-flight rejection on detach. Pure enough to unit-test with a fake {@link DebuggerLike}; the real
+ * attach/detach is exercised in the Electron harness.
+ */
+export class BrowserSession {
+ private readonly nodeId: string
+ private readonly dbg: DebuggerLike
+ private readonly viewport: () => CdpContext
+ private readonly now: () => number
+ private readonly isDevToolsOpen: () => boolean
+ private readonly onLeaseChange: (until: number) => void
+
+ private attached = false
+ private _leaseActiveUntil = 0
+ /**
+ * 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.
+ */
+ private readonly targets = new Map<string, string>()
+ private readonly detachRejectors = new Set<(e: Error) => void>()
+
+ constructor(opts: BrowserSessionOpts) {
+ this.nodeId = opts.nodeId
+ this.dbg = opts.debugger
+ this.viewport = opts.viewport
+ this.now = opts.now ?? Date.now
+ this.isDevToolsOpen = opts.isDevToolsOpen ?? (() => false)
+ this.onLeaseChange = opts.onLeaseChange ?? (() => {})
+ // A detach from ANY cause — our own detach, an idle detach, or a webContents teardown (which
+ // fires `detach` with reason "target closed") — invalidates the attachment and every child
+ // session, and must reject anything still in flight. One handler covers all of them.
+ this.dbg.on('detach', () => this.onDetached())
+ }
+
+ get leaseActiveUntil(): number {
+ return this._leaseActiveUntil
+ }
+
+ isAttached(): boolean {
+ return this.attached
+ }
+
+ /** The live session id for a target, or undefined. A caller must ALWAYS read this fresh — never
+ * cache a session id across a possible detach. */
+ sessionFor(targetId: string): string | undefined {
+ return this.targets.get(targetId)
+ }
+
+ /** Is this exact session id still the live one for this target? False after any detach — which is
+ * how a reused post-reattach session id is refused. */
+ isValidSession(targetId: string, sessionId: string): boolean {
+ return this.targets.get(targetId) === sessionId
+ }
+
+ /** Send a root-target command: attach if needed, extend the lease, and race the send against a
+ * detach so it can never hang past a release. */
+ send(method: string, params: object): Promise<unknown> {
+ return this.dispatch(method, params, undefined)
+ }
+
+ /** 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> {
+ const sessionId = this.targets.get(targetId)
+ if (!sessionId) return Promise.reject(new Error(BROWSER_NO_LIVE_SESSION))
+ return this.dispatch(method, params, sessionId)
+ }
+
+ /** Attach to a child target in FLAT mode, record its session id, return it. */
+ async attachTarget(targetId: string): Promise<string> {
+ const res = (await this.send('Target.attachToTarget', { targetId, flatten: true })) as {
+ sessionId?: string
+ }
+ const sessionId = res?.sessionId
+ if (typeof sessionId !== 'string' || !sessionId) {
+ throw new Error(BROWSER_NO_LIVE_SESSION)
+ }
+ this.targets.set(targetId, sessionId)
+ return sessionId
+ }
+
+ /** Detach a child target and forget its session id. No-op if it has none. */
+ async detachTarget(targetId: string): Promise<void> {
+ const sessionId = this.targets.get(targetId)
+ if (!sessionId) return
+ // Delete FIRST: even if the detach send rejects, the id must not stay usable.
+ this.targets.delete(targetId)
+ await this.send('Target.detachFromTarget', { sessionId })
+ }
+
+ /** Detach if the lease has gone idle. Returns whether it detached (for the sweep's logging). */
+ maybeDetachIdle(now: number = this.now()): boolean {
+ if (this.attached && !leaseIsActive(now, this._leaseActiveUntil)) {
+ this.detachInternal()
+ return true
+ }
+ return false
+ }
+
+ /** The session is ending (owner gone, project closed, app teardown): detach and reject in-flight. */
+ release(): void {
+ this.detachInternal()
+ this._leaseActiveUntil = 0
+ this.onLeaseChange(0)
+ }
+
+ /** The webContents was torn down under us: the attachment and every session id are already dead —
+ * forget them and reject in-flight, but do NOT call `detach()` on a gone target. (This is the
+ * second of the two invalidation points; the `detach` event usually beats us here, and this makes
+ * the teardown path correct even if it does not.) */
+ handleTeardown(): void {
+ this.onDetached()
+ this._leaseActiveUntil = 0
+ this.onLeaseChange(0)
+ }
+
+ // There is deliberately NO handoff-invalidation path: this design has no handoff (Task 4.3), so the
+ // class of bug S8's third trigger guarded against cannot occur here. We removed the feature that
+ // needed the care rather than reimplementing the care.
+
+ private dispatch(method: string, params: object, sessionId: string | undefined): Promise<unknown> {
+ try {
+ this.ensureAttached()
+ } catch (e) {
+ return Promise.reject(e)
+ }
+ this.extendLease()
+ return this.race(sendCdp(this.dbg, method, params, this.viewport(), sessionId))
+ }
+
+ private ensureAttached(): void {
+ if (this.attached) return
+ try {
+ this.dbg.attach('1.3')
+ } catch {
+ const msg = this.isDevToolsOpen()
+ ? browserDevToolsOpenMessage(this.nodeId)
+ : browserAttachFailedMessage(this.nodeId)
+ throw new Error(msg)
+ }
+ this.attached = true
+ }
+
+ private extendLease(): void {
+ this._leaseActiveUntil = this.now() + LEASE_IDLE_MS
+ this.onLeaseChange(this._leaseActiveUntil)
+ }
+
+ private detachInternal(): void {
+ if (this.attached) {
+ try {
+ this.dbg.detach()
+ } catch {
+ // A detach on an already-gone target throws; the state cleanup below is what matters.
+ }
+ }
+ this.onDetached()
+ }
+
+ private onDetached(): void {
+ this.attached = false
+ this.targets.clear()
+ this.rejectInFlight()
+ }
+
+ private rejectInFlight(): void {
+ const rejectors = [...this.detachRejectors]
+ this.detachRejectors.clear()
+ for (const reject of rejectors) reject(new Error(BROWSER_LEASE_DETACHED))
+ }
+
+ private race<T>(p: Promise<T>): Promise<T> {
+ let rejector!: (e: Error) => void
+ const guard = new Promise<never>((_, reject) => {
+ rejector = reject
+ this.detachRejectors.add(rejector)
+ })
+ return Promise.race([p, guard]).finally(() => {
+ this.detachRejectors.delete(rejector)
+ }) as Promise<T>
+ }
+}
+
+/**
+ * Owns every live {@link BrowserSession}, keyed by node id. index.ts holds one of these (PR 7 wires
+ * real guests to it; in PR 5 it is inert but real). Its `targetSessions` view — nodeId → (targetId →
+ * sessionId) — is the S8 aggregate the child-session bookkeeping lives under.
+ */
+export class BrowserLeaseManager {
+ private readonly sessions = new Map<string, BrowserSession>()
+
+ get(nodeId: string): BrowserSession | undefined {
+ return this.sessions.get(nodeId)
+ }
+
+ set(nodeId: string, session: BrowserSession): void {
+ this.sessions.set(nodeId, session)
+ }
+
+ /** Release + drop one node's session (its guest is gone or its owner was released). */
+ release(nodeId: string): void {
+ const session = this.sessions.get(nodeId)
+ if (!session) return
+ session.release()
+ this.sessions.delete(nodeId)
+ }
+
+ /** Idle sweep: detach every session whose lease has expired. Sessions stay in the map (they
+ * re-attach on the next verb); only the debugger attachment is dropped. */
+ sweepIdle(now: number): void {
+ for (const session of this.sessions.values()) session.maybeDetachIdle(now)
+ }
+
+ /** App teardown: release everything. */
+ releaseAll(): void {
+ for (const session of this.sessions.values()) session.release()
+ this.sessions.clear()
+ }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 69c6c8635..1025c3a86 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -16,6 +16,7 @@ installLogSink(logBuffer)
import { writeFilesToClipboard } from './clipboard-files'
import { allowGuestNavigation } from './webview-nav'
import { BrowserControlLedger } from './browser-control-ledger'
+import { BrowserLeaseManager } from './browser-lease'
import { registerFsHandlers } from '../core/fs-handlers'
import { LogBuffer } from '../core/log-buffer'
import { installLogSink, splitTag } from '../core/log-sink'
@@ -2326,6 +2327,12 @@ app.whenReady().then(async () => {
// 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()
+ // Holds the debugger lease per driven browser node. Built and unit-tested in PR 5 but INERT here:
+ // no `browser` verb exists until PR 7, so nothing attaches a guest to it yet. PR 7 wires each
+ // guest's `webContents.debugger` into a BrowserSession, starts the idle sweep, and releases on
+ // owner/project/app teardown. Owned here so that wiring has one home. See browser-lease.ts.
+ const browserLeases = new BrowserLeaseManager()
+ void browserLeases
ipcMain.on(
IPC.agentControlResult,
(