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(eco): prove the agent owns the pane before quitting it, and re-check that pane on wake

enesc81543548488
diff --git a/src/core/pty-manager-platform.test.ts b/src/core/pty-manager-platform.test.ts
index c4f9eec2f..eb7bc43cf 100644
--- a/src/core/pty-manager-platform.test.ts
+++ b/src/core/pty-manager-platform.test.ts
@@ -22,7 +22,12 @@ describe('PtyManager platform registration', () => {
IPC.ptyKill,
IPC.ptyDestroy,
IPC.ptySendText,
- IPC.ptyReadScrollback
+ IPC.ptyReadScrollback,
+ // Registered in core, so BOTH shells serve it. That placement is the point: the hibernation
+ // exit fails CLOSED on a pane it cannot read, so a channel that reached only the desktop
+ // would have switched Eco off for the whole Server Edition — silently, and looking exactly
+ // like "Eco just never fires here". See wake-identity.ts / issue #823.
+ IPC.ptyPaneOwner
]) {
// ptyKill is sender-aware (co-attach: unsubscribe ONE client) → senderListeners.
expect(fake.handlers[ch] ?? fake.listeners[ch] ?? fake.senderListeners[ch], ch).toBeDefined()
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 97d927ef3..f2651bb85 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -1773,6 +1773,9 @@ export class PtyManager {
)
platform().handle(IPC.ptyTmuxStatus, () => this.tmuxStatus())
platform().handle(IPC.ptyPaneCommand, (persistKey: string) => this.paneCommand(persistKey))
+ // Registered HERE, beside its name-only sibling, rather than in either shell: core owns both
+ // reads, so the desktop and the Server Edition are served by one line and cannot drift.
+ platform().handle(IPC.ptyPaneOwner, (persistKey: string) => this.paneOwner(persistKey))
platform().handle(IPC.ptyTerminateForeground, (persistKey: string, expectedAgentId?: string) =>
this.terminateForeground(persistKey, expectedAgentId)
)
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 3b7207706..783e4a763 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -98,6 +98,7 @@ const api: NodeTerminalApi = {
ipcRenderer.invoke(IPC.ptySendText, persistKey, text, opts?.enter),
tmuxStatus: () => ipcRenderer.invoke(IPC.ptyTmuxStatus),
paneCommand: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneCommand, persistKey),
+ paneOwner: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneOwner, persistKey),
terminateForeground: (persistKey, expectedAgentId) =>
ipcRenderer.invoke(IPC.ptyTerminateForeground, persistKey, expectedAgentId),
readSessionName: (sessionId, accountId, agentId) =>
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index c00685c80..5501c1dc6 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -58,6 +58,7 @@ import {
type WorkspaceApi
} from '../../shared/types'
import type { PeerIdentity } from '../../shared/presence'
+import type { PaneOwner } from '../../shared/agents/pane-owner-predicate'
import { buildStubApi } from './stubs'
import { mountPickerRoot, openDirectoryPicker } from './dialog-picker'
import { encodePcmForWire } from './speech-encode'
@@ -265,6 +266,11 @@ export function buildRealApi(
// shell yet" and gives up on its own deadline.
paneCommand: (persistKey) =>
client.request(IPC.ptyPaneCommand, persistKey).catch(() => null) as Promise<string | null>,
+ // A REAL implementation, not a stub: core registers the handler, so the server this browser is
+ // served from answers it. The hibernation exit fails CLOSED on a null, so a stub here would
+ // have silently switched Eco off for the whole Server Edition rather than degrade it.
+ paneOwner: (persistKey) =>
+ client.request(IPC.ptyPaneOwner, persistKey).catch(() => null) as Promise<PaneOwner | null>,
terminateForeground: (persistKey, expectedAgentId) =>
client.request(IPC.ptyTerminateForeground, persistKey, expectedAgentId).catch(() => false) as Promise<boolean>,
// No server handler — the session-name poll degrades to no adopted name. A PRE-EXISTING gap,
diff --git a/src/renderer/lib/hibernationCandidates.test.ts b/src/renderer/lib/hibernationCandidates.test.ts
index a2d720d44..0b3d1810d 100644
--- a/src/renderer/lib/hibernationCandidates.test.ts
+++ b/src/renderer/lib/hibernationCandidates.test.ts
@@ -33,11 +33,32 @@ describe('buildHibernationCandidates', () => {
recurring: false,
liveSubagents: false,
liveBackgroundTask: false,
+ paneUnverified: false,
lastEventAt: IDLE
}
])
})
+ it('lifts `paneUnverified` — the plan needs it, and an omitted field would read as eligible', () => {
+ // The flag the exit sets when the kernel says no agent owns this node's pane (issue #823).
+ // It is a PLAN-time exclusion, so it has to survive this adapter: dropped here, a node that
+ // can never be exited would hold a batch slot on every sweep for the rest of the run.
+ const rows = buildHibernationCandidates(
+ inputs({
+ nodes: [
+ { id: 'a', agentId: 'claude' },
+ { id: 'b', agentId: 'claude' }
+ ],
+ statusById: {
+ a: { state: 'done', sessionId: 'sid-a', lastEventAt: IDLE },
+ b: { state: 'done', sessionId: 'sid-b', lastEventAt: IDLE, paneUnverified: true }
+ }
+ })
+ )
+ expect(rows.map((r) => r.paneUnverified)).toEqual([false, true])
+ expect(planHibernation(rows, NOW, { enabled: true, idleMinutes: 30 })).toEqual(['a'])
+ })
+
it('liveBackgroundTask mirrors backgroundTaskAt presence', () => {
const rows = buildHibernationCandidates(
inputs({
diff --git a/src/renderer/lib/hibernationCandidates.ts b/src/renderer/lib/hibernationCandidates.ts
index f9c71c5dd..e8e2e43de 100644
--- a/src/renderer/lib/hibernationCandidates.ts
+++ b/src/renderer/lib/hibernationCandidates.ts
@@ -52,6 +52,8 @@ export interface HibernationStatusInput {
/** When this node last launched a background shell task, if no turn has started since — the
* third safety fact this adapter exists for (see the header). Present at all = live task. */
backgroundTaskAt?: number
+ /** The last exit attempt found no agent in this pane — see the policy's `paneUnverified`. */
+ paneUnverified?: boolean
}
/** One subagent card, narrowed: whose it is, and whether it has finished. */
@@ -97,6 +99,7 @@ export function buildHibernationCandidates(
recurring: !!st?.loop,
liveSubagents: liveParents.has(n.id),
liveBackgroundTask: st?.backgroundTaskAt !== undefined,
+ paneUnverified: !!st?.paneUnverified,
lastEventAt: st?.lastEventAt
}
})
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 27b271eed..ffb0ff4cc 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -118,6 +118,15 @@ import {
resumeSessionMissing
} from '../terminal/resume-fallback'
import { MAX_LAUNCH_LINE_BYTES, lineBytes } from '@shared/canonical-line'
+import { binariesFor, type PaneOwner } from '@shared/agents/pane-owner-predicate'
+import {
+ captureWakeContext,
+ decideHibernateExit,
+ decideWakeResume,
+ wakeRefusalReason,
+ wakeVerdictIsTransient,
+ type WakeVerdict
+} from '../terminal/wake-identity'
import {
agentHibernateFns,
exitSequence,
@@ -1692,6 +1701,14 @@ export function TerminalNode({
// 'not-eligible' — usually timing, not a refusal that will stand: at mount the spawn is
// still in flight (no session id yet), and right after a reveal tmux may not have answered
// `paneCommand` yet. See `retryLater`.
+ //
+ // …unless the resume half wrote a REASON. That is its standing refusals only (the pane
+ // belongs to something else now, or the record predates the proof) — the transient one
+ // leaves the field null on purpose. Retrying a standing refusal only burns the attempts
+ // that the genuinely-transient cases need, and re-asks a question whose answer cannot
+ // change without the user doing something. The chip carries the sentence; its click is
+ // the way forward, and it re-checks.
+ if (useAgentStatus.getState().byId[id]?.wakeBlocked) return
retryLater()
})
.catch(() => {
@@ -2024,6 +2041,40 @@ export function TerminalNode({
const container = bodyRef.current
if (!container) return
+ /**
+ * Kernel truth about this node's pane, within the same budget the pane-command polls use.
+ *
+ * One `display-message` plus one `ps` locally (one ControlMaster exec channel for a remote
+ * pane), and it is asked at most twice per hibernation — once before the exit, once after it —
+ * for at most `HIBERNATE_BATCH_MAX` nodes a sweep. It is deliberately NOT on any timer: the
+ * question it answers is only meaningful at the instant something is about to be written.
+ *
+ * `null` on anything that is not a clean answer, including the deadline: every caller treats
+ * that as "we cannot see this pane", which is a refusal on both sides of the pair.
+ */
+ const readPaneOwner = async (): Promise<PaneOwner | null> => {
+ let lapse: ReturnType<typeof setTimeout> | undefined
+ try {
+ return await Promise.race([
+ api.pty.paneOwner(id),
+ new Promise<null>((r) => {
+ lapse = setTimeout(() => r(null), RESTART_EXIT_TIMEOUT_MS)
+ })
+ ])
+ } catch {
+ return null
+ } finally {
+ clearTimeout(lapse)
+ }
+ }
+ /** The binary names this node's agent actually runs as. Passed explicitly so a CUSTOM agent is
+ * verifiable from its own launch command — without it `binariesFor` cannot name a
+ * `custom:<uuid>` and answers `unknown`, which here is a refusal, i.e. Eco silently off for
+ * every custom agent on the canvas. */
+ const paneBinaries = (): readonly string[] | null =>
+ agentId ? binariesFor(agentId, useSettings.getState().settings.customAgents) : null
+
+
// Adopt-or-create: a parked terminal (this node unmounted less than TERM_PARK_MS ago) is
// re-adopted with its live PTY session and full xterm state intact; otherwise a fresh
// xterm + session are built. `myNonce` vs the render-updated ref tells the cleanup below
@@ -3646,15 +3697,17 @@ export function TerminalNode({
// The auto-resume above was skipped (that's the feature), but this mount's PANE is
// brand new either way — tmux respawned it, whether from the deep "pause & end session"
// recycle or from a genuine reboot that took a shallow-paused session's tmux with it.
- // The later Resume's pane-recognition (`isShellCommand(pane)` OR the recorded
- // `hibernatedPane` — see performExitPhase's wake half) would otherwise refuse a user
- // whose default shell sits outside the `isShellCommand` allowlist (nu/xonsh/pwsh)
+ // The later Resume's pane-recognition (see `decideWakeResume`) would otherwise refuse a
+ // user whose default shell sits outside the `isShellCommand` allowlist (nu/xonsh/pwsh)
// forever: a PAUSED chip that can never resume, with a live conversation on disk. Record
// what this fresh pane actually is, the same way the exit half does — replacing any
- // stale value a pre-reboot shallow pause left behind, which described a pane that no
+ // stale record a pre-reboot shallow pause left behind, which described a pane that no
// longer exists.
- const settled = await queryPaneWithin(() => api.pty.paneCommand(id), RESTART_EXIT_TIMEOUT_MS)
- useAgentStatus.getState().setHibernatedPane(id, settled)
+ //
+ // No ownership gate here, and none is owed: nothing is being QUIT: this pane was just
+ // respawned by tmux and holds a brand-new shell, which is the context the later resume
+ // is meant to launch into. The gate belongs where an exit is written.
+ useAgentStatus.getState().setHibernatedContext(id, captureWakeContext(await readPaneOwner()))
}
})
.catch((err: unknown) => {
@@ -3925,6 +3978,28 @@ export function TerminalNode({
// permission prompt ANSWERS it).
const gate = restartEligibility(agentId, st?.state, agentSessionId)
if (!gate.ok || !agentId || !agentSessionId || !restartTarget()) return 'not-eligible'
+ // ── IS THE CLI ACTUALLY IN THIS PANE? (issue #823) ──────────────────────────────────────
+ // Everything above asks about the node's STATE; this asks about the pane, and it is the
+ // only question that makes "resume it where we exited it" a promise we can keep. `done`
+ // is a memory of the last hook event, and hooks arrive over a reverse tunnel from wherever
+ // the agent actually runs: a node whose agent was reached over an interactive `ssh` that
+ // has since died still reads `done`, and its pane is now the LOCAL login shell. Exiting it
+ // types `/exit` into that shell, records it as SLEEPING, and hands the later wake a pane
+ // in which the remote session id cannot resolve — which is exactly the reported bug.
+ //
+ // `isAgentPane` (via `decideHibernateExit`) answers from the kernel's foreground process
+ // group, so it sees through both disguises the name-based read cannot: `node` for every
+ // npm-installed CLI, and `ssh` for an agent on another machine. Refusing costs one sweep;
+ // being wrong costs a conversation.
+ const exitVerdict = decideHibernateExit(await readPaneOwner(), agentId, paneBinaries())
+ if (exitVerdict !== 'agent-owns-pane') {
+ // Only the TERMINAL verdict is recorded. `'unreadable'` is a probe that failed (no tmux,
+ // a pane mid-teardown, a lapsed deadline) and the next sweep re-asks; latching it would
+ // drop the node out of the plan for the rest of the run on no evidence at all.
+ useAgentStatus.getState().setPaneUnverified(id, exitVerdict === 'not-in-this-pane')
+ return 'not-eligible'
+ }
+ useAgentStatus.getState().setPaneUnverified(id, false)
const outcome = await performExitPhase({
agentId,
sessionId: agentSessionId,
@@ -3933,19 +4008,19 @@ export function TerminalNode({
isLive: restartTarget
})
if (outcome === 'exited') {
- // Remember WHAT the pane settled to. The wake will only type into a pane it recognizes,
- // and its `isShellCommand` allowlist does not know `nu`, `xonsh` or `pwsh` — while the
- // exit half accepts those through its allowlist-free "the command stopped being the CLI"
- // signal. Without this record the wake is STRICTER than the exit that produced it, and
- // such a user is hibernated and then never woken: the chip refuses forever.
- // One extra poll rather than a value out of `performExitPhase`, whose behavior is pinned
+ // Remember the pane we exited INTO — the proof the wake spends. It carries the command
+ // (the wake's recognition allowlist does not know `nu`, `xonsh` or `pwsh`, while the exit
+ // half accepts those through its allowlist-free "the command stopped being the CLI"
+ // signal, so without it the wake would be STRICTER than the exit that produced it and
+ // such a user would be hibernated and never woken) AND the pane's own identity, so a
+ // record cannot authorise a write into a pane it never described.
+ //
+ // One extra read rather than a value out of `performExitPhase`, whose behavior is pinned
// byte-for-byte by Task 8's tests. `null` (a pane we could not read) FORGETS the old
- // value: a stale string must never stand in as permission to type into today's pane.
- const settled = await queryPaneWithin(
- () => api.pty.paneCommand(id),
- RESTART_EXIT_TIMEOUT_MS
- )
- useAgentStatus.getState().setHibernatedPane(id, settled)
+ // record: absent is refused, and that is the correct answer for an exit whose landing we
+ // did not witness. A stale record must never stand in as permission to type into today's
+ // pane.
+ useAgentStatus.getState().setHibernatedContext(id, captureWakeContext(await readPaneOwner()))
}
return outcome
}),
@@ -3997,15 +4072,34 @@ export function TerminalNode({
// resume, and the pane is a REPL the user can type into: by now it may belong to vim, to
// `top`, or to a claude the user launched by hand — and a launch line typed into a live
// program is sent to that program, as a message or a mangled command. A pane we cannot
- // READ answers null and is refused for the same reason.
+ // READ is refused for the same reason.
+ //
+ // What this asks is not "is a shell here?" but "is this the pane we exited the CLI in?".
+ // The difference is the whole of issue #823: a name-based read cannot tell the local login
+ // shell that an agent's `ssh` died back to apart from the shell that agent would have left
+ // behind, so it typed the resume into the wrong machine. The proof travels with the
+ // hibernation record instead, taken at the exit while the difference was still visible
+ // (`decideHibernateExit`), and this is where it is spent. See wake-identity.ts for the
+ // measurements and for why a node with no proof — every node hibernated by the build that
+ // shipped the bug — is refused rather than guessed at.
//
- // Two ways to recognize it, mirroring the exit half's two: a KNOWN shell, or the exact
- // command this node's own exit measured the pane settling to (`hibernatedPane`). The
- // second is what keeps a `nu` / `xonsh` / `pwsh` user — whom the exit accepts through its
- // allowlist-free signal — from being hibernated and never woken.
- const pane = await queryPaneWithin(() => api.pty.paneCommand(id), RESTART_EXIT_TIMEOUT_MS)
- const settled = useAgentStatus.getState().byId[id]?.hibernatedPane
- if (!isShellCommand(pane) && !(pane !== null && pane === settled)) return 'not-eligible'
+ // `exitedByUs` splits the two wake families: a deep "pause & end session" RECYCLES the tmux
+ // session and a `dropped` node's CLI died on its own, so neither has a pane of ours to
+ // match; both keep exactly the shell recognition they have today, and both gain the
+ // agent-running refusal they did not.
+ const stWake = useAgentStatus.getState().byId[id]
+ const verdict: WakeVerdict = decideWakeResume({
+ owner: await readPaneOwner(),
+ recorded: stWake?.hibernatedContext,
+ exitedByUs: !!stWake?.hibernated,
+ agentId,
+ binaries: paneBinaries()
+ })
+ // Always written, so a refusal that has since been fixed does not leave a stale sentence on
+ // the chip. `null` for `'resume'` and for the transient `'unreadable'` — the latter is
+ // timing, and the trigger's bounded retry (which reads this field) owns it.
+ useAgentStatus.getState().setWakeBlocked(id, wakeRefusalReason(verdict))
+ if (verdict !== 'resume') return 'not-eligible'
// Clear the line before the launch line goes in. The shell above is the one WE exited to,
// hours ago — nothing stops a passer-by (or a stray paste, or the user's own aborted
// command) from having left a half-typed line at its prompt, and `deliverCommand`'s first
@@ -4054,6 +4148,20 @@ export function TerminalNode({
// real command — junk output, and it would eat any half-typed line the user left there.
// Skip straight to marking (and, if deep, recycling) — there is nothing left to exit.
const alreadyExited = !!st?.hibernated
+ // The same pane-ownership question Eco's exit asks, and for the same reason: a manual pause
+ // ends in the same SLEEPING record and the same much-later wake, so a pause whose CLI is
+ // not in this pane would leave behind the exact record #823 is about. Skipped when the pane
+ // was ALREADY exited by us — there is no agent to find, and `alreadyExited` is precisely the
+ // case where that is expected rather than suspicious.
+ //
+ // Unlike the sweep this refusal is NOT latched into `paneUnverified`: that flag exists to
+ // keep a node out of the automatic plan, and a user who presses Pause is entitled to press
+ // it again. They get the ordinary `'not-eligible'`, which the menu already has wording for.
+ if (
+ !alreadyExited &&
+ decideHibernateExit(await readPaneOwner(), agentId, paneBinaries()) !== 'agent-owns-pane'
+ )
+ return 'not-eligible'
const outcome = alreadyExited
? 'exited'
: await performExitPhase({
@@ -4083,8 +4191,7 @@ export function TerminalNode({
// it so the SLEEPING machinery (pane-recognition on wake) still applies — plus `paused`,
// which is the only thing that changes: no auto-wake on reveal, and no auto-resume should
// the tmux session itself later die and come back `fresh` (a reboot, e.g.).
- const settled = await queryPaneWithin(() => api.pty.paneCommand(id), RESTART_EXIT_TIMEOUT_MS)
- useAgentStatus.getState().setHibernatedPane(id, settled)
+ useAgentStatus.getState().setHibernatedContext(id, captureWakeContext(await readPaneOwner()))
useAgentStatus.getState().setHibernated(id, true)
useAgentStatus.getState().setPaused(id, true)
}
@@ -5344,15 +5451,24 @@ export function TerminalNode({
) : (
status?.hibernated && (
<button
- className="term-node__status term-node__status--sleeping nodrag"
- title="Agent hibernated to save memory — click to resume"
+ className={
+ 'term-node__status term-node__status--sleeping nodrag' +
+ (status.wakeBlocked ? ' term-node__status--wake-blocked' : '')
+ }
+ /* A refused wake used to be visible only as whatever the pane said afterwards — in
+ the reported case, claude's own red "No conversation found" in a shell the user
+ never asked to be typed into. The node believed it had woken. Now the refusal has
+ a sentence, and it lives on the chip that is already the way back: still clickable,
+ because a re-check is exactly what the user wants once they have fixed the pane
+ (ssh'd back in, quit whatever took it over). */
+ title={status.wakeBlocked ?? 'Agent hibernated to save memory — click to resume'}
onClick={(e) => {
e.stopPropagation()
wakeRef.current()
}}
>
<span className="term-node__status-dot" />
- SLEEPING
+ {status.wakeBlocked ? 'SLEEPING — NOT RESUMED' : 'SLEEPING'}
</button>
)
)}
diff --git a/src/renderer/state/agentStatus.persist.test.ts b/src/renderer/state/agentStatus.persist.test.ts
index 50ebfb931..5713736e7 100644
--- a/src/renderer/state/agentStatus.persist.test.ts
+++ b/src/renderer/state/agentStatus.persist.test.ts
@@ -96,41 +96,40 @@ describe('loop persistence (cron/schedule survive an app restart)', () => {
expect(Date.now() - st.lastEventAt!).toBeLessThan(5000) // hours-old clock replaced
})
- it('persists `hibernatedPane` with the flag and drops it on wake', async () => {
- // What the pane settled to when the CLI let go: the wake's second way of recognizing a pane it
- // may type into, for shells the `isShellCommand` allowlist does not know (nu/xonsh/pwsh).
- // Kept past a wake it would be a standing permission to type into whatever that string names.
+ it('persists `hibernatedContext` with the flag and drops it on wake', async () => {
+ // The pane the CLI let go of: what the wake re-checks before it types a launch line. Kept past
+ // a wake it would be a standing permission to type into whatever that record names.
const store = memStorage()
vi.stubGlobal('localStorage', store)
const { useAgentStatus } = await import('./agentStatus')
- useAgentStatus.getState().setHibernatedPane('n15', 'nu')
+ useAgentStatus.getState().setHibernatedContext('n15', { command: 'nu', panePid: 7, paneId: '%3' })
useAgentStatus.getState().setHibernated('n15', true)
expect(JSON.parse(store.getItem('nodeterm.agentStatus')!).n15).toMatchObject({
hibernated: true,
- hibernatedPane: 'nu'
+ hibernatedContext: { command: 'nu', panePid: 7, paneId: '%3' }
})
useAgentStatus.getState().setHibernated('n15', false)
- expect(useAgentStatus.getState().byId['n15'].hibernatedPane).toBeUndefined()
- expect(JSON.parse(store.getItem('nodeterm.agentStatus')!).n15?.hibernatedPane).toBeUndefined()
+ expect(useAgentStatus.getState().byId['n15'].hibernatedContext).toBeUndefined()
+ expect(JSON.parse(store.getItem('nodeterm.agentStatus')!).n15?.hibernatedContext).toBeUndefined()
})
it('forgets the recorded pane when the exit could not read one (null)', async () => {
vi.stubGlobal('localStorage', memStorage())
const { useAgentStatus } = await import('./agentStatus')
- useAgentStatus.getState().setHibernatedPane('n16', 'nu')
- useAgentStatus.getState().setHibernatedPane('n16', null)
- // A stale string must never stand in as permission to type into TODAY's pane.
- expect(useAgentStatus.getState().byId['n16'].hibernatedPane).toBeUndefined()
+ useAgentStatus.getState().setHibernatedContext('n16', { command: 'nu', panePid: 7 })
+ useAgentStatus.getState().setHibernatedContext('n16', null)
+ // A stale record must never stand in as permission to type into TODAY's pane.
+ expect(useAgentStatus.getState().byId['n16'].hibernatedContext).toBeUndefined()
})
- it('drops `hibernatedPane` with the flag on the live-state self-heal', async () => {
+ it('drops `hibernatedContext` with the flag on the live-state self-heal', async () => {
vi.stubGlobal('localStorage', memStorage())
const { useAgentStatus } = await import('./agentStatus')
- useAgentStatus.getState().setHibernatedPane('n17', 'nu')
+ useAgentStatus.getState().setHibernatedContext('n17', { command: 'nu', panePid: 7 })
useAgentStatus.getState().setHibernated('n17', true)
useAgentStatus.getState().setState('n17', 'working', 'claude')
expect(useAgentStatus.getState().byId['n17'].hibernated).toBeUndefined()
- expect(useAgentStatus.getState().byId['n17'].hibernatedPane).toBeUndefined()
+ expect(useAgentStatus.getState().byId['n17'].hibernatedContext).toBeUndefined()
})
it('never restores a recorded pane without the flag it belongs to', async () => {
@@ -138,12 +137,12 @@ describe('loop persistence (cron/schedule survive an app restart)', () => {
'localStorage',
memStorage({
'nodeterm.agentStatus': JSON.stringify({
- n18: { unread: false, sessionId: 's', hibernatedPane: 'nu' }
+ n18: { unread: false, sessionId: 's', hibernatedContext: { command: 'nu', panePid: 7 } }
})
})
)
const { useAgentStatus } = await import('./agentStatus')
- expect(useAgentStatus.getState().byId['n18'].hibernatedPane).toBeUndefined()
+ expect(useAgentStatus.getState().byId['n18'].hibernatedContext).toBeUndefined()
})
it('setHibernated(false) on a node that is not hibernated changes NOTHING', async () => {
@@ -193,45 +192,48 @@ describe('loop persistence (cron/schedule survive an app restart)', () => {
expect(saved.hibernated).toBeUndefined()
})
- it('persists `hibernatedPane` for a PAUSED node even with `hibernated` unset — the deep pause records what its recycled pane settled to, and needs the record to survive a restart just as `paused` does', async () => {
+ it('persists `hibernatedContext` for a PAUSED node even with `hibernated` unset — the deep pause records what its recycled pane settled to, and needs the record to survive a restart just as `paused` does', async () => {
const store = memStorage()
vi.stubGlobal('localStorage', store)
const { useAgentStatus } = await import('./agentStatus')
useAgentStatus.getState().setPaused('n26', true)
- useAgentStatus.getState().setHibernatedPane('n26', 'nu')
+ useAgentStatus.getState().setHibernatedContext('n26', { command: 'nu', panePid: 7 })
const saved = JSON.parse(store.getItem('nodeterm.agentStatus')!).n26
- expect(saved).toMatchObject({ paused: true, hibernatedPane: 'nu' })
+ expect(saved).toMatchObject({ paused: true, hibernatedContext: { command: 'nu', panePid: 7 } })
expect(saved.hibernated).toBeUndefined()
})
- it('restores `hibernatedPane` on load for a paused (not hibernated) node', async () => {
+ it('restores `hibernatedContext` on load for a paused (not hibernated) node', async () => {
vi.stubGlobal(
'localStorage',
memStorage({
'nodeterm.agentStatus': JSON.stringify({
- n27: { unread: false, sessionId: 's', paused: true, hibernatedPane: 'nu' }
+ n27: { unread: false, sessionId: 's', paused: true, hibernatedContext: { command: 'nu', panePid: 7 } }
})
})
)
const { useAgentStatus } = await import('./agentStatus')
- expect(useAgentStatus.getState().byId['n27']).toMatchObject({ paused: true, hibernatedPane: 'nu' })
+ expect(useAgentStatus.getState().byId['n27']).toMatchObject({
+ paused: true,
+ hibernatedContext: { command: 'nu', panePid: 7 }
+ })
})
- it('setPaused(false) drops `hibernatedPane` when it was the only owner, but leaves it standing for `hibernated`', async () => {
+ it('setPaused(false) drops `hibernatedContext` when it was the only owner, but leaves it standing for `hibernated`', async () => {
const store = memStorage()
vi.stubGlobal('localStorage', store)
const { useAgentStatus } = await import('./agentStatus')
// paused-only: resuming drops the pane record too.
useAgentStatus.getState().setPaused('n28', true)
- useAgentStatus.getState().setHibernatedPane('n28', 'nu')
+ useAgentStatus.getState().setHibernatedContext('n28', { command: 'nu', panePid: 7 })
useAgentStatus.getState().setPaused('n28', false)
- expect(useAgentStatus.getState().byId['n28'].hibernatedPane).toBeUndefined()
+ expect(useAgentStatus.getState().byId['n28'].hibernatedContext).toBeUndefined()
// hibernated AND paused together: resuming `paused` alone leaves `hibernated`'s copy intact.
useAgentStatus.getState().setHibernated('n29', true)
- useAgentStatus.getState().setHibernatedPane('n29', 'nu')
+ useAgentStatus.getState().setHibernatedContext('n29', { command: 'nu', panePid: 7 })
useAgentStatus.getState().setPaused('n29', true)
useAgentStatus.getState().setPaused('n29', false)
- expect(useAgentStatus.getState().byId['n29'].hibernatedPane).toBe('nu')
+ expect(useAgentStatus.getState().byId['n29'].hibernatedContext).toMatchObject({ command: 'nu' })
})
it('clears `paused` on a LIVE state — same self-heal as `hibernated`', async () => {
@@ -247,20 +249,20 @@ describe('loop persistence (cron/schedule survive an app restart)', () => {
}
})
- it('the LIVE-state self-heal drops `hibernatedPane` alongside a paused-only flag (deep pause), but NOT when `hibernated` still owns it', async () => {
+ it('the LIVE-state self-heal drops `hibernatedContext` alongside a paused-only flag (deep pause), but NOT when `hibernated` still owns it', async () => {
const { useAgentStatus } = await import('./agentStatus')
// paused-only (the deep "pause & end session" shape): the pane record goes with it.
useAgentStatus.getState().setPaused('n30', true)
- useAgentStatus.getState().setHibernatedPane('n30', 'nu')
+ useAgentStatus.getState().setHibernatedContext('n30', { command: 'nu', panePid: 7 })
useAgentStatus.getState().setState('n30', 'working', 'claude')
- expect(useAgentStatus.getState().byId['n30'].hibernatedPane).toBeUndefined()
+ expect(useAgentStatus.getState().byId['n30'].hibernatedContext).toBeUndefined()
// hibernated AND paused together (shallow pause): the shared `hibernated` clear already drops
// it — this is not a NEW case, just confirming the paused-only branch doesn't double-clear.
useAgentStatus.getState().setHibernated('n31', true)
useAgentStatus.getState().setPaused('n31', true)
- useAgentStatus.getState().setHibernatedPane('n31', 'nu')
+ useAgentStatus.getState().setHibernatedContext('n31', { command: 'nu', panePid: 7 })
useAgentStatus.getState().setState('n31', 'working', 'claude')
- expect(useAgentStatus.getState().byId['n31'].hibernatedPane).toBeUndefined()
+ expect(useAgentStatus.getState().byId['n31'].hibernatedContext).toBeUndefined()
})
it('keeps `paused` through a `done` event — same as `hibernated`, and through a cold restart (this store never clears it on its own)', async () => {
diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.ts
index b3842f958..9cea90253 100644
--- a/src/renderer/state/agentStatus.ts
+++ b/src/renderer/state/agentStatus.ts
@@ -3,6 +3,7 @@ import { WORKING_STALE_MS } from '@shared/agents/stale'
import type { AgentId } from '@shared/agents/config'
import type { AgentState } from '@shared/agents/normalize'
import type { NodeTerminalApi, ObservedClaudeAccount } from '@shared/types'
+import type { WakeContext } from '../terminal/wake-identity'
/**
* Transient per-node status for agent (e.g. Claude Code) sessions, driven by the agent's hooks.
@@ -90,8 +91,37 @@ export interface AgentNodeStatus {
* and a `nu` user could be hibernated and then never woken: the chip would refuse forever.
* Remembering what we exited TO closes that gap, and it is narrow by construction: it permits
* one specific string, on one specific node, recorded by us.
+ *
+ * It is a RECORD, not just a string, because the name alone was not enough: a pane whose agent
+ * was reached over an interactive `ssh` presents the same local shell after that ssh dies as it
+ * would if the CLI had run here, so the wake typed the resume into the wrong machine's login
+ * shell (issue #823). The pane identity travels with the name, and — more importantly — this
+ * field is only ever written by an exit that first PROVED the agent owned the pane. An entry
+ * without one is refused rather than guessed at, which is also how pre-fix records retire.
+ */
+ hibernatedContext?: WakeContext
+ /**
+ * The last hibernation attempt found no agent in this node's pane, so nothing was exited
+ * (`decideHibernateExit` → `'not-in-this-pane'`: the pane holds a plain shell, or an interactive
+ * `ssh` whose agent lives on another machine — see wake-identity.ts).
+ *
+ * TRANSIENT, and read by the sweep's PLAN, not only by the exit. That placement is the whole
+ * point: the plan is a deterministic sort-and-slice over the oldest-idle nodes, and a node in
+ * this state stays `done`, offscreen and idle forever — so it would sit at the head of that
+ * order and occupy a batch slot on every single pass, refusing each time, while no eligible node
+ * behind it was ever reached. That is the identical starvation the policy's `remote` field is
+ * excluded at plan time to avoid; this is the same rule for the same reason.
+ *
+ * Withdrawn by any live hook event (the CLI is demonstrably back in the pane) — see `setState`.
*/
- hibernatedPane?: string
+ paneUnverified?: boolean
+ /**
+ * Why the last wake refused, in one sentence for the chip's tooltip. Transient: it describes the
+ * pane as it was a moment ago, and a stale reason on a pane that has since been fixed would be a
+ * worse lie than no reason at all. Cleared by a resume, by any live hook event, and by the next
+ * wake that does not refuse.
+ */
+ wakeBlocked?: string
/**
* The user (or Eco's idle sweep, when `settings.agentHibernationPersistAcrossRestart` is on)
* explicitly PAUSED this node: its CLI was exited (and, for the deeper "pause & end session"
@@ -231,9 +261,14 @@ export interface AgentStatusStore {
* Waking also restarts the idle clock (`lastEventAt`), so a quiet resumed session is not
* re-hibernated on the next sweep. */
setHibernated(id: string, on: boolean): void
- /** Record what the pane settled to when this node's CLI let go of it (`null` = forget: a stale
- * value must never permit a wake into a pane we did not measure). See `hibernatedPane`. */
- setHibernatedPane(id: string, pane: string | null): void
+ /** Record the pane this node's CLI let go of (`null` = forget: a stale record must never permit
+ * a wake into a pane we did not measure). See `hibernatedContext`. */
+ setHibernatedContext(id: string, ctx: WakeContext | null): void
+ /** Record (or withdraw) "the last hibernation attempt found no agent in this pane". Transient;
+ * see `paneUnverified`. Withdrawn automatically by any live hook event. */
+ setPaneUnverified(id: string, on: boolean): void
+ /** Record (or clear) why the last wake refused, for the chip's tooltip. See `wakeBlocked`. */
+ setWakeBlocked(id: string, reason: string | null): void
/** Mark the node explicitly paused (true) or resumed (false). Persisted; see `paused`. Waking
* restarts the idle clock, same as `setHibernated` — a resumed session must not read as having
* been idle since before the pause. */
@@ -367,8 +402,19 @@ export function createAgentStatusSession(
// and this is the only record of what that pane turned out to be (see the cold-restore
// gate in TerminalNode.tsx). Meaningless (and, as a wake permission, unwanted) once
// NEITHER flag holds.
- if ((v.hibernated || v.paused) && typeof v.hibernatedPane === 'string')
- out[id].hibernatedPane = v.hibernatedPane
+ if (v.hibernated || v.paused) {
+ // Shape-checked, not trusted: localStorage is hand-editable, and this record is what
+ // authorises a write into a pane. A partial or mistyped one is dropped entirely (⇒ the
+ // wake's `'no-proof'` refusal), never half-applied — the same rule the `loop` entry
+ // below follows, for a much cheaper mistake.
+ const c = v.hibernatedContext
+ if (c && typeof c.command === 'string' && typeof c.panePid === 'number' && c.panePid > 0)
+ out[id].hibernatedContext = {
+ command: c.command,
+ panePid: c.panePid,
+ paneId: typeof c.paneId === 'string' ? c.paneId : undefined
+ }
+ }
// Independent of `hibernated`: the deep "pause & end session" choice recycles the tmux
// session, so a paused node can perfectly well hydrate with `hibernated` unset.
if (v.paused) out[id].paused = true
@@ -420,8 +466,8 @@ export function createAgentStatusSession(
account: v.account,
loop: v.loop,
hibernated: v.hibernated,
- // Never written without a flag it belongs to (see `hibernatedPane`'s load comment).
- hibernatedPane: v.hibernated || v.paused ? v.hibernatedPane : undefined,
+ // Never written without a flag it belongs to (see `hibernatedContext`'s load comment).
+ hibernatedContext: v.hibernated || v.paused ? v.hibernatedContext : undefined,
paused: v.paused
}
}
@@ -540,7 +586,7 @@ export function createAgentStatusSession(
const alive = state === 'working' || state === 'blocked' || state === 'waiting'
if (alive && prev.hibernated) {
next.hibernated = undefined
- next.hibernatedPane = undefined // goes with the flag, always
+ next.hibernatedContext = undefined // goes with the flag, always
}
// Same self-heal, same reasoning: a live hook event is proof the CLI is running, whatever
// brought it back (our own resume, or the user typing the launch line by hand) — a standing
@@ -552,8 +598,15 @@ export function createAgentStatusSession(
// `hibernated` to protect it, so without this an in-memory record describing a pane that
// is now demonstrably running something else would linger, and stand as permission for
// the next deep pause to be typed into recognizing a pane it never measured.
- if (!next.hibernated) next.hibernatedPane = undefined
+ if (!next.hibernated) next.hibernatedContext = undefined
}
+ // A hook event of ANY kind — `done` included — is the CLI reporting from inside the pane,
+ // which is exactly the fact both of these withdraw. `paneUnverified` said "no agent is in
+ // this pane"; a hook event says otherwise, and without this the node would stay out of the
+ // sweep's plan for the rest of the run. `wakeBlocked` described a refusal that is now moot.
+ // Gated on neither `alive` nor `newTurn`: a `done` POST still comes from a live CLI.
+ if (prev.paneUnverified) next.paneUnverified = undefined
+ if (prev.wakeBlocked) next.wakeBlocked = undefined
// A hook event of ANY kind is proof the CLI is alive — it is the CLI that fired it — so a
// standing DROPPED verdict is withdrawn here, `done` included. That is the one self-heal
// above which deliberately does NOT gate on `alive`: `done` must not clear `hibernated`
@@ -643,7 +696,9 @@ export function createAgentStatusSession(
...prev,
hibernated: on ? true : undefined,
// Hibernating KEEPS what the exit closure just recorded; waking drops it.
- hibernatedPane: on ? prev.hibernatedPane : undefined
+ hibernatedContext: on ? prev.hibernatedContext : undefined,
+ // A wake that succeeded answers whatever the last refusal said.
+ wakeBlocked: on ? prev.wakeBlocked : undefined
}
// Waking RESTARTS the idle clock. Without this, a node whose conversation was resumed but
// whose CLI then sits quiet (an agent that fires no hook until you talk to it) still
@@ -657,16 +712,41 @@ export function createAgentStatusSession(
return { byId }
}),
- setHibernatedPane: (id, pane) =>
+ setHibernatedContext: (id, ctx) =>
set((s) => {
const prev = s.byId[id] ?? EMPTY
- const next = pane ?? undefined
- if (prev.hibernatedPane === next) return s
- const byId = { ...s.byId, [id]: { ...prev, hibernatedPane: next } }
+ const next = ctx ?? undefined
+ // Value equality, not identity: the caller builds a fresh object from every pane read, and
+ // an identity compare would write (and persist) on each one.
+ if (
+ prev.hibernatedContext?.command === next?.command &&
+ prev.hibernatedContext?.panePid === next?.panePid &&
+ prev.hibernatedContext?.paneId === next?.paneId
+ )
+ return s
+ const byId = { ...s.byId, [id]: { ...prev, hibernatedContext: next } }
save(byId)
return { byId }
}),
+ setPaneUnverified: (id, on) =>
+ set((s) => {
+ const prev = s.byId[id] ?? EMPTY
+ const next = on ? true : undefined
+ if (prev.paneUnverified === next) return s
+ // Transient: no `save`. It describes this run's reading of a live pane, and a persisted
+ // copy would keep a node out of the sweep across a restart on evidence nobody re-took.
+ return { byId: { ...s.byId, [id]: { ...prev, paneUnverified: next } } }
+ }),
+
+ setWakeBlocked: (id, reason) =>
+ set((s) => {
+ const prev = s.byId[id] ?? EMPTY
+ const next = reason ?? undefined
+ if (prev.wakeBlocked === next) return s
+ return { byId: { ...s.byId, [id]: { ...prev, wakeBlocked: next } } }
+ }),
+
setPaused: (id, on) =>
set((s) => {
const prev = s.byId[id] ?? EMPTY
@@ -682,7 +762,8 @@ export function createAgentStatusSession(
// both flags together, in which case `setHibernated(id, false)` already dropped this —
// but `setPaused` must be correct standing alone, for the deep-pause case where
// `hibernated` was never set and this is the only owner).
- if (!prev.hibernated) next.hibernatedPane = undefined
+ if (!prev.hibernated) next.hibernatedContext = undefined
+ next.wakeBlocked = undefined
}
const byId = { ...s.byId, [id]: next }
save(byId)
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index f0609cdde..caec75eb2 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -2046,6 +2046,19 @@ body,
color: var(--text);
}
+/* SLEEPING, but the wake refused: the pane is no longer the one this session was exited in, so
+ nothing was typed into it (see wake-identity.ts). Warning-coloured like DROPPED rather than
+ muted like plain SLEEPING, because this one needs the user — the conversation will not come back
+ on its own. Still the same button; its click re-checks the pane. */
+.term-node__status--wake-blocked {
+ color: var(--warn);
+}
+
+.term-node__status--wake-blocked:hover {
+ color: var(--warn);
+ opacity: 0.85;
+}
+
/* PAUSED: same quiet treatment as SLEEPING (a click resumes) — distinct label because a paused
node will NOT auto-resume when reopened, which SLEEPING does. */
.term-node__status--paused {
diff --git a/src/renderer/terminal/hibernation-policy.test.ts b/src/renderer/terminal/hibernation-policy.test.ts
index 08834d963..e93f80699 100644
--- a/src/renderer/terminal/hibernation-policy.test.ts
+++ b/src/renderer/terminal/hibernation-policy.test.ts
@@ -19,6 +19,7 @@ const base = (id: string, over: object = {}) => ({
recurring: false,
liveSubagents: false,
liveBackgroundTask: false,
+ paneUnverified: false,
lastEventAt: 0,
...over
})
@@ -40,7 +41,13 @@ describe('planHibernation', () => {
base('i', { state: 'waiting' }),
base('j', { recurring: true }),
base('k', { liveSubagents: true }),
- base('l', { liveBackgroundTask: true })
+ base('l', { liveBackgroundTask: true }),
+ // A node whose last exit attempt found no agent in its pane is excluded HERE, not merely
+ // refused at fire time. It is `done`, offscreen and idle and nothing about it will change
+ // on its own, so left in the plan it would hold a batch slot on every sweep for the rest
+ // of the run — the same starvation `remote` is excluded at plan time to avoid. See
+ // wake-identity.ts / issue #823.
+ base('m', { paneUnverified: true, lastEventAt: 0 })
],
NOW,
cfg
diff --git a/src/renderer/terminal/hibernation-policy.ts b/src/renderer/terminal/hibernation-policy.ts
index 25aacbe9a..5239805f4 100644
--- a/src/renderer/terminal/hibernation-policy.ts
+++ b/src/renderer/terminal/hibernation-policy.ts
@@ -30,6 +30,14 @@
* - **Unknown idle is NOT idle.** A candidate with no `lastEventAt` (no hook event has ever been
* seen for it in this run) is never eligible — the same rule as pendingLaunch's "an unknown
* dependency state is not satisfied". Guessing here costs the user a live session.
+ * - **Never a pane the agent does not OWN.** Eco's contract is "quit the CLI in this pane and
+ * resume it in this pane", and `#{pane_current_command}` cannot tell whether that is what the
+ * pane holds: an npm-installed CLI reports as `node`, and a CLI reached over an interactive
+ * `ssh` reports as `ssh` while running on another machine entirely. The exit therefore asks the
+ * kernel who owns the pane's foreground group (`decideHibernateExit`), and a node it refused is
+ * kept out of subsequent plans by this flag. Issue #823: without the ownership question, a node
+ * whose ssh had since died was exited — `/exit` typed into the local login shell — recorded as
+ * SLEEPING, and its wake typed `claude --resume <remote id>` into that same local shell.
* - **Never a REMOTE session** (SSH project / relay tab) in v1 — and excluded at PLAN time, not
* only when the exit is attempted: the plan is a deterministic sort-and-slice, so two remote
* nodes at the head of the oldest-idle order would occupy both batch slots on every pass and no
@@ -96,6 +104,19 @@ export interface HibernationCandidate {
* to prevent, reachable here through the automatic sweep instead.
*/
paused: boolean
+ /**
+ * The last exit attempt proved there is no agent in this node's pane, so nothing was quit
+ * (`agentStatus.paneUnverified`; the verdict itself is `decideHibernateExit`).
+ *
+ * Excluded HERE, at plan time, for exactly the reason `remote` is — and this one is worse. A node
+ * in this state is `done`, offscreen and idle, and NOTHING about it will change on its own: it
+ * sorts to the head of the oldest-idle order and stays there. Left in the plan it would take a
+ * batch slot on every sweep for the rest of the run, refuse at fire time, and starve every
+ * eligible node behind it. Two such nodes would switch Eco off entirely, silently.
+ *
+ * Transient, and withdrawn by any live hook event — a CLI that fires a hook is a CLI in the pane.
+ */
+ paneUnverified: boolean
}
export interface HibernationConfig {
@@ -158,6 +179,7 @@ export function planHibernation(
!c.hibernated &&
!c.paused &&
!c.remote &&
+ !c.paneUnverified &&
c.wired &&
c.offscreen &&
c.state === 'done' &&
diff --git a/src/renderer/terminal/wake-identity.test.ts b/src/renderer/terminal/wake-identity.test.ts
new file mode 100644
index 000000000..c210c5953
--- /dev/null
+++ b/src/renderer/terminal/wake-identity.test.ts
@@ -0,0 +1,211 @@
+import { describe, it, expect } from 'vitest'
+import type { PaneOwner } from '@shared/agents/pane-owner-predicate'
+import {
+ captureWakeContext,
+ decideHibernateExit,
+ decideWakeResume,
+ wakeRefusalReason,
+ wakeVerdictIsTransient,
+ type WakeContext
+} from './wake-identity'
+
+/**
+ * Every pane below is a READING TAKEN FROM A REAL PANE (tmux 3.4 + procps-ng, one host, one
+ * interactive ssh to itself). They are transcribed rather than invented because the whole bug is
+ * that the invented ones looked fine:
+ *
+ * local shell idle pane_pid 3182371 %0 bash fg `bash --norc --noprofile -i`
+ * ssh up (agent on far side) pane_pid 3182371 %0 ssh fg `ssh -i /tmp/probekey … localhost`
+ * ssh dead, login shell back pane_pid 3182371 %0 bash fg `bash --norc --noprofile -i`
+ * local claude in the pane pane_pid 3186583 %0 node fg `node /tmp/fakebin/claude`
+ *
+ * Note the first and third readings are IDENTICAL, pane id and pane pid included: after the fact
+ * nothing local distinguishes "the CLI ran here" from "the CLI was at the far end of an ssh that
+ * has since died". That is why the proof has to be taken at the exit.
+ */
+const owner = (o: Partial<PaneOwner> & Pick<PaneOwner, 'command' | 'argv'>): PaneOwner => ({
+ panePid: 3182371,
+ tty: '/dev/pts/24',
+ paneId: '%0',
+ pids: [3182371],
+ ...o
+})
+
+const LOCAL_SHELL = owner({ command: 'bash', argv: ['bash --norc --noprofile -i'] })
+const SSH_TO_AGENT = owner({
+ command: 'ssh',
+ argv: ['ssh -i /tmp/probekey -o StrictHostKeyChecking=no localhost'],
+ pids: [3182630]
+})
+const LOCAL_CLAUDE = owner({
+ command: 'node',
+ argv: ['node /tmp/fakebin/claude'],
+ panePid: 3186583,
+ pids: [3186717]
+})
+
+describe('decideHibernateExit — may we type `/exit` into this pane?', () => {
+ it('permits a pane the agent actually owns, THROUGH the `node` disguise', () => {
+ // `pane_current_command` says `node` for every npm-installed CLI, so the name-based read this
+ // replaces could not have told this pane from any other node process.
+ expect(decideHibernateExit(LOCAL_CLAUDE, 'claude')).toBe('agent-owns-pane')
+ })
+
+ it('REFUSES a pane holding an interactive ssh — the agent is on another machine', () => {
+ // Eco's position on an ssh-in-pane node, and it falls out of the ownership question rather
+ // than needing a rule of its own: `ssh` is not an agent binary, and `NEVER_A_BINARY` makes
+ // sure it can never become one, whatever a custom agent's launch command says.
+ expect(decideHibernateExit(SSH_TO_AGENT, 'claude')).toBe('not-in-this-pane')
+ })
+
+ it('REFUSES a pane already sitting on a shell — there is no CLI here to quit', () => {
+ // The reported chain starts here: the node still reads `done` (hooks came over a tunnel from
+ // the far side and simply stopped), but its pane fell back to the local login shell when the
+ // ssh died. The old code typed `/exit` into that shell and recorded it as SLEEPING.
+ expect(decideHibernateExit(LOCAL_SHELL, 'claude')).toBe('not-in-this-pane')
+ })
+
+ it('fails CLOSED on a pane it cannot read', () => {
+ // Deliberately unlike the rest of this app, where a failed probe degrades to the bare
+ // pre-feature behaviour. Here the pre-feature behaviour is to quit whatever is in the pane.
+ expect(decideHibernateExit(null, 'claude')).toBe('unreadable')
+ expect(decideHibernateExit(owner({ command: 'bash', argv: [] }), 'claude')).toBe('unreadable')
+ })
+
+ it('names a CUSTOM agent from its own launch command rather than refusing it', () => {
+ const mine = owner({ command: 'node', argv: ['node /opt/bin/my-agent --serve'] })
+ const custom = [{ id: 'custom:u1', launchCmd: 'npx -y my-agent --serve' }]
+ expect(decideHibernateExit(mine, 'custom:u1')).toBe('unreadable') // unnameable without it
+ expect(
+ decideHibernateExit(mine, 'custom:u1', ['my-agent'])
+ ).toBe('agent-owns-pane')
+ // …which is what `binariesFor(agentId, settings.customAgents)` supplies at the call site.
+ expect(custom[0].launchCmd).toContain('my-agent')
+ })
+})
+
+describe('decideWakeResume — may we type the resume line into this pane?', () => {
+ /** What the exit recorded for a pane it proved the agent owned, then watched settle to a shell. */
+ const recorded: WakeContext = { command: 'bash', panePid: 3182371, paneId: '%0' }
+
+ it('resumes the ordinary same-context wake', () => {
+ expect(
+ decideWakeResume({ owner: LOCAL_SHELL, recorded, exitedByUs: true, agentId: 'claude' })
+ ).toBe('resume')
+ })
+
+ it('REFUSES when the pane is a different shell than the one exited into', () => {
+ // The pane's root process moved: the tmux session was recycled under this node, or the node
+ // was respawned onto a new one. The record describes a pane that is not this one, and it is
+ // not permission to type into whatever took its place.
+ const elsewhere = owner({ command: 'bash', argv: ['bash -i'], panePid: 99999, paneId: '%7' })
+ expect(
+ decideWakeResume({ owner: elsewhere, recorded, exitedByUs: true, agentId: 'claude' })
+ ).toBe('context-changed')
+ })
+
+ it('REFUSES a record with no proof — every node hibernated by the build that shipped the bug', () => {
+ // The migration, and the only honest answer for it: the pane in front of us looks exactly like
+ // the pane the record describes (see the header — the two readings are identical), so there is
+ // nothing left to check. The node stays SLEEPING and its chip stays clickable.
+ expect(
+ decideWakeResume({ owner: LOCAL_SHELL, recorded: undefined, exitedByUs: true, agentId: 'claude' })
+ ).toBe('no-proof')
+ })
+
+ it('REFUSES a pane that now holds an interactive ssh', () => {
+ expect(
+ decideWakeResume({ owner: SSH_TO_AGENT, recorded, exitedByUs: true, agentId: 'claude' })
+ ).toBe('context-changed')
+ })
+
+ it('REFUSES a pane an agent is running in again — a launch line typed into a live CLI is a MESSAGE', () => {
+ // The user relaunched claude by hand, or a wrapper loop restarted it. Asked before anything
+ // else, and for both wake families.
+ expect(
+ decideWakeResume({ owner: LOCAL_CLAUDE, recorded, exitedByUs: true, agentId: 'claude' })
+ ).toBe('agent-running')
+ expect(
+ decideWakeResume({ owner: LOCAL_CLAUDE, recorded: null, exitedByUs: false, agentId: 'claude' })
+ ).toBe('agent-running')
+ })
+
+ it('keeps the allowlist-free recognition for nu / xonsh / pwsh users', () => {
+ // The exit half accepts a shell its allowlist does not know; without this the wake would be
+ // STRICTER than the exit that produced it and such a user would be hibernated and never woken.
+ const nu = owner({ command: 'nu', argv: ['nu'] })
+ const nuRecord: WakeContext = { command: 'nu', panePid: 3182371, paneId: '%0' }
+ expect(
+ decideWakeResume({ owner: nu, recorded: nuRecord, exitedByUs: true, agentId: 'claude' })
+ ).toBe('resume')
+ // …but only for the command it actually measured. `vim` is not a shell and is not the record.
+ const vim = owner({ command: 'vim', argv: ['vim /etc/hosts'] })
+ expect(
+ decideWakeResume({ owner: vim, recorded: nuRecord, exitedByUs: true, agentId: 'claude' })
+ ).toBe('context-changed')
+ })
+
+ it('does not read a MISSING pane id as a mismatch', () => {
+ // A record taken before `paneId` existed, or a read whose format expanded to nothing: that is
+ // absent evidence, and `panePid` is already holding the pane's identity.
+ const noId = owner({ command: 'bash', argv: ['bash -i'], paneId: undefined })
+ expect(
+ decideWakeResume({ owner: noId, recorded, exitedByUs: true, agentId: 'claude' })
+ ).toBe('resume')
+ expect(
+ decideWakeResume({
+ owner: LOCAL_SHELL,
+ recorded: { command: 'bash', panePid: 3182371 },
+ exitedByUs: true,
+ agentId: 'claude'
+ })
+ ).toBe('resume')
+ })
+
+ describe('the wakes that are NOT ours to match (deep pause / dropped)', () => {
+ // A deep "pause & end session" deliberately recycles the tmux session, and a `dropped` node's
+ // CLI died on its own. Neither has a pane of ours to match; requiring one would strand both
+ // behind a refusal they can never satisfy. They keep exactly today's shell recognition.
+ it('resumes into a plain shell with no record at all', () => {
+ expect(
+ decideWakeResume({ owner: LOCAL_SHELL, recorded: null, exitedByUs: false, agentId: 'claude' })
+ ).toBe('resume')
+ })
+ it('still refuses a pane that is not a shell', () => {
+ expect(
+ decideWakeResume({ owner: SSH_TO_AGENT, recorded: null, exitedByUs: false, agentId: 'claude' })
+ ).toBe('context-changed')
+ })
+ })
+
+ it('treats an unreadable pane as transient, and every standing refusal as standing', () => {
+ expect(
+ decideWakeResume({ owner: null, recorded, exitedByUs: true, agentId: 'claude' })
+ ).toBe('unreadable')
+ expect(wakeVerdictIsTransient('unreadable')).toBe(true)
+ for (const v of ['agent-running', 'no-proof', 'context-changed'] as const) {
+ expect(wakeVerdictIsTransient(v), v).toBe(false)
+ // …and a standing refusal is the only kind that gets a sentence: that field is what the
+ // wake trigger reads to stop retrying, so a transient verdict must leave it null.
+ expect(wakeRefusalReason(v), v).toBeTruthy()
+ }
+ expect(wakeRefusalReason('unreadable')).toBeNull()
+ expect(wakeRefusalReason('resume')).toBeNull()
+ })
+})
+
+describe('captureWakeContext', () => {
+ it('records the pane the exit settled into', () => {
+ expect(captureWakeContext(LOCAL_SHELL)).toEqual({
+ command: 'bash',
+ panePid: 3182371,
+ paneId: '%0'
+ })
+ })
+
+ it('records NOTHING it could not measure — an absent record is refused, a blank one would not be', () => {
+ expect(captureWakeContext(null)).toBeNull()
+ expect(captureWakeContext(owner({ command: '', argv: ['bash'] }))).toBeNull()
+ expect(captureWakeContext(owner({ command: 'bash', argv: ['bash'], panePid: 0 }))).toBeNull()
+ })
+})
diff --git a/src/renderer/terminal/wake-identity.ts b/src/renderer/terminal/wake-identity.ts
new file mode 100644
index 000000000..4ec94f812
--- /dev/null
+++ b/src/renderer/terminal/wake-identity.ts
@@ -0,0 +1,172 @@
+/**
+ * WHICH PANE MAY BE TYPED INTO — the identity behind Eco's exit and its much later wake.
+ *
+ * Hibernation is two writes separated by hours: `/exit` now, `claude --resume <id>` when the user
+ * comes back. Both land in a tmux pane the user can also type into, and the second one carries a
+ * session id that only resolves in the context the first one quit. So the pair needs an identity,
+ * and the question it has to answer is NOT "is something shell-shaped in this pane?" but "is this
+ * the shell we exited the CLI in?".
+ *
+ * ── WHY THE OLD GATE COULD NOT ANSWER IT (issue #823, measured on tmux 3.4) ─────────────────────
+ *
+ * The wake's gate was `isShellCommand(pane) || pane === hibernatedPane` — a NAME test. For a node
+ * whose agent is reached over an interactive `ssh` inside its pane, the names read like this
+ * (measured, a real pane, real ssh, real `ps`):
+ *
+ * local shell idle pane_current_command = bash fg argv = `bash …`
+ * ssh up, agent on far side pane_current_command = ssh fg argv = `ssh -i … localhost`
+ * ssh dead, login shell back pane_current_command = bash fg argv = `bash …`
+ *
+ * `pane_pid` and `pane_id` are IDENTICAL in all three readings — the pane's root process is the
+ * local login shell throughout, and the remote shell was never a local process at all. So after the
+ * fact NOTHING about the pane distinguishes "the CLI was here" from "the CLI was at the far end of
+ * an ssh that has since died": both present a plain local shell. The old gate passed, and the
+ * resume was typed into the Mac's login shell at `~`, where the remote session id cannot resolve.
+ *
+ * ── WHERE THE IDENTITY ACTUALLY LIVES ───────────────────────────────────────────────────────────
+ *
+ * The difference is only visible while the CLI is still running, so the proof has to be taken THEN.
+ * `decideHibernateExit` refuses to quit a pane unless the kernel says the agent binary owns its
+ * foreground process group (`isAgentPane` — the same positive, three-valued predicate the delivery
+ * gate uses). An `ssh` pane answers `not-agent`, and so does a pane that is already sitting on a
+ * shell because the CLI is long gone. Neither is exited, so neither ever becomes SLEEPING, and
+ * there is nothing for a later wake to get wrong.
+ *
+ * `decideWakeResume` is then the cheap re-check across the gap: the same pane, still not an agent's,
+ * still recognisable. It cannot re-derive the proof — that moment has passed — so a record without
+ * one is refused rather than guessed at. That is deliberately the migration path too: a node
+ * hibernated by the build that shipped this bug carries no proof, and refusing it is the only
+ * honest answer (the node stays SLEEPING and its chip stays clickable).
+ */
+import { isShellCommand } from '@shared/agents/pane'
+import { isAgentPane, type PaneOwner } from '@shared/agents/pane-owner-predicate'
+
+/**
+ * What a pane looked like at the instant our `/exit` was answered — the proof a wake re-checks.
+ *
+ * `panePid` and `paneId` cannot tell two SHELLS apart (see the header measurement), and they are
+ * not here for that. They pin the PANE: a session recycled under the node, or a node respawned onto
+ * a new one, changes both, and a resume aimed at a record from the pane before it would be landing
+ * somewhere it was never authorised for. `command` carries the allowlist-free recognition the exit
+ * half already relies on, so a `nu` / `xonsh` / `pwsh` user is not hibernated and then never woken.
+ */
+export interface WakeContext {
+ /** `#{pane_current_command}` once the CLI had let go. */
+ command: string
+ /** `#{pane_pid}` — the process tmux forked for the pane. Constant for the pane's life. */
+ panePid: number
+ /** `#{pane_id}` (`%17`) — never reused for the life of the tmux server. Absent on an older read. */
+ paneId?: string
+}
+
+/**
+ * `'agent-owns-pane'` is the ONLY outcome that may be followed by a write.
+ *
+ * `'not-in-this-pane'` is terminal for this node until something changes: the kernel answered and
+ * the agent is not in the pane's foreground group. `'unreadable'` is transient (no tmux, a pane
+ * that stopped existing, `ps` unavailable, the deadline lapsed) and the next sweep re-asks — it is
+ * never upgraded, because the exit it gates is irreversible.
+ */
+export type ExitContextVerdict = 'agent-owns-pane' | 'not-in-this-pane' | 'unreadable'
+
+/**
+ * May we ask the CLI in this pane to quit?
+ *
+ * Fails CLOSED on `unknown`, unlike most of this app's probes: everywhere else a probe that cannot
+ * answer degrades to the bare, pre-feature behaviour, but here the pre-feature behaviour is to type
+ * `/exit` into whatever is there. The conversation is only recoverable through the `--resume` this
+ * pair promises, so "we could not see the pane" must mean "leave it alone", not "quit it anyway".
+ */
+export function decideHibernateExit(
+ owner: PaneOwner | null | undefined,
+ agentId: string,
+ binaries?: readonly string[] | null
+): ExitContextVerdict {
+ switch (isAgentPane(owner, agentId, binaries)) {
+ case 'agent':
+ return 'agent-owns-pane'
+ case 'not-agent':
+ return 'not-in-this-pane'
+ default:
+ return 'unreadable'
+ }
+}
+
+/** The pane identity to remember, or null when the read gave us nothing to remember. Null is not a
+ * blank record — it is the absence of one, and the wake refuses on it. */
+export function captureWakeContext(owner: PaneOwner | null | undefined): WakeContext | null {
+ if (!owner || !owner.command || !(owner.panePid > 0)) return null
+ return { command: owner.command, panePid: owner.panePid, paneId: owner.paneId }
+}
+
+/**
+ * `'resume'` is the only outcome that may be followed by a write.
+ *
+ * - `'agent-running'` — a CLI owns this pane again (the user relaunched one by hand, or a
+ * wrapper loop restarted it). A launch line typed into a live CLI is sent
+ * to it as a MESSAGE. Standing refusal.
+ * - `'no-proof'` — we exited this node ourselves but hold no record of the pane we exited
+ * into. Pre-fix records, and any record a failed post-exit read dropped.
+ * - `'context-changed'` — we hold a record and the pane no longer matches it.
+ * - `'unreadable'` — the pane could not be read. Transient; the caller may retry.
+ */
+export type WakeVerdict = 'resume' | 'agent-running' | 'no-proof' | 'context-changed' | 'unreadable'
+
+export interface WakeDecisionInput {
+ owner: PaneOwner | null | undefined
+ /** The proof recorded by the exit that produced this state, if any. */
+ recorded: WakeContext | null | undefined
+ /**
+ * Did OUR exit put this pane on a shell (`agentStatus.hibernated`)?
+ *
+ * The two wake families need different questions, and this is what separates them. When we did
+ * the exit there is a specific pane we exited INTO, and matching it is the whole point. When we
+ * did not — a deep "pause & end session" deliberately RECYCLES the tmux session, and a `dropped`
+ * node's CLI died on its own — there is no prior pane to match, and requiring one would strand
+ * both behind a refusal they can never satisfy. Those keep exactly the shell recognition they
+ * have today, plus the agent-running refusal below, which they did not have.
+ */
+ exitedByUs: boolean
+ agentId: string
+ binaries?: readonly string[] | null
+}
+
+export function decideWakeResume(i: WakeDecisionInput): WakeVerdict {
+ if (!i.owner) return 'unreadable'
+ // Asked FIRST, and for both families: whatever else is true, a pane an agent is running in is
+ // never a pane to type a launch line into.
+ if (isAgentPane(i.owner, i.agentId, i.binaries) === 'agent') return 'agent-running'
+ const pane = i.owner.command
+ if (!pane) return 'unreadable'
+ if (!i.exitedByUs) return isShellCommand(pane) ? 'resume' : 'context-changed'
+ const rec = i.recorded
+ if (!rec) return 'no-proof'
+ if (i.owner.panePid !== rec.panePid) return 'context-changed'
+ // Compared only when BOTH sides carry one: a record taken before `paneId` existed, or a read the
+ // format expanded to nothing for, must not read as a mismatch — that is missing evidence, and
+ // `panePid` above is already holding the pane's identity.
+ if (rec.paneId && i.owner.paneId && rec.paneId !== i.owner.paneId) return 'context-changed'
+ if (!isShellCommand(pane) && pane !== rec.command) return 'context-changed'
+ return 'resume'
+}
+
+/** Does this verdict mean "ask again in a moment"? Everything else is a standing refusal, and the
+ * wake's bounded retry must not spend its attempts on one. */
+export function wakeVerdictIsTransient(v: WakeVerdict): boolean {
+ return v === 'unreadable'
+}
+
+/** What to tell the user about a wake that refused. One sentence, no jargon: the chip's tooltip is
+ * the only place any of this is ever visible. */
+export function wakeRefusalReason(v: WakeVerdict): string | null {
+ switch (v) {
+ case 'agent-running':
+ return 'Something is already running in this terminal, so the session was not resumed. Open it to see.'
+ case 'context-changed':
+ return 'This terminal is no longer the shell the session was paused in, so it was not resumed. Open it and resume by hand.'
+ case 'no-proof':
+ return 'This session was paused by an older version that did not record where, so it cannot be resumed safely. Open the terminal and resume by hand.'
+ default:
+ return null
+ }
+}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 14e1fc4f0..e655d9f98 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -32,6 +32,12 @@ export const IPC = {
/** The foreground command of a node's tmux pane (`#{pane_current_command}`) — how the in-place
* agent restart sees that the CLI has exited and a shell owns the pane again. */
ptyPaneCommand: 'pty:pane-command',
+ /** Kernel truth about a node's tmux pane: its root pid, tty, tmux pane id, and the full argv of
+ * its FOREGROUND process group (`PaneOwner`). The name-only `ptyPaneCommand` above cannot tell
+ * an agent from anything else — an npm-installed CLI reports as `node`, and an agent reached
+ * over an interactive `ssh` reports as `ssh` — so the hibernation exit asks this instead before
+ * it types `/exit` into a pane. null when the pane cannot be read. */
+ ptyPaneOwner: 'pty:pane-owner',
/** Renderer → core: SIGTERM the non-shell foreground process group in this node's pane.
* Model switching uses this instead of typing an exit slash-command into an agent composer. */
ptyTerminateForeground: 'pty:terminate-foreground',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 76fabebbf..748df43bc 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -5,6 +5,7 @@ import { DEFAULT_WORKTREE_PATH_TEMPLATE } from './worktree'
import type { CloneProgress } from './clone-url'
import type { KeybindingOverrides, TerminalShortcutPolicy } from './keybindings'
import type { NormalizedAgentEvent } from './agents/normalize'
+import type { PaneOwner } from './agents/pane-owner-predicate'
import type { AgentId, AgentPermissionMode, BuiltinAgentId, PromptInjectionMode } from './agents/config'
import type { ControlConfirmWaivers } from './control-confirm'
import type { AgentMessageDeliverRequest, AgentMessageReply } from './agents/agent-messaging'
@@ -1000,6 +1001,11 @@ export interface PtyApi {
* node persistKey. null when it is unknown — no session, no tmux, or the query failed — which
* callers must read as "not observed", never as evidence of a particular command. */
paneCommand(persistKey: string): Promise<string | null>
+ /** Kernel truth about a node's pane — its root pid, tty, tmux pane id and the full argv of its
+ * foreground process group — so a caller can ask WHO owns the pane rather than what tmux calls
+ * it. `null` is "could not read", never evidence that the pane is free (see `isAgentPane`'s
+ * three-valued verdict, which is what consumers should decide on). */
+ paneOwner(persistKey: string): Promise<PaneOwner | null>
/** Terminate the foreground process group in a node's pane. Returns false when the pane/process
* cannot be safely identified; it never kills the pane's login shell. When `expectedAgentId` is
* given, the kill happens only if that harness actually owns the foreground group (argv-verified)