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.

fix(windows): keep released and npm-launched agents messageable

Fabricio Casali2ccb922fa6b1
diff --git a/CLAUDE.md b/CLAUDE.md
index 7e480c07e..462d167ef 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -73,9 +73,22 @@ means — and what you may assume when writing a feature — is three tiers, not
**Direct Windows agent messaging:** `core/native-windows-pane.ts` owns a headless screen for
non-persistent native PTYs. Lookup uses the runtime node index, and the console identity probe
-uses `GetConsoleProcessList` plus OS executable paths/birth times. A single native process reached
+uses `GetConsoleProcessList` plus OS executable paths/birth times. A single process reached
through an unambiguous shell chain is required; detached or ambiguous candidates refuse. This
-is not a POSIX foreground-process-group claim. The project/verified-hook/idle/receipt gates still
+is not a POSIX foreground-process-group claim. **An interpreter (`node`, `bun`, `python`, …) is
+named by its script, never by its own executable**: every npm-installed agent CLI on Windows is
+`cmd` → `node <package>\bin\<cli>.js`, and naming that pane `node` made Codex and every npx
+custom agent `not-agent`. The probe keeps only the interpreter's FIRST positional argument
+(`CommandLineToArgvW`, inside PowerShell; the rest of the command line, prompt text included, never
+leaves the probe) and `scriptCommandName` maps it to the key of its package's `bin` map, which is
+the table npm generated the `.cmd` shim from, falling back to the script basename exactly as the
+POSIX predicate does. The interpreter is the leaf, never a hop, so a CLI's own children (Codex's
+native `codex.exe`, MCP servers) cannot make the pane ambiguous.
+**A RELEASED session is still a messaging target.** Park expiry and the offscreen release drop the
+`Session`, but the host keeps it running, so `targetLive` asks `PtyManager.sessionExists` (attached,
+else tmux, else the host, with a failed read answering "exists") and the owner/paste/envelope probes
+route through `sessionHostOwns`, which falls back to the release record. Asking only for an attached
+client answered `targetGone`, terminal and never queued, about a live agent in another project. The project/verified-hook/idle/receipt gates still
apply, paste mode must be observed, and the exact generation/process is checked before writing.
`PtyManager.sendText` (the confirmed `write` verb, rename, note push, dictation) also routes a
direct native PTY through `NativeWindowsPane.sendText` — framed only when paste mode was requested,
@@ -588,7 +601,8 @@ Lifecycle, by intent:
landed. The predicate is deliberately the narrowest one that closes it — a tmux-backed session is
never protected (the kill costs a redraw), and neither is a plain terminal. **An IDLE agent CLI on
a non-persistent pty IS protected** (`agentProcess`, `agentProcessInPane`; not once hibernated,
- paused or dropped): killing it looked free because cold restore `--resume`s it on revive, but the
+ paused, dropped, or once its CLI announced a SessionEnd, `sessionEnded`, which is its own
+ transient flag because `state: undefined` alone is also what an idle agent looks like): killing it looked free because cold restore `--resume`s it on revive, but the
resumed CLI fires `SessionStart:resume` and idles with no further hook event, the status mirror
leaves it unverified, and agent messaging refused it for as long as it stayed idle — measured
2026-09-13 on Windows native ptys. The mirror now also lets a verified `idle_prompt` right after a
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 2dac85742..2a13c85a6 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -60,6 +60,9 @@ handler needs something only Electron has (an SSH ControlMaster, a native dialog
not the persistence key. `NativeWindowsPane` checks console membership, the unambiguous native
process chain and process birth times, and frames paste only after the terminal requested it.
Do not replace that read with a stored `agentId` or the restart heuristic's deepest descendant.
+An interpreter such as `node` is named by its script's package `bin` entry, never as `node`, so
+npm-installed CLIs such as Codex are recognized. A session released by park expiry or offscreen
+release is still messageable: existence and routing ask the backend, not the attached client.
The persistent session-host transport has its own versioned messaging extension: the host checks
its session generation, OS process identity and emulator before writing. An older live host keeps
its terminals and refuses the extension; never restart it automatically or fall back to sendKeys.
diff --git a/docs/windows-session-host.md b/docs/windows-session-host.md
index 1f3fac764..7dc261e6c 100644
--- a/docs/windows-session-host.md
+++ b/docs/windows-session-host.md
@@ -487,7 +487,14 @@ identity through console membership and an unambiguous shell-child chain. Proces
and a generation id detect replacement/PID reuse. It deliberately does not choose an arbitrary
deepest descendant, interpret prompt text as an executable, or accept a detached console.
This Windows ownership evidence is not POSIX foreground-group semantics; ambiguous console
-trees and interpreter-only wrappers refuse. Existing project consent, verified idle hooks,
+trees refuse. An interpreter is identified by its script: the probe keeps only the first
+positional argument (`CommandLineToArgvW`, inside PowerShell) and `scriptCommandName` resolves it
+to the command its npm package publishes in `bin`, else to the script basename. Measured on
+Windows 11 (2026-09-14) against a live Codex pane opened from the canvas: the PR-era probe read
+`node` and the installed app refused `send` with `targetNotAgentPane (observed: node)`, while the
+new probe read `codex` (`agent`) from the same console. A fake npm package in a separate console
+confirmed the prompt argument never appears in the probe output. The
+interpreter is the leaf; its children (a native `codex.exe`, MCP servers) do not count. Existing project consent, verified idle hooks,
delivery locks, post-write verification and receipt tracking remain in force.
The persistent host has a separate, additive messaging extension (`messageOwnerV1`,
@@ -498,6 +505,11 @@ that the same session object is still registered after every await. The resultin
sanitized multiline bracketed paste plus Enter. Main still owns the project/consent/hook/binary
and receipt gates. The direct adapter is never used for host-backed sessions.
+A host-backed session stays addressable after the desktop releases its client (park expiry,
+offscreen release). `targetLive` comes from `PtyManager.sessionExists`, and the three messaging
+probes route by `sessionHostOwns`, which reads the release record when no `Session` is left and
+otherwise applies `sendText`'s rule (no local tmux means the host owns persistence).
+
The extension is independently versioned so the existing terminal protocol v1/v2 is unchanged.
Old live hosts reject the new command names, and the client returns null/false without falling
back to `write`, `sendKeys`, or a local tmux. **Installing a new app does not upgrade an already
diff --git a/src/core/agents/agent-messaging.ts b/src/core/agents/agent-messaging.ts
index 41bd6325e..86f9545c3 100644
--- a/src/core/agents/agent-messaging.ts
+++ b/src/core/agents/agent-messaging.ts
@@ -70,7 +70,14 @@ export interface AgentMessagingDeps {
paneOwner(nodeId: string): Promise<PaneOwner | null>
sendEnvelope(nodeId: string, envelope: string, expected?: PaneOwner): Promise<boolean>
envelopePasteReady?(nodeId: string): Promise<boolean>
- hasLiveSession(nodeId: string): boolean
+ /**
+ * Does a session exist for this node at all — attached in this process OR held by a backend
+ * after its client was released (`PtyManager.sessionExists`)? The delivery's `targetLive` fact.
+ * A probe that could not answer must answer true: only confirmed absence is `targetGone`, which
+ * is terminal and never queued. Asking only for an ATTACHED client told orchestrators that a
+ * parked or offscreen-released agent was gone while its session kept running.
+ */
+ hasLiveSession(nodeId: string): boolean | Promise<boolean>
mirrorEntry?(nodeId: string): MirrorEntry | undefined
/** The main-process projects store (`workspaceStore.persistedCanvases()` on the desktop). */
projects(): readonly { id: string; nodes: readonly MessagingStoredNode[] }[]
@@ -587,7 +594,7 @@ export async function runDelivery(
targetIsRemote: deps.isRemoteNode(req.targetNodeId),
notPermitted,
retryAfterMs,
- targetLive: deps.hasLiveSession(req.targetNodeId)
+ targetLive: await deps.hasLiveSession(req.targetNodeId)
},
delivery
)
diff --git a/src/core/pty-manager.pane-owner.test.ts b/src/core/pty-manager.pane-owner.test.ts
index d52ce1494..48f86e210 100644
--- a/src/core/pty-manager.pane-owner.test.ts
+++ b/src/core/pty-manager.pane-owner.test.ts
@@ -130,6 +130,44 @@ describe('PtyManager.paneOwner', () => {
expect(calls).toHaveLength(0) // No fallback to the POSIX tmux that is also installed.
})
+ it('reaches a RELEASED session-host generation through its release record, never tmux', async () => {
+ // Park expiry / offscreen release drops the Session, but the host keeps the session running.
+ // Before the release record carried the backend, every probe fell through to the tmux branch
+ // (installed here on purpose) and a live agent read as unreachable.
+ const mgr = await manager() as unknown as {
+ sessions: Map<string, unknown>
+ released: Map<string, unknown>
+ paneOwner(id: string): Promise<unknown>
+ envelopePasteReady(id: string): Promise<boolean>
+ sendEnvelope(id: string, text: string, expected?: unknown): Promise<boolean>
+ }
+ mgr.sessions.clear()
+ mgr.released.set(NODE, { sessionId: 'host-session', remote: false, sessionHost: true })
+ const expected = { panePid: 10, tty: 'win32-console:10', paneId: 'host-generation', command: 'opencode', argv: ['opencode'] }
+ hostMessaging.owner.mockResolvedValueOnce(expected)
+ hostMessaging.pasteReady.mockResolvedValueOnce(true)
+ hostMessaging.send.mockResolvedValueOnce(true)
+ expect(await mgr.paneOwner(NODE)).toEqual(expected)
+ expect(await mgr.envelopePasteReady(NODE)).toBe(true)
+ expect(await mgr.sendEnvelope(NODE, 'message', expected)).toBe(true)
+ expect(hostMessaging.send).toHaveBeenCalledWith(TARGET, 'message', expected)
+ expect(calls).toHaveLength(0)
+ })
+
+ it('keeps a released TMUX generation on the tmux path', async () => {
+ const mgr = await manager() as unknown as {
+ sessions: Map<string, unknown>
+ released: Map<string, unknown>
+ paneOwner(id: string): Promise<unknown>
+ }
+ mgr.sessions.clear()
+ mgr.released.set(NODE, { sessionId: 'sess-1', remote: false, sessionHost: false })
+ hostMessaging.owner.mockClear()
+ await mgr.paneOwner(NODE)
+ expect(hostMessaging.owner).not.toHaveBeenCalled()
+ expect(calls[0]?.file).toBe('/usr/bin/tmux')
+ })
+
it('finds a live non-persistent Windows node by its runtime index', async () => {
const mgr = await manager({ tmux: null }) as unknown as {
sessions: Map<string, unknown>
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 6329c5798..020df606c 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -988,7 +988,10 @@ export class PtyManager {
* persisted node this process has ever released: the same order as the session map itself, and
* rewritten rather than appended on every subsequent release of the same node.
*/
- private released = new Map<string, { sessionId: string; size?: PtySize; remote: boolean }>()
+ private released = new Map<
+ string,
+ { sessionId: string; size?: PtySize; remote: boolean; sessionHost?: boolean }
+ >()
/**
* The ONE control-mode client this manager keeps for background WRITES, plus the node whose tmux
* session it is attached to (see `backgroundWrite` / `sharedClientFor`).
@@ -1112,7 +1115,10 @@ export class PtyManager {
this.released.set(session.persistKey, {
sessionId,
size: session.appliedSize,
- remote: !!session.sshRemote
+ remote: !!session.sshRemote,
+ // Which backend still holds the session after this client goes. Agent messaging reaches a
+ // released session by NAME, and must ask the backend that owns it (`sessionHostOwns`).
+ sessionHost: !!session.sessionHost
})
releasePty(session.proc as ReleasablePty)
this.forget(sessionId, session)
@@ -2470,6 +2476,25 @@ export class PtyManager {
return undefined
}
+ /**
+ * Does the Windows session host own this node's persistent session, whether or not a client of
+ * ours is attached to it right now?
+ *
+ * A live generation answers for itself. A RELEASED one (park expiry, offscreen release) has no
+ * `Session` left, but the host keeps the session running, so the release record answers. A node
+ * this process never attached (an app restart, a project not yet opened) mirrors `sendText`'s
+ * rule: with no local tmux, the session host is this machine's persistence backend.
+ *
+ * Without the released leg, every messaging probe of a released session-host node fell through
+ * to the POSIX tmux branch, which on Windows answers null: the agent was alive and unreachable.
+ */
+ private sessionHostOwns(persistKey: string, live: Session | undefined): boolean {
+ if (live) return !!live.sessionHost
+ const known = this.released.get(persistKey)
+ if (known) return known.sessionHost === true
+ return !this.tmuxPath && this.getSettings().tmuxEnabled && sessionHostSupported()
+ }
+
/** The exact live generation for a node id, including a non-persistent indexed plain shell. */
private liveSessionForPersistKey(persistKey: string): Session | undefined {
const indexedId = this.byPersistKey.get(persistKey)
@@ -4410,7 +4435,7 @@ export class PtyManager {
}
// Only the owning host may attest this generation. An older live host rejects the
// extension; that refusal must never fall through to an unrelated POSIX tmux.
- if (live?.sessionHost) return sessionHostMessageOwner(target)
+ if (this.sessionHostOwns(persistKey, live)) return sessionHostMessageOwner(target)
if (!this.tmuxPath) return null
const first = await runAsync(this.tmuxPath, [
'-L',
@@ -4469,7 +4494,7 @@ export class PtyManager {
const live = this.liveSessionForPersistKey(persistKey)
if (live?.nativeWindowsPane) return live.nativeWindowsPane.sendEnvelope(envelope, expected)
const target = sessionName(persistKey)
- if (live?.sessionHost) {
+ if (this.sessionHostOwns(persistKey, live)) {
return expected ? sessionHostMessageEnvelope(target, envelope, expected) : false
}
const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote
@@ -4505,7 +4530,7 @@ export class PtyManager {
async envelopePasteReady(persistKey: string): Promise<boolean> {
const live = this.liveSessionForPersistKey(persistKey)
if (live?.nativeWindowsPane) return live.nativeWindowsPane.pasteAware()
- if (live?.sessionHost) return sessionHostMessagePasteReady(sessionName(persistKey))
+ if (this.sessionHostOwns(persistKey, live)) return sessionHostMessagePasteReady(sessionName(persistKey))
// Existing tmux path frames in paste-buffer -p.
return !!(live?.sshRemote || this.tmuxPath)
}
diff --git a/src/main/index.ts b/src/main/index.ts
index 71880654e..645b1c184 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1796,7 +1796,8 @@ app.whenReady().then(async () => {
paneOwner: (id) => ptyManager.paneOwner(id),
sendEnvelope: (id, envelope, expected) => ptyManager.sendEnvelope(id, envelope, expected),
envelopePasteReady: (id) => ptyManager.envelopePasteReady(id),
- hasLiveSession: (id) => ptyManager.hasLiveSession(id),
+ // Attached OR released-but-running: see AgentMessagingDeps.hasLiveSession.
+ hasLiveSession: (id) => ptyManager.sessionExists(id),
projects: () => workspaceStore.persistedCanvases(),
isRemoteNode: (id) => !!ptyManager.sshRemoteForNode(id),
// GLOBAL CONSTRAINT 11: every delivery path is gated behind the per-project switch. The switch
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 93d5ed408..e633ecba7 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -13054,9 +13054,15 @@ export function Canvas() {
// (the cold-restore's own resume, or a hand-launched relaunch) is the only live proof
// that node was watching for.
cs.setPaused(e.nodeId, false)
+ // A new CLI is in the pane: whatever exited before it no longer describes this node.
+ cs.setSessionEnded(e.nodeId, false)
}
if (e.sessionPhase === 'end') {
cs.setState(e.nodeId, undefined, e.agentId)
+ // Recorded as its OWN fact, after the state: `state: undefined` alone is what an idle
+ // agent looks like, and the memory levers would keep protecting a pane that now holds
+ // only a shell (see `agentProcessInPane`).
+ cs.setSessionEnded(e.nodeId, true)
// In-session /loop dies with its session; cron (and scheduled cloud routines)
// keep running after it — their cards stay until CronDelete / manual dismiss.
const kind = cs.byId[e.nodeId]?.loop?.kind
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 7ab654d45..8068fd4cb 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -478,6 +478,8 @@ interface ParkedTerminal {
parkedAgentState?: AgentState
/** An agent CLI was in the pane at park time — see `ParkedEntryState.agentProcess`. */
agentProcess: boolean
+ /** Live read: has the CLI announced its exit since? The veto over `agentProcess`. */
+ readSessionEnded: () => boolean
/** When this entry was parked — what ages the snapshot above (`parkedStateFloor`). */
parkedAt: number
/** The node's agent state RIGHT NOW, read from the store of the session this node belongs to
@@ -510,6 +512,7 @@ function parkDisposable(key: string): boolean {
tmuxBacked: p.tmuxBacked,
parkedAgentState: p.parkedAgentState,
agentProcess: p.agentProcess,
+ liveSessionEnded: p.readSessionEnded(),
parkedAt: p.parkedAt,
liveAgentState: p.readAgentState()
})
@@ -4359,6 +4362,7 @@ export function TerminalNode({
// agent status on this very unmount — every lever reads later and would see nothing.
parkedAgentState: readAgentState(),
agentProcess: readAgentProcessRef.current(),
+ readSessionEnded: () => agentStatusStore.getState().byId[id]?.sessionEnded === true,
parkedAt: Date.now(),
readAgentState,
cleanups,
diff --git a/src/renderer/state/agentStatus.test.ts b/src/renderer/state/agentStatus.test.ts
index 31eeabe6c..08f9ae0f0 100644
--- a/src/renderer/state/agentStatus.test.ts
+++ b/src/renderer/state/agentStatus.test.ts
@@ -19,6 +19,40 @@ afterEach(() => {
vi.useRealTimers()
})
+describe('sessionEnded — an announced exit is its own fact, not an idle state', () => {
+ it('is set explicitly and withdrawn by the next state transition', () => {
+ const id = nid()
+ const s = useAgentStatus.getState()
+ s.setState(id, 'done', 'claude')
+ s.setState(id, undefined, 'claude')
+ useAgentStatus.getState().setSessionEnded(id, true)
+ expect(useAgentStatus.getState().byId[id]?.sessionEnded).toBe(true)
+ const same = useAgentStatus.getState().byId
+ useAgentStatus.getState().setSessionEnded(id, true)
+ expect(useAgentStatus.getState().byId).toBe(same)
+ useAgentStatus.getState().setState(id, 'working', 'claude', true)
+ expect(useAgentStatus.getState().byId[id]?.sessionEnded).toBeUndefined()
+ })
+
+ it('can be recorded for a node whose status entry was already cleared (a parked pane)', () => {
+ const id = nid()
+ useAgentStatus.getState().setSessionEnded(id, true)
+ expect(useAgentStatus.getState().byId[id]?.sessionEnded).toBe(true)
+ useAgentStatus.getState().setSessionEnded(id, false)
+ expect(useAgentStatus.getState().byId[id]?.sessionEnded).toBeUndefined()
+ })
+
+ it('Canvas records it on SessionEnd and withdraws it on SessionStart', () => {
+ // A store flag with no writer is the bug in a new place: the levers would type-check and stay
+ // protected forever. Pinned at source level, like the setState argument list above.
+ const src = readFileSync(resolve(__dirname, '../../..', 'src/renderer/canvas/Canvas.tsx'), 'utf8')
+ const end = src.slice(src.indexOf("if (e.sessionPhase === 'end') {"))
+ expect(end.slice(0, 600)).toMatch(/cs\.setSessionEnded\(e\.nodeId, true\)/)
+ const start = src.slice(src.indexOf("if (e.sessionPhase === 'start') {"), src.indexOf("if (e.sessionPhase === 'end') {"))
+ expect(start).toMatch(/cs\.setSessionEnded\(e\.nodeId, false\)/)
+ })
+})
+
describe('done-holdoff race guard', () => {
// Claude Code runs hooks in parallel: the last PostToolUse's curl can land AFTER the
// Stop's curl. Without a holdoff that late "working" resurrects a finished turn.
diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.ts
index b3842f958..fc3393c6c 100644
--- a/src/renderer/state/agentStatus.ts
+++ b/src/renderer/state/agentStatus.ts
@@ -118,6 +118,19 @@ export interface AgentNodeStatus {
* it can still see.
*/
dropped?: boolean
+ /**
+ * This node's CLI announced its own exit (any SessionEnd hook: `/exit`, `/quit`,
+ * Ctrl+D) and nothing has started a session since.
+ *
+ * It exists because a SessionEnd used to be recorded only as `state: undefined`, which is also
+ * what an agent that is merely idle looks like. `agentId` is durable and outlives the CLI, so
+ * `agentProcessInPane` read every exited agent as still running, and the memory levers refused
+ * forever to release a non-persistent pane that held nothing but a shell.
+ *
+ * TRANSIENT, like `dropped`: it is a claim about a pane in this app run. Cleared by the next
+ * SessionStart and by any state transition, since only a live CLI fires those.
+ */
+ sessionEnded?: boolean
/** Which agent this node is running (claude/codex/gemini/…), when known. */
agentId?: AgentId
/**
@@ -241,6 +254,9 @@ export interface AgentStatusStore {
/** Record (or withdraw) the verdict that this node's CLI died unannounced. Transient; see
* `dropped`. Cheap to call repeatedly — it bails when the flag already reads that way. */
setDropped(id: string, on: boolean): void
+ /** Record (or withdraw) that this node's CLI announced its exit. Transient; see `sessionEnded`.
+ * Bails when the flag already reads that way. */
+ setSessionEnded(id: string, on: boolean): void
/** Record that this node just launched a background shell task (see `backgroundTaskAt`).
* Transient — nothing is written to localStorage. */
markBackgroundTask(id: string): void
@@ -560,6 +576,8 @@ export function createAgentStatusSession(
// (a late Stop POST would undo a hibernation we just performed), but it absolutely does
// disprove "this pane has no CLI in it". Nothing is saved — the flag is transient.
if (prev.dropped) next.dropped = undefined
+ // Same reasoning: a state transition is fired by a live CLI, so "it exited" no longer holds.
+ if (prev.sessionEnded) next.sessionEnded = undefined
const byId = { ...s.byId, [id]: next }
// `state` itself is transient, so a plain transition writes nothing — but dropping a
// PERSISTED flag has to reach disk, or a relaunch would restore a hibernated/paused node
@@ -701,6 +719,14 @@ export function createAgentStatusSession(
return { byId: { ...s.byId, [id]: { ...prev, dropped: on ? true : undefined } } }
}),
+ setSessionEnded: (id, on) =>
+ set((s) => {
+ const prev = s.byId[id] ?? EMPTY
+ if (!!prev.sessionEnded === on) return s
+ // Transient, no `save()`: see the field comment.
+ return { byId: { ...s.byId, [id]: { ...prev, sessionEnded: on ? true : undefined } } }
+ }),
+
markBackgroundTask: (id) =>
set((s) => {
const prev = s.byId[id] ?? EMPTY
diff --git a/src/renderer/terminal/live-work.test.ts b/src/renderer/terminal/live-work.test.ts
index dbba7d301..89b9179e1 100644
--- a/src/renderer/terminal/live-work.test.ts
+++ b/src/renderer/terminal/live-work.test.ts
@@ -41,6 +41,9 @@ describe('agentProcessInPane', () => {
expect(agentProcessInPane('claude', { hibernated: true })).toBe(false)
expect(agentProcessInPane('claude', { paused: true })).toBe(false)
expect(agentProcessInPane('claude', { dropped: true })).toBe(false)
+ // A SessionEnd (`/exit`) records only `state: undefined`, which is also what an idle agent
+ // looks like. Without its own flag the pane stayed protected for the rest of the run.
+ expect(agentProcessInPane('claude', { sessionEnded: true })).toBe(false)
})
})
diff --git a/src/renderer/terminal/live-work.ts b/src/renderer/terminal/live-work.ts
index c0c59b0cd..22eb17d7d 100644
--- a/src/renderer/terminal/live-work.ts
+++ b/src/renderer/terminal/live-work.ts
@@ -71,14 +71,27 @@ export function wouldKillLiveWork(i: LiveWorkInput): boolean {
/**
* Is an agent CLI believed to be running in the pane? An agent node whose CLI we already exited
- * (`hibernated`, `paused`) or that we observed die (`dropped`) holds only a shell — killing that
- * costs nothing a revive cannot restore, so it stays reclaimable.
+ * (`hibernated`, `paused`), that we observed die (`dropped`) or that announced its own exit
+ * (`sessionEnded`) holds only a shell — killing that costs nothing a revive cannot restore, so it
+ * stays reclaimable.
+ *
+ * An agent whose hooks never report a session end (codex, opencode: see `SESSION_END_CAPABLE`)
+ * keeps reading as running after a deliberate quit. That is the safe direction: memory held, no
+ * work lost.
*/
export function agentProcessInPane(
agentId: string | undefined,
- status: { hibernated?: boolean; paused?: boolean; dropped?: boolean } | undefined
+ status:
+ | { hibernated?: boolean; paused?: boolean; dropped?: boolean; sessionEnded?: boolean }
+ | undefined
): boolean {
- return !!agentId && status?.hibernated !== true && status?.paused !== true && status?.dropped !== true
+ return (
+ !!agentId &&
+ status?.hibernated !== true &&
+ status?.paused !== true &&
+ status?.dropped !== true &&
+ status?.sessionEnded !== true
+ )
}
/**
diff --git a/src/renderer/terminal/park-budget.test.ts b/src/renderer/terminal/park-budget.test.ts
index cb29358d2..5cf9022e6 100644
--- a/src/renderer/terminal/park-budget.test.ts
+++ b/src/renderer/terminal/park-budget.test.ts
@@ -152,6 +152,14 @@ describe('a parked plain-shell agent survives the departure clear (#126)', () =>
expect(canDisposeParkedEntry({ ...idleAgent, agentProcess: false })).toBe(true)
})
+ it('releases that park once its CLI announces an exit AFTER parking', () => {
+ // The snapshot was taken while the CLI ran; the live read is what can say it has since left.
+ const idleAgent: ParkedEntryState = { tmuxBacked: false, parkedAgentState: 'done', parkedAt, agentProcess: true }
+ expect(canDisposeParkedEntry({ ...idleAgent, liveSessionEnded: true })).toBe(true)
+ // The veto never overrides a live turn: exited-then-relaunched-and-working stays protected.
+ expect(canDisposeParkedEntry({ ...idleAgent, liveSessionEnded: true, liveAgentState: 'working' })).toBe(false)
+ })
+
it('keeps protecting a waiting snapshot past the same window', () => {
const waiting: ParkedEntryState = { ...working, parkedAgentState: 'waiting' }
expect(canDisposeParkedEntry(waiting, parkedAt + 10 * WORKING_STALE_MS)).toBe(false)
diff --git a/src/renderer/terminal/park-budget.ts b/src/renderer/terminal/park-budget.ts
index c83468237..e4c531590 100644
--- a/src/renderer/terminal/park-budget.ts
+++ b/src/renderer/terminal/park-budget.ts
@@ -70,6 +70,10 @@ export interface ParkedEntryState {
/** An agent CLI was running in the pane AT PARK TIME (`agentProcessInPane`). Snapshotted for
* the same reason as `parkedAgentState`: the parking unmount clears the node's status. */
agentProcess?: boolean
+ /** The node's CLI has announced its exit SINCE the park (`AgentNodeStatus.sessionEnded`, read
+ * live). A veto over the `agentProcess` snapshot, which only says what was true at park time:
+ * an unmounted pane keeps running, and its CLI can still exit (the kanban card modal). */
+ liveSessionEnded?: boolean
}
/** `canDisposePark` for a park entry: the live read, with the AGED park-time snapshot under it.
@@ -79,7 +83,7 @@ export interface ParkedEntryState {
export function canDisposeParkedEntry(e: ParkedEntryState, now: number = Date.now()): boolean {
return canDisposePark({
tmuxBacked: e.tmuxBacked,
- agentProcess: e.agentProcess,
+ agentProcess: e.agentProcess === true && e.liveSessionEnded !== true,
agentState: effectiveAgentState(
e.liveAgentState,
parkedStateFloor(e.parkedAgentState, e.parkedAt, now)
diff --git a/src/server/canvas-control.test.ts b/src/server/canvas-control.test.ts
index 6bcfd9b78..abddb0d4f 100644
--- a/src/server/canvas-control.test.ts
+++ b/src/server/canvas-control.test.ts
@@ -105,7 +105,8 @@ describe('initServerCanvasControl', () => {
destroySession: vi.fn(async () => undefined),
paneOwner,
sendEnvelope,
- hasLiveSession: () => true
+ hasLiveSession: () => true,
+ sessionExists: async () => true
} as unknown as PtyManager
const settings = (): Settings => ({ ...DEFAULT_SETTINGS })
@@ -252,7 +253,8 @@ describe('initServerCanvasControl', () => {
pids: [200]
})),
sendEnvelope: legacySendEnvelope,
- hasLiveSession: () => true
+ hasLiveSession: () => true,
+ sessionExists: async () => true
} as unknown as PtyManager
runtime = await initServerCanvasControl({
@@ -339,7 +341,8 @@ describe('initServerCanvasControl', () => {
destroySession: vi.fn(async () => undefined),
paneOwner: vi.fn(async () => null),
sendEnvelope: vi.fn(async () => true),
- hasLiveSession: () => true
+ hasLiveSession: () => true,
+ sessionExists: async () => true
} as unknown as PtyManager
runtime = await initServerCanvasControl({
diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.ts
index 82735cfa3..f6a4ebc74 100644
--- a/src/server/canvas-control.ts
+++ b/src/server/canvas-control.ts
@@ -192,7 +192,8 @@ export async function initServerCanvasControl(
// separate paste from Enter so a fresh TUI cannot swallow the first submit keystroke.
sendEnvelope: (nodeId, envelope) =>
sendSettledEnvelope(deps.ptyManager, nodeId, envelope),
- hasLiveSession: (nodeId) => deps.ptyManager.hasLiveSession(nodeId),
+ // Attached OR released-but-running: see AgentMessagingDeps.hasLiveSession.
+ hasLiveSession: (nodeId) => deps.ptyManager.sessionExists(nodeId),
mirrorEntry,
projects: () => deps.workspaceStore.persistedCanvases(),
isRemoteNode: () => false,
diff --git a/src/session-host/windows-pane-owner.test.ts b/src/session-host/windows-pane-owner.test.ts
index 434a2e934..730b271e1 100644
--- a/src/session-host/windows-pane-owner.test.ts
+++ b/src/session-host/windows-pane-owner.test.ts
@@ -1,6 +1,12 @@
import { describe, expect, it } from 'vitest'
import { isAgentPane } from '../shared/agents/pane-owner-predicate'
-import { windowsConsoleOwner, windowsConsoleProbeScript, type WindowsConsoleProcess } from './windows-pane-owner'
+import {
+ scriptCommandName,
+ windowsConsoleOwner,
+ windowsConsoleProbeScript,
+ type ReadPackageJson,
+ type WindowsConsoleProcess
+} from './windows-pane-owner'
const root: WindowsConsoleProcess = { pid: 10, parent: 1, executable: 'C:\\Program Files\\PowerShell\\7\\pwsh.exe', born: '2026-09-12T10:00:00Z' }
const agent: WindowsConsoleProcess = { pid: 20, parent: 10, executable: 'C:\\Users\\A User\\bin\\opencode.exe', born: '2026-09-12T10:00:01Z' }
@@ -29,6 +35,68 @@ describe('Windows console agent identity', () => {
expect(owner([{ ...root, born: '' }, agent])).toBeNull()
expect(owner([root, { ...agent, born: '2025-01-01T00:00:00Z' }])).toBeNull()
})
+ describe('npm-installed CLIs run through an interpreter', () => {
+ /** Written with `/` for legibility; the probe reports Windows separators. */
+ const w = (path: string): string => path.replace(/\//g, '\\')
+ const NPM = 'C:/Users/A User/AppData/Roaming/npm/node_modules'
+ // The real layouts measured on a Windows install, 2026-09-14.
+ const packages: Record<string, string> = {
+ [w(`${NPM}/@openai/codex/package.json`)]: JSON.stringify({ name: '@openai/codex', bin: { codex: 'bin/codex.js' } }),
+ [w(`${NPM}/@acme/agent/package.json`)]: JSON.stringify({ name: '@acme/agent', bin: { 'acme-agent': 'dist/cli.js' } }),
+ [w(`${NPM}/@acme/agent/dist/package.json`)]: JSON.stringify({ type: 'module' }),
+ [w(`${NPM}/solo/package.json`)]: JSON.stringify({ name: '@acme/solo', bin: 'cli.js' })
+ }
+ const read: ReadPackageJson = (file) => packages[file] ?? null
+ const cmd: WindowsConsoleProcess = { pid: 10, parent: 1, executable: w('C:/Windows/System32/cmd.exe'), born: '2026-09-14T10:00:00Z' }
+ const node = (script: string | undefined): WindowsConsoleProcess => ({
+ pid: 20, parent: 10, executable: w('C:/Program Files/nodejs/node.exe'), born: '2026-09-14T10:00:01Z', script
+ })
+ const probe = (rows: WindowsConsoleProcess[]) =>
+ windowsConsoleOwner(10, 'generation-a', { processes: rows, console: rows.map((r) => r.pid) }, read)
+
+ it('resolves the mixed separators a real npm shim hands node', () => {
+ // Measured on a live Codex pane: `npm.cmd` writes `%dp0%` with `\` and the rest with `/`.
+ const script = 'C:\\Users\\A User\\AppData\\Roaming\\npm/node_modules/@openai/codex/bin/codex.js'
+ expect(isAgentPane(probe([cmd, node(script)]), 'codex')).toBe('agent')
+ })
+
+ it('names Codex by its package bin, not node, and ignores its native child', () => {
+ const native = { pid: 30, parent: 20, executable: w(`${NPM}/@openai/codex/vendor/codex.exe`), born: '2026-09-14T10:00:02Z' }
+ const result = probe([cmd, node(w(`${NPM}/@openai/codex/bin/codex.js`)), native])
+ expect(isAgentPane(result, 'codex')).toBe('agent')
+ expect(result).toMatchObject({ pids: [20], command: 'node' })
+ })
+
+ it('keeps a pure-Node custom agent with several MCP children unambiguous, past a nested package.json', () => {
+ const mcp = (pid: number) => ({ pid, parent: 20, executable: w('C:/bin/python.exe'), born: '2026-09-14T10:00:03Z' })
+ const result = probe([cmd, node(w(`${NPM}/@acme/agent/dist/cli.js`)), mcp(31), mcp(32)])
+ expect(isAgentPane(result, 'custom:acme', ['acme-agent'])).toBe('agent')
+ })
+
+ it('resolves a string bin to the unscoped package name, through the doubled separator a shim emits', () => {
+ expect(scriptCommandName(w(`${NPM}//solo/cli.js`), read)).toBe('solo')
+ })
+
+ it('never promotes a script its nearest package does not publish', () => {
+ expect(scriptCommandName(w(`${NPM}/@openai/codex/bin/helper.js`), read)).toBe('helper.js')
+ expect(isAgentPane(probe([cmd, node(w(`${NPM}/@openai/codex/bin/helper.js`))]), 'codex')).toBe('not-agent')
+ })
+
+ it('stays node when the interpreter runs no script, and never reads a UNC or relative path', () => {
+ expect(isAgentPane(probe([cmd, node(undefined)]), 'codex')).toBe('not-agent')
+ expect(probe([cmd, node(undefined)])?.argv).toEqual(['node'])
+ const reads: string[] = []
+ const spy: ReadPackageJson = (file) => {
+ reads.push(file)
+ return null
+ }
+ expect(scriptCommandName(w('//server/share/codex.js'), spy)).toBe('codex.js')
+ expect(scriptCommandName(w('bin/codex.js'), spy)).toBe('codex.js')
+ expect(reads).toEqual([])
+ expect(scriptCommandName('evil name.js', spy)).toBeNull()
+ })
+ })
+
it('never interpolates a non-integer process identifier into PowerShell', () => {
expect(() => windowsConsoleProbeScript(NaN)).toThrow()
expect(() => windowsConsoleProbeScript(-1)).toThrow()
diff --git a/src/session-host/windows-pane-owner.ts b/src/session-host/windows-pane-owner.ts
index e3ecf20c1..8652fa76c 100644
--- a/src/session-host/windows-pane-owner.ts
+++ b/src/session-host/windows-pane-owner.ts
@@ -1,4 +1,6 @@
import { execFile } from 'child_process'
+import { readFileSync } from 'fs'
+import { win32 as winPath } from 'path'
import type { PaneOwner } from '../shared/agents/pane-owner-predicate'
/** Exact Windows console/process generation, not merely a reused PID or executable name. */
@@ -21,6 +23,12 @@ export interface WindowsConsoleProcess {
parent: number
executable: string
born: string
+ /**
+ * For an INTERPRETER on the console only: its first positional argument, the script it runs.
+ * The probe extracts it with `CommandLineToArgvW` and discards the rest of the command line, so
+ * prompt text never leaves the probe. Absent for everything else.
+ */
+ script?: string
}
export interface WindowsConsoleSnapshot {
@@ -28,15 +36,103 @@ export interface WindowsConsoleSnapshot {
processes: WindowsConsoleProcess[]
}
-const SHELLS = new Set(['pwsh', 'powershell', 'cmd'])
+const SHELLS = new Set(['pwsh', 'powershell', 'cmd', 'bash', 'sh'])
+/**
+ * Interpreters whose identity is the script they run, not their own executable. An npm-installed
+ * agent CLI on Windows is `cmd` -> `node <package>\bin\<cli>.js` (Codex measured 2026-09-14, with
+ * the native `codex.exe` as node's child). Naming such a pane `node` made it `not-agent`.
+ * Same list as the POSIX predicate's `INTERPRETERS`, so both platforms resolve the same shapes.
+ */
+const INTERPRETERS = new Set(['node', 'nodejs', 'bun', 'deno', 'python', 'python3', 'ruby', 'perl'])
function executableName(executable: string): string {
return (executable.replace(/\\/g, '/').split('/').pop() ?? '').toLowerCase().replace(/\.exe$/, '')
}
+/** Reads a `package.json` as text, or null when there is none to read. Injected for tests. */
+export type ReadPackageJson = (file: string) => string | null
+
+function readPackageJsonSync(file: string): string | null {
+ try {
+ return readFileSync(file, 'utf8')
+ } catch {
+ return null
+ }
+}
+
+const BIN_NAME = /^[A-Za-z0-9._@-]+$/
+
+/**
+ * The bin name a package publishes for `target`, `null` when the package publishes none for it, or
+ * `undefined` when this `package.json` is not a package root (a nested `{"type":"module"}`), so the
+ * walk continues upward.
+ */
+function binNameFor(raw: string, dir: string, target: string): string | null | undefined {
+ let pkg: unknown
+ try {
+ pkg = JSON.parse(raw)
+ } catch {
+ return undefined
+ }
+ if (!pkg || typeof pkg !== 'object') return undefined
+ const { name, bin } = pkg as { name?: unknown; bin?: unknown }
+ if (typeof name !== 'string' || !name) return undefined
+ const matches = (value: unknown): boolean =>
+ typeof value === 'string' && winPath.resolve(dir, value).toLowerCase() === target
+ let found: string | null = null
+ if (typeof bin === 'string') {
+ if (matches(bin)) found = name.split('/').pop() ?? null
+ } else if (bin && typeof bin === 'object') {
+ for (const [key, value] of Object.entries(bin as Record<string, unknown>)) {
+ if (matches(value)) {
+ found = key
+ break
+ }
+ }
+ }
+ return found && BIN_NAME.test(found) ? found : null
+}
+
+/**
+ * The command name an interpreter's script is installed under: the name the user typed.
+ *
+ * An npm CLI's script lives inside its package, and that package's `bin` map is the very table npm
+ * generated the `.cmd` shim from, so the key pointing at this script IS the command. An exact
+ * lookup, not a guess from the file name: Codex's script is `codex.js` and a bundled CLI's is often
+ * `index.js`, neither of which names the command.
+ *
+ * Anything that does not resolve through a package falls back to the script's basename, which is
+ * what the POSIX predicate derives from `node /path/agent.js`. A wrong answer is a name that matches
+ * nothing, i.e. a refusal. Only drive-absolute paths are read: a UNC path would reach another
+ * machine, and a relative one has no cwd to resolve against.
+ */
+export function scriptCommandName(script: string, read: ReadPackageJson = readPackageJsonSync): string | null {
+ const trimmed = script.trim()
+ if (!trimmed || /[\r\n\0]/.test(trimmed)) return null
+ const normalized = winPath.normalize(trimmed)
+ if (/^[A-Za-z]:\\/.test(normalized)) {
+ const target = normalized.toLowerCase()
+ let dir = winPath.dirname(normalized)
+ for (let depth = 0; depth < 8; depth++) {
+ const raw = read(winPath.join(dir, 'package.json'))
+ if (raw !== null) {
+ const name = binNameFor(raw, dir, target)
+ if (typeof name === 'string') return name
+ if (name === null) break // the nearest package root decides, and it published no bin for this
+ }
+ const parent = winPath.dirname(dir)
+ if (parent === dir) break
+ dir = parent
+ }
+ }
+ const base = winPath.basename(normalized)
+ return base && BIN_NAME.test(base) ? base : null
+}
+
export function windowsConsoleOwner(
rootPid: number,
generation: string,
- snapshot: WindowsConsoleSnapshot
+ snapshot: WindowsConsoleSnapshot,
+ read: ReadPackageJson = readPackageJsonSync
): PaneOwner | null {
const attached = new Set(snapshot.console)
const rows = new Map(snapshot.processes.map((row) => [row.pid, row]))
@@ -60,13 +156,19 @@ export function windowsConsoleOwner(
continue
}
}
+ // An interpreter is the leaf, never a hop: it is the process the console hands input to, and a
+ // CLI's own children (the native `codex.exe`, MCP servers) must not make the pane ambiguous.
+ const name = INTERPRETERS.has(binary) && current.script
+ ? scriptCommandName(current.script, read) ?? binary
+ : binary
return {
panePid: rootPid,
tty: `win32-console:${rootPid}`,
paneId: `win32:${generation}:${root.born}`,
command: binary,
- // Deliberately derived from the OS executable path, NOT arguments/prompt text.
- argv: [binary],
+ // Derived from the OS executable path, or for an interpreter from the ONE script argument the
+ // probe kept. Never from prompt text.
+ argv: [name],
pids: [current.pid],
processBirths: [current.born]
}
@@ -80,7 +182,8 @@ export function windowsConsoleOwner(
export function windowsConsoleProbeScript(rootPid: number): string {
if (!Number.isSafeInteger(rootPid) || rootPid <= 0) throw new Error('invalid console root PID')
return `$ErrorActionPreference = 'Stop';
-Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class NtConsoleProbe { [DllImport("kernel32.dll", SetLastError=true)] public static extern bool FreeConsole(); [DllImport("kernel32.dll", SetLastError=true)] public static extern bool AttachConsole(uint pid); [DllImport("kernel32.dll", SetLastError=true)] public static extern uint GetConsoleProcessList([Out] uint[] ids, uint length); }';
+Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class NtConsoleProbe { [DllImport("kernel32.dll", SetLastError=true)] public static extern bool FreeConsole(); [DllImport("kernel32.dll", SetLastError=true)] public static extern bool AttachConsole(uint pid); [DllImport("kernel32.dll", SetLastError=true)] public static extern uint GetConsoleProcessList([Out] uint[] ids, uint length); [DllImport("shell32.dll", SetLastError=true)] static extern IntPtr CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string cmd, out int count); [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr p); public static string ScriptArg(string cmd) { if (String.IsNullOrEmpty(cmd)) return ""; int n; IntPtr p = CommandLineToArgvW(cmd, out n); if (p == IntPtr.Zero) return ""; try { if (n < 2) return ""; string a = Marshal.PtrToStringUni(Marshal.ReadIntPtr(p, IntPtr.Size)); return (a == null || a.StartsWith("-")) ? "" : a; } finally { LocalFree(p); } } }';
+$interpreters = @('node', 'nodejs', 'bun', 'deno', 'python', 'python3', 'ruby', 'perl');
$self = $PID; $ids = @();
try {
[void][NtConsoleProbe]::FreeConsole();
@@ -91,7 +194,10 @@ try {
for ($i = 0; $i -lt $count; $i++) { if ($buffer[$i] -ne $self) { $ids += [int]$buffer[$i] } };
} finally { [void][NtConsoleProbe]::FreeConsole() };
$rows = @(Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -ne $self } | ForEach-Object {
- @{ pid = [int]$_.ProcessId; parent = [int]$_.ParentProcessId; executable = [string]$_.ExecutablePath; born = $(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { '' }) }
+ $row = @{ pid = [int]$_.ProcessId; parent = [int]$_.ParentProcessId; executable = [string]$_.ExecutablePath; born = $(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { '' }) };
+ $exe = ([IO.Path]::GetFileNameWithoutExtension([string]$_.ExecutablePath)).ToLower();
+ if (($ids -contains [int]$_.ProcessId) -and ($interpreters -contains $exe)) { $row.script = [NtConsoleProbe]::ScriptArg([string]$_.CommandLine) };
+ $row
});
@{ console = @($ids); processes = $rows } | ConvertTo-Json -Depth 4 -Compress;`
}