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): preserve idle agent messaging sessions

Fabricio Casalicbe6f9947b0c
diff --git a/CLAUDE.md b/CLAUDE.md
index 6dbd15e6d..7e480c07e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -71,6 +71,25 @@ means — and what you may assume when writing a feature — is three tiers, not
## Commands
+**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
+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
+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,
+no process attestation. It used to fall through to the session-host backend, which has no entry for
+a direct PTY, so every `write` to such a pane failed.
+Do not route the persistent session-host backend through this direct-PTY adapter. Its independently
+versioned `messageOwnerV1` / `messagePasteReadyV1` / `messageEnvelopeV1` extension runs in the host:
+the OS probe is bound to `HostSession.generation`, the session registry is rechecked after every
+await, and the emulator's paste mode is checked again immediately before the synchronous write.
+An older live host refuses these unknown commands while keeping the v1/v2 terminal contract intact;
+never replace it automatically or fall back to name-only input to enable messaging. Windows OpenCode
+context exports use the npm shim through PowerShell with a validated session identifier, not
+`execFile('opencode')` (which cannot execute the npm shim on Windows).
+
```bash
npm install # deps + rebuilds node-pty against Electron's ABI (postinstall hook)
npm run dev # dev mode with renderer HMR
@@ -567,8 +586,15 @@ Lifecycle, by intent:
identical call kills it and everything under it — an agent CLI mid-turn included. Issue #126: a
project switch terminated a working Claude agent, which then auto-resumed from wherever the kill
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, a finished agent or
- an unknown state (nothing is running to lose). **A fifth lever owes the same gate.**
+ 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
+ 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
+ verified `SessionStart` commit a verified non-inferred `done` (`MirrorEntry.sessionStarted`), and
+ the decider reports a proven node reset by a boundary as `targetNotIdleUnknown`, not
+ `targetStatusStale`. **A fifth lever owes the same gate.**
The fifth is the offscreen release of an ARMED node (`--after`, `shouldDeferReleaseForHeldLaunch`,
2026-09-02): the held launch is delivered by session NAME, so with tmux underneath the release is
harmless and the node stays `sessionReady` (the teardown keeps the flag for an offscreen release
@@ -1452,6 +1478,16 @@ the wire never see any of it):
## Agent support (Claude / Codex / Gemini / Copilot / opencode / Grok / custom)
+**Message scope publication:** desktop `send`/`reply`/`notify` wait for pending active-canvas edits
+to be saved when either endpoint is on that canvas (`renderer/lib/messageScopeSync.ts`). `list`
+and context links can already see a newly opened node while main's `persistedCanvases()` cannot;
+the scope resolver reports that absent target as `cross-project`. The publication barrier never
+travels, never overrides an external-edit conflict, and does not authorize anything: main still
+checks unique project membership, runtime ownership, consent, verified status and the native pane.
+An unrelated active canvas is not saved for a background message. Server control already writes
+its nodes through the authoritative store; the renderer barrier is a desktop concern. Mobile is
+not an agent-message sender.
+
The app is a pluggable multi-agent system: Claude Code is one builtin of
several. Extra terminal-node behavior is driven per agent by a registry + capability lists, a
shared 4-state model, and a **transient** zustand store `state/agentStatus.ts`
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0223794bd..2dac85742 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -56,6 +56,16 @@ handler needs something only Electron has (an SSH ControlMaster, a native dialog
**injected dep** whose absence is a documented degrade — see `registerTranscriptIpc` /
`registerContextEnsureIpc` — rather than a reason to keep the whole handler in `src/main`.
+**Windows agent messaging:** direct ConPTY terminals are looked up by the runtime node index,
+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.
+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.
+Message dispatch publishes pending canvas edits before main resolves scope, without overwriting
+an unresolved file conflict. See `docs/windows-session-host.md`.
+
## Three surfaces
A feature is not done until you have decided how it behaves on each — even if the decision is "not
diff --git a/docs/agent-messaging-idle-session-boundary-fix.md b/docs/agent-messaging-idle-session-boundary-fix.md
new file mode 100644
index 000000000..d384fb233
--- /dev/null
+++ b/docs/agent-messaging-idle-session-boundary-fix.md
@@ -0,0 +1,244 @@
+# Agent messaging: idle sessions killed and permanently reported as stale
+
+**Status: local fix, not committed, not upstream. Written for a PR against nodeterm.**
+Diagnosed and patched locally on a Windows desktop install
+(`C:\Desenv\particular\nodeterm`, base commit `2393e06a`) on 2026-09-13. Everything below is a
+description of that local diff (`git status`/`git diff` on that tree) plus what was and was not
+validated — not a claim that this has been reviewed or is ready to merge as-is.
+
+## The report this fixes
+
+A multi-agent orchestration (coordinator + architect + coder, all Claude Code, all on Windows,
+all non-tmux/native-PTY sessions) worked with `send`/`reply` for a while. Then, after each
+delivery, the receiving Claude session started refusing every further message as
+`targetStatusStale`, permanently:
+
+- `send` to the coder failed twice, then a `write` to it failed too; the coder was closed and
+ reopened, delivered its task, and *also* went `targetStatusStale` afterward.
+- The architect went the same way: `send` failed twice, `write` failed, and the terminal still
+ visibly showed Claude sitting at its prompt (not crashed, not busy).
+- The canvas kept every node the whole time — nothing showed as closed or gone.
+- Closing and recreating a node "fixed" it, which is a workaround, not a diagnosis.
+
+## Root cause — three independent bugs, all Windows-shaped, one shared consequence
+
+### 1. An idle agent CLI on a non-tmux backend gets killed by the ordinary memory levers
+
+`src/renderer/terminal/live-work.ts`'s `wouldKillLiveWork` (the shared gate behind offscreen
+release and all three park-eviction levers — see `CLAUDE.md`'s "Every memory lever must ask
+whether the kill ends live work") only protected a node whose `agentState` was
+`working`/`waiting`/`blocked`. A **`done`** agent CLI — an ordinary finished turn, sitting at its
+prompt — read as "nothing running to lose" and was released/parked-and-evicted exactly like a
+plain terminal.
+
+On tmux (mac/Linux) that is correct: releasing/evicting only detaches the client, the shell and
+the CLI process keep running underneath, and reattach is a warm redraw. **On Windows, when no
+real tmux is found, there is no shell underneath the CLI to survive the kill** — the pty *is* the
+CLI's own process tree (either a direct native PTY, or — after the session-host packaging fix
+below — a session-host-owned pty; either way, killing the client kills the process). The
+"protection" this predicate is supposed to provide never engaged for an idle-but-still-open Claude
+session, so:
+
+- The session went offscreen (project switch, pan away, or the 10-minute offscreen-release timer)
+ while idle → killed.
+- Cold-restore auto-resumed it with `claude --resume <id>` on revive, which *looks* like nothing
+ happened (same node, same title, same session id) — but see bug 2 for why that is where the
+ permanent refusal comes from.
+
+### 2. `SessionStart`/`SessionEnd` correctly resets messaging proof, but the refusal it produces is misleading
+
+`src/core/agent-status-mirror.ts`'s `reduceEffectiveEntry` treats every session boundary
+(`kind: 'session'`) as `commitState(undefined, false)` — the node's `state` goes to `undefined`
+and `stateVerified` goes to `false`. This part is correct and deliberate: a CLI that just
+started/resumed/ended cannot be assumed idle-and-safe-to-message.
+
+The bug is in what `src/core/agents/agent-message-decide.ts`'s `identityRefusal` reports for that
+entry. It only distinguished "never observed anything" (which needs `targetStatusStale`, a
+retryable *identity* refusal: "wait for it to prove itself") from every other case, which fell
+through to the same `targetStatusStale`. A node that **had** proven itself earlier in this run —
+delivered messages fine, `stateVerified: true` — and then crossed a `SessionStart`/`SessionEnd`
+boundary (a resume, an in-place restart, a plain relaunch) was reported with the *same* wording:
+"the target has a node identity but has not posted a verified status yet." That is a false
+statement about a node whose identity was never in question — the honest fact is `idleRefusal`'s
+own "the node is between sessions (no current state)", but `identityRefusal` runs first in
+`decidePreProbe` and pre-empts it.
+
+Because a Claude CLI that just resumed and is sitting idle at its prompt, with nothing to do, may
+never take another turn on its own, this reads as *permanently* stale from the outside — exactly
+the reported symptom. It resolves the moment the node's next turn posts a **verified** event, but
+nothing was telling the caller (or the human) that a turn is what it is waiting for, or that the
+identity itself is fine.
+
+### 3. `write` to a non-persistent native Windows PTY silently failed
+
+`src/core/pty-manager.ts`'s `sendText` (the `write` control verb, `/rename`, note-push, dictation
+— every internal writer, not just agent messaging) had three branches: SSH remote, session-host,
+tmux. A **direct** native Windows PTY (`Session.nativeWindowsPane` set, no `session.sshRemote`, no
+`session.sessionHost`, `this.tmuxPath` unset) fell into the `session-host` branch by the `!this.
+tmuxPath` condition, which calls `sessionHostSendKeys(target, …)` against a session-host session
+name that **does not exist** for a direct PTY — it always returned `false`. Every `write` to such a
+pane failed, unconditionally, which is the "write falhou" half of the report.
+
+## The fix
+
+### 1. Idle agent CLIs are now protected like `working`/`waiting`/`blocked`
+
+`src/renderer/terminal/live-work.ts`:
+- `LiveWorkInput` gained `agentProcess?: boolean` — "is an agent CLI believed to be running in
+ this pane, whatever its turn state" (line ~50).
+- `wouldKillLiveWork` (line 66) now returns `true` on `agentProcess` alone, before even looking at
+ `agentState`.
+- New `agentProcessInPane(agentId, status)` (line 77): true for any node with an `agentId` whose
+ status does **not** say `hibernated`/`paused`/`dropped` — those three are the CLI's own
+ documented "there is genuinely no process left to protect" states (Eco exit, manual pause, the
+ `dropped` liveness check), and only those three make the node reclaimable again.
+
+`src/renderer/terminal/park-budget.ts`: `ParkedEntryState` and `canDisposeParkedEntry` (line ~62)
+now carry/forward `agentProcess`, snapshotted at park time for the same reason
+`parkedAgentState` already is (the departure effect that parks a node also clears its live agent
+status on the same unmount).
+
+`src/renderer/nodes/TerminalNode.tsx`: a `readAgentProcessRef` alongside the existing
+`readAgentStateRef`, read into both the offscreen-release check and the park snapshot.
+
+**This is not Windows-gated.** It is the same shared predicate every platform's offscreen/park
+levers already call; on tmux it changes nothing observable (a tmux-backed session was never
+protected *or* endangered by this — killing the client there was always cheap, and now it is
+merely *also* not attempted for an idle agent, which costs one extra warm reattach where a plain
+terminal's would have been evicted). Reviewers on mac/Linux should still sanity-check this: it is
+shared code, and I only validated it on Windows.
+
+### 2. The mirror can now honestly clear the "no evidence yet" doubt for a resumed-and-idle CLI, and the decider tells the truth about what it is waiting for
+
+`src/core/agent-status-mirror.ts`:
+- `MirrorEntry.sessionStarted?: true` (line ~149) — "the current stateless entry was committed by
+ a **verified** `SessionStart` this run, and nothing has committed a state since." Not persisted
+ (`buildFile`'s allowlist untouched), cleared on every `commitState` (line ~467).
+- A verified Claude `idle_prompt` notification (`ev.idle === true`) arriving right after a
+ verified session start, with no state committed since, is now allowed to commit a **verified,
+ non-inferred** `done` (`idleAfterSessionStart`, line ~500-505; the extra `commitState` parameter,
+ line ~457-473). The reasoning: a CLI that has taken no turn since starting/resuming cannot be
+ holding a pending approval behind its prompt, so `idle_prompt`'s existing "rescue" mechanism
+ (already used to un-stick a node that ESC'd out of a tool call — see `normalize.ts`) is safe to
+ trust here in a way it is not safe to trust for an *arbitrary* `done` (which could be masking a
+ live approval).
+- **This depends on Claude actually firing a verified `idle_prompt` shortly after a resume with no
+ new turn — I have not confirmed that it does.** See "What was validated" below; this half of the
+ fix is unverified in practice.
+
+`src/core/agents/agent-message-decide.ts` (`identityRefusal`, line ~307-314): a node that **has**
+proven itself before (`e.verifiedAt` is a number) and is currently reset to `state === undefined`
+by a session boundary now reports `targetNotIdleUnknown` with `SESSION_BOUNDARY_REASON` ("the node
+crossed a session boundary … and has not reported a turn since") instead of `targetStatusStale`.
+A node that has **never** proven itself still gets `targetStatusStale` — that branch is unchanged,
+and correctly so: for that node the identity question really is still open.
+
+### 3. `write` now reaches a direct native Windows PTY
+
+`src/core/pty-manager.ts` (`sendText`, line ~4002) checks `live?.nativeWindowsPane` **before** the
+session-host/tmux branches and delegates to it.
+
+`src/core/native-windows-pane.ts` gained `sendText(text, enter)` (line ~73): frames the payload as
+a bracketed paste only when the pane has asked for one (same `paste-buffer -p` contract the tmux
+path already uses), writes it unframed otherwise, then an Enter if requested. Deliberately **no
+process attestation** here (unlike `sendEnvelope`, the agent-messaging delivery path) — `write`,
+`/rename`, note-push and dictation have always typed into whatever currently owns the pane, and
+adding an attestation here would be new, unrequested behavior for callers that never had one.
+
+## Packaging fix (independent of the three bugs above, but required to change the failure mode at all)
+
+The installed build had **no session-host at all** — `dist:win` never ran `host:build`, and
+`build.win` declared no `extraResources` for it, so every terminal on that install was, and always
+would be, a non-persistent direct native PTY. `package.json`:
+- `dist:win` now runs `npm run host:build` before `electron-builder`.
+- `build.win.extraResources` now ships `out/session-host/host.cjs` plus a filtered copy of
+ `node_modules/node-pty` (its `lib/**/*.js`, `package.json`, and the platform's built
+ `build/Release/*.node`/`.exe`/`.dll`) under `resources/session-host/node_modules/node-pty`.
+
+Without this, bug 1's fix is close to moot: an "idle agent CLI" protected by `agentProcess` is
+still a **direct** PTY tree, so protecting it from the memory levers only delays the same problem
+to whenever the app itself restarts/quits (which kills every direct PTY regardless — there is
+nothing underneath to survive that). With the session-host present, a normal app restart now
+reattaches instead of relaunching from a dead process (see "What was validated").
+
+## What was validated
+
+- `npm run typecheck` clean.
+- `npx vitest run` on every touched file's suite: clean except one pre-existing Windows-only
+ failure (`agent-status-mirror.test.ts`'s "writes the file with 0600 permissions" — POSIX file
+ mode does not apply on NTFS, unrelated to this change).
+- New/extended tests: `live-work.test.ts` (`agentProcessInPane`, the new protected case),
+ `park-budget.test.ts` (a parked idle-agent entry), `native-windows-pane.test.ts`
+ (`sendText` framing/Enter/disposed-pane cases), `agent-status-mirror.test.ts` (the
+ `sessionStarted`/idle-rescue state machine, four cases: verified rescue, unverified idle,
+ unverified session start, a state commit disarming the rescue), `agent-message-decide.test.ts`
+ (`targetNotIdleUnknown` for a proven node reset by a boundary vs. `targetStatusStale` for a
+ never-proven one).
+- `npm run dist:win` produced an installer whose `resources\session-host\host.cjs` and bundled
+ `node-pty` are present and load (smoke-tested: spawned the packaged host in an isolated
+ `userData`, confirmed it writes `session-host.json`, listens on its named pipe, and a packaged
+ `node-pty` opens a real ConPTY).
+- Installed on the local machine and restarted. Confirmed via the OS process tree that terminal
+ sessions are now children of the session-host process (not of `nodeterm.exe` directly) — the
+ packaging fix is in effect.
+- Confirmed hooks are alive post-restart (`PreToolUse`/`PostToolUse` posted normally for an
+ actively-working session within ~6 minutes of the restart).
+- Sent `send` to two cold-restored, not-yet-active nodes; both correctly returned
+ `targetStatusStale` (retryable) — this is the **expected, unchanged** branch (a node that has
+ posted nothing at all this run has no `verifiedAt` yet, so `SESSION_BOUNDARY_REASON` does not
+ apply; it applies only to a node reset *mid-run* after having proven itself).
+
+## What was NOT validated / open questions for the PR
+
+- **The `idleAfterSessionStart` rescue (part of fix 2) was not observed firing.** Two resumed
+ Claude sessions sat idle for 6+ minutes after the restart with no `SessionStart` posted at all
+ (not even the ordinary one, let alone the rescue's `idle_prompt`) — before either wrote to me
+ again, I did not confirm whether that stalls indefinitely or eventually posts. This may be
+ ordinary contention (five CLIs cold-starting at once on one machine) or may indicate the rescue
+ needs a different signal. **A reviewer should confirm on a clean run whether Claude Code
+ reliably fires a verified `idle_prompt` shortly after `--resume` with no new user turn** — if it
+ does not, this half of fix 2 does nothing observable and `targetNotIdleUnknown`'s honest wording
+ (fix 2's other half, which *was* validated) is what actually helps.
+- **The original multi-agent scenario (coordinator + architect + coder exchanging `send`/`reply`
+ across several deliveries) was not re-run end-to-end.** What was validated is each mechanism in
+ isolation (the protection predicate, the mirror state machine, the decider's wording, the write
+ path, the packaging). A full re-run of the original reproduction is the natural acceptance test
+ for a PR.
+- Fix 1 and fix 2 are **shared, cross-platform code** (`live-work.ts`, `park-budget.ts`,
+ `agent-status-mirror.ts`, `agent-message-decide.ts`) even though the bug was only reachable on
+ Windows today (mac/Linux always have tmux underneath). A PR should note this explicitly and get
+ eyes from whoever owns the tmux-path behavior, even though the intent is that nothing observable
+ changes there.
+- No attempt was made to explain **why the session-host process was absent** beyond "the packaging
+ never shipped it" — i.e., no investigation of whether some *other* running install ever had a
+ session-host, or whether this was true since the Windows session-host work landed. Worth a
+ changelog note if this repo tracks a "since which version were Windows sessions ever
+ persistent" fact.
+- This diff is **entirely uncommitted** on the machine it was written on. No branch, no commit, no
+ PR opened yet — that is intentionally left for whoever picks this up.
+
+## Files touched
+
+```
+CLAUDE.md
+CONTRIBUTING.md (no functional change noted beyond what CLAUDE.md documents)
+package.json
+src/core/agent-status-mirror.ts
+src/core/agent-status-mirror.test.ts
+src/core/agents/agent-message-decide.ts
+src/core/agents/agent-message-decide.test.ts
+src/core/native-windows-pane.ts
+src/core/native-windows-pane.test.ts
+src/core/pty-manager.ts
+src/renderer/nodes/TerminalNode.tsx
+src/renderer/terminal/live-work.ts
+src/renderer/terminal/live-work.test.ts
+src/renderer/terminal/park-budget.ts
+src/renderer/terminal/park-budget.test.ts
+```
+
+These are on top of a larger set of pre-existing local, uncommitted changes (the native Windows
+agent-messaging work `docs/windows-session-host.md`'s "Automated verification" section already
+describes — `session-host/message-pane.ts`, `windows-pane-owner.ts`, the `processBirths` field on
+`PaneOwner`, etc.). This document only covers the three bugs above and the packaging fix; it does
+not re-describe that pre-existing work.
diff --git a/package.json b/package.json
index f42539189..4f635fbdf 100644
--- a/package.json
+++ b/package.json
@@ -124,6 +124,27 @@
},
"win": {
"icon": "build/icon.ico",
+ "extraResources": [
+ {
+ "from": "out/session-host",
+ "to": "session-host",
+ "filter": [
+ "host.cjs"
+ ]
+ },
+ {
+ "from": "node_modules/node-pty",
+ "to": "session-host/node_modules/node-pty",
+ "filter": [
+ "package.json",
+ "lib/**/*.js",
+ "!lib/**/*.test.js",
+ "build/Release/*.node",
+ "build/Release/*.exe",
+ "build/Release/*.dll"
+ ]
+ }
+ ],
"target": [
{
"target": "nsis",
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.ts
index ba0a14c46..489128011 100644
--- a/src/core/agent-status-mirror.test.ts
+++ b/src/core/agent-status-mirror.test.ts
@@ -2063,6 +2063,48 @@ describe('reduceEntry records whether the state transition was verified', () =>
expect(b.verifiedAt).toBe(1000)
})
+ describe('idle rescue after a verified session start (resumed CLI idling at its prompt)', () => {
+ const started = (verified = true) =>
+ reduceEntry(
+ reduceEntry(undefined, ev({ state: 'done', verified: true }), 1000),
+ ev({ kind: 'session', sessionPhase: 'start', verified }),
+ 2000
+ )
+
+ it('a verified idle_prompt commits a verified, NON-inferred done', () => {
+ const c = reduceEntry(started(), ev({ state: 'done', idle: true, interrupted: true, verified: true }), 3000)
+ expect(c.state).toBe('done')
+ expect(c.stateVerified).toBe(true)
+ expect(c.idleInferred).toBeUndefined()
+ expect(c.sessionStarted).toBeUndefined()
+ })
+
+ it('an unverified idle_prompt is still ignored', () => {
+ const c = reduceEntry(started(), ev({ state: 'done', idle: true, verified: false }), 3000)
+ expect(c.state).toBeUndefined()
+ expect(c.stateVerified).toBe(false)
+ })
+
+ it('an unverified session start does not arm the rescue', () => {
+ const c = reduceEntry(started(false), ev({ state: 'done', idle: true, verified: true }), 3000)
+ expect(c.state).toBeUndefined()
+ })
+
+ it('a session END never arms the rescue', () => {
+ const a = reduceEntry(undefined, ev({ state: 'done', verified: true }), 1000)
+ const b = reduceEntry(a, ev({ kind: 'session', sessionPhase: 'end', verified: true }), 2000)
+ const c = reduceEntry(b, ev({ state: 'done', idle: true, verified: true }), 3000)
+ expect(c.state).toBeUndefined()
+ })
+
+ it('any state commit after the start disarms it (a turn may hold an approval)', () => {
+ const b = reduceEntry(started(), ev({ state: 'blocked', verified: true }), 2500)
+ expect(b.sessionStarted).toBeUndefined()
+ const c = reduceEntry(b, ev({ state: 'done', idle: true, verified: true }), 3000)
+ expect(c.state).toBe('blocked')
+ })
+ })
+
it('a session boundary drops the proof with the state it was about', () => {
// SessionStart/End reset the node to idle. A `stateVerified: true` left standing beside a
// state of `undefined` would assert proof about a state that no longer exists.
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index 95dcb5755..5147a2de7 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -138,6 +138,15 @@ export interface MirrorEntry {
* renderer re-reports its persisted set at boot, and a wake (or `clearNode`) drops the flag.
*/
hibernated?: true
+ /**
+ * The CURRENT stateless entry was committed by a VERIFIED `SessionStart` this run, and nothing
+ * has committed a state since. A CLI that has just started or resumed and taken no turn cannot
+ * be holding an approval, so its `idle_prompt` is allowed to commit a verified, non-inferred
+ * `done` (see `reduceEffectiveEntry`). Without that, a resumed CLI idling at its prompt was
+ * unmessageable forever: the boundary left it unverified and only a turn could re-verify it.
+ * Runtime-only (not in `buildFile`'s allowlist); cleared by every state commit.
+ */
+ sessionStarted?: true
}
/** This host's Server-Edition install metadata (spec: server-update). Written by the installer
@@ -445,16 +454,23 @@ function reduceEffectiveEntry(
* `proof` is the evidence for THIS transition, passed in rather than read off `ev` so the one
* caller that means something different has to say so out loud.
*/
- const commitState = (state: AgentState | undefined, proof: boolean): void => {
+ const commitState = (
+ state: AgentState | undefined,
+ proof: boolean,
+ idleAfterSessionStart = false
+ ): void => {
next.state = state
next.updatedAt = now
next.stateVerified = proof
if (proof) next.verifiedAt = now
next.clientRevision = ev.clientRevision
+ delete next.sessionStarted
// Which KIND of `done` this is, recorded on the same edge as the state itself. `idle` is only
// ever meaningful on a `done`; assigning (not merging) is the point — a later, genuine turn-end
// `done` must clear the marker, or a node would stay tainted for the rest of its session.
- if (state === 'done' && ev.idle) next.idleInferred = true
+ // The one idle `done` that is NOT inferred is the one right after a verified session start:
+ // no turn has run, so no approval can be pending behind the prompt (see `sessionStarted`).
+ if (state === 'done' && ev.idle && !idleAfterSessionStart) next.idleInferred = true
else delete next.idleInferred
// The entry's STATE now comes from this run, so it is no longer the one restored off disk.
// Cleared HERE and only here: an event that commits no state — a context/usage event, a
@@ -478,7 +494,15 @@ function reduceEffectiveEntry(
// An `idle` done (Claude went quiet at its prompt) is a RESCUE, not a turn end: it may only
// move a node that is still `working`. A node that is blocked/waiting is ALSO idle at the
// prompt — clearing it there would drop a live approval — and one already done needs nothing.
- if (ev.idle && prev?.state !== 'working') return next
+ // ONE exception: a verified idle right after a verified session start, with no state committed
+ // in between. A just-started or just-resumed CLI at its prompt is genuinely idle — and without
+ // this it stays unverified until a turn it can only get from a message it cannot receive.
+ const idleAfterSessionStart =
+ ev.idle === true &&
+ ev.verified === true &&
+ prev?.sessionStarted === true &&
+ prev.state === undefined
+ if (ev.idle && prev?.state !== 'working' && !idleAfterSessionStart) return next
// An unanswered Codex `request_user_input`: the ask arrives as waiting+awaitingInput and the
// turn's OWN Stop follows as `done` before the user answers (the ask ends the turn; the answer
// opens a new one). That done must not flip the node green over a live question — hold
@@ -509,7 +533,7 @@ function reduceEffectiveEntry(
// working did not change the state whose proof this describes. `clientRevision` is ASSIGNED
// rather than merged — an event with no stamp is a report that this node is running a script
// that cannot send one, which is exactly what a stale entry would hide.
- if (!heldOff) commitState(ev.state, ev.verified === true)
+ if (!heldOff) commitState(ev.state, ev.verified === true, idleAfterSessionStart)
} else if (ev.kind === 'session') {
// SessionStart / SessionEnd both reset the node to idle (renderer: setState(id, undefined)).
// The proof goes with the state it was about, and `false` is passed EXPLICITLY rather than
@@ -518,6 +542,9 @@ function reduceEffectiveEntry(
// and is what makes a refusal retryable.
commitState(undefined, false)
next.awaitingInput = undefined
+ // The boundary proves nothing about a state (and leaves `verifiedAt` alone), but a VERIFIED
+ // start arms the idle rescue above.
+ if (ev.sessionPhase === 'start' && ev.verified === true) next.sessionStarted = true
}
// subagent-start / subagent-end / recurring: identity captured above, main state untouched.
return next
diff --git a/src/core/agents/agent-message-decide.test.ts b/src/core/agents/agent-message-decide.test.ts
index 06ae3507a..aa728caae 100644
--- a/src/core/agents/agent-message-decide.test.ts
+++ b/src/core/agents/agent-message-decide.test.ts
@@ -8,6 +8,7 @@ import {
DECISION_ORDER,
RETRYABLE,
NO_TOKEN_FILE_NOTE,
+ SESSION_BOUNDARY_REASON,
type AgentMessageOutcomeKind,
type DeliveryFacts
} from './agent-message-decide'
@@ -167,6 +168,27 @@ describe('the THREE unverified refusals — Correction C1 + Finding F2', () => {
expect(retryable(o)).toBe(true)
})
+ it('a PROVEN node reset by a session boundary is between sessions, not stale', () => {
+ // Measured 2026-09-13: an idle architect was resumed (`SessionStart:resume`) with no turn after,
+ // and every send was refused as `targetStatusStale` — an identity accusation for a node whose
+ // identity was fine. The honest refusal is gate 2's.
+ const o = decideDelivery(
+ ready({
+ target: unverified({ state: undefined, verifiedAt: 900, clientRevision: MANAGED_SCRIPT_REVISION }),
+ tokenFilePresent: true
+ })
+ )
+ expect(o).toEqual({ kind: 'targetNotIdleUnknown', reason: SESSION_BOUNDARY_REASON })
+ expect(retryable(o)).toBe(true)
+ })
+
+ it('a node that has NEVER proven itself stays stale across a boundary', () => {
+ const o = decideDelivery(
+ ready({ target: unverified({ state: undefined, clientRevision: MANAGED_SCRIPT_REVISION }), tokenFilePresent: true })
+ )
+ expect(o.kind).toBe('targetStatusStale')
+ })
+
it('a current script with NO token file is not retryable and says what to do', () => {
const o = decideDelivery(
ready({ target: unverified({ clientRevision: MANAGED_SCRIPT_REVISION }), tokenFilePresent: false })
diff --git a/src/core/agents/agent-message-decide.ts b/src/core/agents/agent-message-decide.ts
index 104811c4d..f7692b133 100644
--- a/src/core/agents/agent-message-decide.ts
+++ b/src/core/agents/agent-message-decide.ts
@@ -302,9 +302,19 @@ function identityRefusal(
...(typeof e.clientRevision === 'number' ? { observedRevision: e.clientRevision } : {})
}
if (!f.tokenFilePresent) return { kind: 'targetStatusUnverified', note: NO_TOKEN_FILE_NOTE }
+ // A node that HAS proven itself and whose CLI then crossed a session boundary (started, resumed,
+ // ended) is not "stale" — it is between sessions, which is `idleRefusal`'s fact. Reporting it as
+ // `targetStatusStale` told the caller the identity was the problem, while the real fact is that
+ // no turn has been reported since the boundary.
+ if (observed && e.state === undefined && typeof e.verifiedAt === 'number')
+ return { kind: 'targetNotIdleUnknown', reason: SESSION_BOUNDARY_REASON }
return { kind: 'targetStatusStale' }
}
+export const SESSION_BOUNDARY_REASON =
+ 'the node crossed a session boundary (its CLI started, resumed or exited) and has not reported ' +
+ 'a turn since'
+
/**
* The gates that cost NOTHING to evaluate — decided before any pane is touched.
*
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 27b271eed..7ab654d45 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -75,6 +75,7 @@ import {
planParkEviction,
type ParkTimer
} from '../terminal/park-budget'
+import { agentProcessInPane } from '../terminal/live-work'
import {
mayDisposeOffscreen,
offscreenCoreIsRemote,
@@ -475,6 +476,8 @@ interface ParkedTerminal {
* lever reads later than that, so without this snapshot every park looks agent-less. See
* `effectiveAgentState`. */
parkedAgentState?: AgentState
+ /** An agent CLI was in the pane at park time — see `ParkedEntryState.agentProcess`. */
+ agentProcess: 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
@@ -506,6 +509,7 @@ function parkDisposable(key: string): boolean {
return canDisposeParkedEntry({
tmuxBacked: p.tmuxBacked,
parkedAgentState: p.parkedAgentState,
+ agentProcess: p.agentProcess,
parkedAt: p.parkedAt,
liveAgentState: p.readAgentState()
})
@@ -1490,6 +1494,14 @@ export function TerminalNode({
// offer this node's in-place restart from the SAME derivation, and a second copy drifting from
// this one yields a row whose closure refuses every click.
const agentId = createdAgentId(data)
+ /** Is an agent CLI believed to be running in this pane right now? The created agent, else one a
+ * hook event identified (a hand-launched CLI). Read through a ref by the release/park levers. */
+ const readAgentProcess = (): boolean => {
+ const st = agentStatusStore.getState().byId[id]
+ return agentProcessInPane(agentId ?? st?.agentId, st)
+ }
+ const readAgentProcessRef = useRef(readAgentProcess)
+ readAgentProcessRef.current = readAgentProcess
// Gate each former `isClaude` site by the capability it actually represents.
const showStatus = !!agentId && hasHooks(agentId) // status badge + session-title capture
const showLoop = !!agentId && canRecur(agentId) // /loop · /schedule · /cron chrome
@@ -4346,6 +4358,7 @@ export function TerminalNode({
// Snapshot NOW, because the departure effect declared below this one clears this node's
// agent status on this very unmount — every lever reads later and would see nothing.
parkedAgentState: readAgentState(),
+ agentProcess: readAgentProcessRef.current(),
parkedAt: Date.now(),
readAgentState,
cleanups,
@@ -4531,7 +4544,8 @@ export function TerminalNode({
if (
shouldDeferReleaseForLiveWork({
tmuxBacked: sessionPersistentRef.current,
- agentState: readAgentStateRef.current()
+ agentState: readAgentStateRef.current(),
+ agentProcess: readAgentProcessRef.current()
})
) {
// Re-stamp the offscreen clock: this node is not RELEASABLE yet, and the Eco
diff --git a/src/renderer/terminal/live-work.test.ts b/src/renderer/terminal/live-work.test.ts
index 3c10eddf0..dbba7d301 100644
--- a/src/renderer/terminal/live-work.test.ts
+++ b/src/renderer/terminal/live-work.test.ts
@@ -1,6 +1,11 @@
import { describe, it, expect } from 'vitest'
import { WORKING_STALE_MS } from '@shared/agents/stale'
-import { effectiveAgentState, parkedStateFloor, wouldKillLiveWork } from './live-work'
+import {
+ agentProcessInPane,
+ effectiveAgentState,
+ parkedStateFloor,
+ wouldKillLiveWork
+} from './live-work'
describe('wouldKillLiveWork', () => {
it('is true only for a NON-tmux session whose agent is working/waiting/blocked', () => {
@@ -18,6 +23,25 @@ describe('wouldKillLiveWork', () => {
expect(wouldKillLiveWork({ tmuxBacked: false, agentState: 'done' })).toBe(false)
expect(wouldKillLiveWork({ tmuxBacked: false })).toBe(false)
})
+ it('protects an IDLE agent CLI on a non-tmux pty — killing it forces a resume that strands messaging', () => {
+ for (const agentState of ['done', undefined] as const) {
+ expect(wouldKillLiveWork({ tmuxBacked: false, agentState, agentProcess: true })).toBe(true)
+ }
+ expect(wouldKillLiveWork({ tmuxBacked: true, agentState: 'done', agentProcess: true })).toBe(false)
+ })
+})
+
+describe('agentProcessInPane', () => {
+ it('is true for an agent node whose CLI we have not exited or seen die', () => {
+ expect(agentProcessInPane('claude', undefined)).toBe(true)
+ expect(agentProcessInPane('claude', {})).toBe(true)
+ })
+ it('is false with no agent, or once the pane holds only a shell', () => {
+ expect(agentProcessInPane(undefined, undefined)).toBe(false)
+ expect(agentProcessInPane('claude', { hibernated: true })).toBe(false)
+ expect(agentProcessInPane('claude', { paused: true })).toBe(false)
+ expect(agentProcessInPane('claude', { dropped: true })).toBe(false)
+ })
})
describe('effectiveAgentState — the snapshot FLOOR under a live store read', () => {
diff --git a/src/renderer/terminal/live-work.ts b/src/renderer/terminal/live-work.ts
index f8f09631a..c0c59b0cd 100644
--- a/src/renderer/terminal/live-work.ts
+++ b/src/renderer/terminal/live-work.ts
@@ -18,8 +18,8 @@
* The predicate is deliberately the NARROWEST one that closes the bug: it takes both halves, and
* either half alone leaves today's behavior untouched. A tmux-backed session is never protected
* (the kill costs a redraw, and protecting it would forfeit real memory on the setups where
- * reclaiming it is free); a plain terminal, a finished agent and an unknown state are never
- * protected either (nothing is running to lose).
+ * reclaiming it is free); a plain terminal is never protected either. An agent CLI still running
+ * in the pane IS protected even when idle (`agentProcess`) — see `wouldKillLiveWork`.
*/
import { WORKING_STALE_MS } from '@shared/agents/stale'
import type { AgentState } from '@shared/agents/normalize'
@@ -45,11 +45,40 @@ export interface LiveWorkInput {
/** The node's live agent state (`agentStatus.byId[nodeId].state`); absent = a plain terminal, or
* no hook event seen for it yet. */
agentState?: AgentState
+ /**
+ * Is an agent CLI believed to be running in this pane, whatever its turn state
+ * (`agentProcessInPane`)? Absent = not known, which keeps the state-only rule.
+ */
+ agentProcess?: boolean
}
-/** Would tearing down this terminal's PTY client destroy work that is still running? */
+/**
+ * Would tearing down this terminal's PTY client destroy work that is still running?
+ *
+ * On a non-persistent pty an IDLE agent is live work too. The CLI process is the conversation's
+ * only live holder: killing it and letting cold restore `--resume` it on revive looks harmless, but
+ * the resumed CLI fires `SessionStart:resume` and then sits at its prompt emitting nothing. The
+ * status mirror commits that boundary as unverified-and-stateless, so agent messaging refuses the
+ * node (`targetStatusStale`) for as long as it stays idle — and only a message could end the idle.
+ * Measured 2026-09-13 on Windows native ptys: an architect node idle at 12:39, resumed at 13:13 with
+ * no user turn, refused every send at 15:28 while its terminal showed Claude at the prompt.
+ */
export function wouldKillLiveWork(i: LiveWorkInput): boolean {
- return !i.tmuxBacked && !!i.agentState && LIVE_AGENT_STATES.has(i.agentState)
+ if (i.tmuxBacked) return false
+ if (i.agentProcess) return true
+ return !!i.agentState && LIVE_AGENT_STATES.has(i.agentState)
+}
+
+/**
+ * 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.
+ */
+export function agentProcessInPane(
+ agentId: string | undefined,
+ status: { hibernated?: boolean; paused?: boolean; dropped?: boolean } | undefined
+): boolean {
+ return !!agentId && status?.hibernated !== true && status?.paused !== true && status?.dropped !== true
}
/**
diff --git a/src/renderer/terminal/park-budget.test.ts b/src/renderer/terminal/park-budget.test.ts
index 87c4cefb8..cb29358d2 100644
--- a/src/renderer/terminal/park-budget.test.ts
+++ b/src/renderer/terminal/park-budget.test.ts
@@ -145,6 +145,13 @@ describe('a parked plain-shell agent survives the departure clear (#126)', () =>
expect(canDisposeParkedEntry(working, parkedAt + WORKING_STALE_MS + 1)).toBe(true)
})
+ it('protects a park whose pane held an idle agent CLI on a non-tmux pty', () => {
+ const idleAgent: ParkedEntryState = { tmuxBacked: false, parkedAgentState: 'done', parkedAt, agentProcess: true }
+ expect(canDisposeParkedEntry(idleAgent, parkedAt + 10 * WORKING_STALE_MS)).toBe(false)
+ expect(canDisposeParkedEntry({ ...idleAgent, tmuxBacked: true })).toBe(true)
+ expect(canDisposeParkedEntry({ ...idleAgent, agentProcess: false })).toBe(true)
+ })
+
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 c3b79c8aa..c83468237 100644
--- a/src/renderer/terminal/park-budget.ts
+++ b/src/renderer/terminal/park-budget.ts
@@ -67,6 +67,9 @@ export interface ParkedEntryState {
parkedAt?: number
/** The node's agent state RIGHT NOW, read from that node's own agent-status store. */
liveAgentState?: AgentState
+ /** 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
}
/** `canDisposePark` for a park entry: the live read, with the AGED park-time snapshot under it.
@@ -76,6 +79,7 @@ export interface ParkedEntryState {
export function canDisposeParkedEntry(e: ParkedEntryState, now: number = Date.now()): boolean {
return canDisposePark({
tmuxBacked: e.tmuxBacked,
+ agentProcess: e.agentProcess,
agentState: effectiveAgentState(
e.liveAgentState,
parkedStateFloor(e.parkedAgentState, e.parkedAt, now)