Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(agents): show when an agent CLI died unannounced, with one-click resume
enesf81329c84263
diff --git a/CLAUDE.md b/CLAUDE.mdindex 70e23f2ca..9e79ef5b5 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1352,6 +1352,39 @@ else, and its context links must keep classifying across restarts).`NormalizedAgentEvent` from `agent:status`, drives the `agentStatus` store, fires throttled(5s/node) background notifications, and records the session id. Header shows a pulsing**RUNNING** (working) / **NEEDS YOU** (waiting/blocked) badge.+- **DROPPED — the CLI died and nobody told us** (`renderer/terminal/agent-liveness.ts`, issue #616).+ Every ORDERLY exit announces itself: Eco's `/exit` sets `hibernated`, "Pause session" sets+ `paused`, and a user typing `/exit` fires the CLI's own SessionEnd, which `setState(id, undefined)`+ records. A KILL announces nothing — the process is gone before it can run a hook, and tmux's shell+ still owns the pane so the PTY never closes. The node therefore kept rendering its last badge over+ a dead conversation, with the CLI's parting `Resume this session with: claude --resume <uuid>` and+ a stray `^[%` in the pane as the only evidence. Not exotic: measured on the reporting host+ (2026-09-04) 62 GB RAM with swap fully consumed, kernel `oom_kill` at 187, 147 live `claude`+ processes holding 44 GB. The signal is `#{pane_current_command}` reading as a shell while the+ status table still believes an agent is parked there, and the four refusals are the feature:+ a `null` pane read is NEVER evidence (a downed ControlMaster must not make a canvas of healthy+ remote nodes claim they died); `hibernated`/`paused` are our own exits and already have chips;+ **only `done`**, never `working` — a turn in flight is exactly when a tool subprocess can own the+ pane's foreground, so the alarm would fire on a healthy agent running a shell command; and the+ agent must be in **`SESSION_END_CAPABLE`**. That last list is the false-positive gate and is+ DERIVED from `normalize.ts`, not chosen: exactly four normalizers map `sessionPhase: 'end'`+ (claude, gemini, copilot, grok) and **codex and opencode map none**, so on those two a deliberate+ `/quit` and an OOM kill leave byte-identical evidence and the chip would be a coin flip shown as a+ fact. Adding an id without first adding its normalizer branch puts a chip on every session its+ owner quit on purpose — `agent-liveness.test.ts` asserts the list against that source. The verdict+ (`agentStatus.dropped`) is TRANSIENT, a stronger call than the other clocks: it is a claim about a+ pane, panes are re-measurable in milliseconds, and a persisted one would strand a stale chip on a+ node someone resumed by hand. ANY hook event withdraws it — the one self-heal that deliberately+ does not gate on `alive`, since `done` disproves "there is no CLI in this pane" even though it must+ not clear `hibernated`. Cost is bounded by asking only for a node that is BOTH watched and already+ believed to be a parked agent. Resume reuses the hibernation wake closure unchanged, which+ re-reads the pane and refuses anything that is not a shell. Chip on the node header, the kanban+ card and the card modal; Desktop and Server Edition identical; relay tabs answer `null` and are+ never judged. **A second thing this catches, unplanned:** in the same sweep 9 of 149 panes sat at a+ bare shell because a cold-restore `--resume` had answered *"No conversation found with session+ ID"* — the persisted `sessionId` outlived its transcript. The chip surfaces those too, but the+ Resume it offers replays the same dead id; making cold restore fall back to a bare launch when the+ transcript is gone is a separate, unbuilt fix.- **Hook server (loopback HTTP)** — `src/core/agents/hook-server.ts` is a main-processloopback HTTP server (per-session bearer token, fail-open) that the installed hook scriptsPOST to; it replaced the old `fs.watch` signal-log mechanism. `buildPtyEnv` injects thediff --git a/src/renderer/components/kanban/CardModal.tsx b/src/renderer/components/kanban/CardModal.tsxindex 88a37aced..1828b8864 100644--- a/src/renderer/components/kanban/CardModal.tsx+++ b/src/renderer/components/kanban/CardModal.tsx@@ -70,6 +70,7 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,const [editingNote, setEditingNote] = useState(false)const agentSessionId = useAgentStatus((st) => st.byId[session.id]?.sessionId)const paused = useAgentStatus((st) => !!st.byId[session.id]?.paused)+ const dropped = useAgentStatus((st) => !!st.byId[session.id]?.dropped)// Same chip as the card and the canvas node header — the modal is where a user checks WHICH// session this is, so the account belongs in its header chips, not only two views away.const observedAccount = useAgentStatus((st) => st.byId[session.id]?.account)@@ -285,6 +286,20 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,when the node is being driven even though the drive lands on the CANVAS webview, notthis modal's — which is what the user needs to know (Task 6.3). */}{isBrowser && <BrowserDrivingIndicator nodeId={session.id} />}+ {isTerminal && dropped && (+ // Same argument as PAUSED below, with a worse cause: the modal co-attaches a live view+ // of a pane that holds a bare shell, and without this the user would be looking at the+ // CLI's own parting "Resume this session with: …" line with nothing saying what it+ // means. The wake trigger admits `dropped` for exactly this click.+ <button+ className="kanban-badge kanban-badge--dropped"+ style={{ cursor: 'pointer', border: 'none' }}+ title="This session's agent process is gone (it did not exit cleanly) — click to resume the conversation"+ onClick={() => wakeHibernatedNode(session.id)}+ >+ DROPPED+ </button>+ )}{isTerminal && paused && (// Opening the card is one of the modal-open wake triggers `TerminalNode` publishes// (see `setKanbanModalNode`), and it deliberately skips a PAUSED node — so the modaldiff --git a/src/renderer/components/kanban/SessionCard.tsx b/src/renderer/components/kanban/SessionCard.tsxindex ea8e0e097..fee8b1936 100644--- a/src/renderer/components/kanban/SessionCard.tsx+++ b/src/renderer/components/kanban/SessionCard.tsx@@ -57,16 +57,22 @@ export const SessionCard = memo(function SessionCard({// SLEEPING (Eco: the agent CLI was exited to reclaim its RAM) is one more branch here, not a// follow-up. Ranked last: a hibernated node is idle by definition, so `working`/`waiting` can// only mean the wake already landed and the hooks are ahead of the flag.+ // DROPPED (the CLI died unannounced — see terminal/agent-liveness.ts) is ranked FIRST: it is the+ // strongest claim on the card, and it cannot actually collide with the others, since the verdict+ // is only ever raised on a `done` node that is neither paused nor hibernated. Ordering it here is+ // about which sentence a reader of this chain meets first, not about resolving a conflict.const badge =- session.kind !== 'sticky' && status?.state === 'working'- ? 'running'- : session.kind !== 'sticky' && (status?.state === 'waiting' || status?.state === 'blocked')- ? 'needs'- : session.kind !== 'sticky' && status?.paused- ? 'paused'- : session.kind !== 'sticky' && status?.hibernated- ? 'sleeping'- : null+ session.kind !== 'sticky' && status?.dropped+ ? 'dropped'+ : session.kind !== 'sticky' && status?.state === 'working'+ ? 'running'+ : session.kind !== 'sticky' && (status?.state === 'waiting' || status?.state === 'blocked')+ ? 'needs'+ : session.kind !== 'sticky' && status?.paused+ ? 'paused'+ : session.kind !== 'sticky' && status?.hibernated+ ? 'sleeping'+ : nullconst stickyPreview = session.kind === 'sticky' ? (session.text ?? '').trim() : ''const assignees = meta?.assignees ?? []const due = meta?.dueAt@@ -118,6 +124,14 @@ export const SessionCard = memo(function SessionCard({<span className="kanban-card__title">{session.title}</span>{session.kind === 'sticky' && <span className="kanban-card__kind">note</span>}{session.kind === 'browser' && <span className="kanban-card__kind">web</span>}+ {badge === 'dropped' && (+ <span+ className="kanban-badge kanban-badge--dropped"+ title="This session's agent process is gone (it did not exit cleanly) — open the card to resume it"+ >+ DROPPED+ </span>+ )}{badge === 'running' && <span className="kanban-badge kanban-badge--running">RUNNING</span>}{badge === 'needs' && <span className="kanban-badge kanban-badge--needs">NEEDS YOU</span>}{badge === 'paused' && (diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex dcb31b67a..472693909 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -126,6 +126,12 @@ import {type PauseOutcome,type ResumePhaseOutcome} from '../terminal/agent-restart'+import {+ looksDropped,+ looksDroppedCandidate,+ LIVENESS_POLL_MS,+ LIVENESS_QUERY_MS+} from '../terminal/agent-liveness'import { shouldAutoWake, shouldColdResume } from '../terminal/hibernation-policy'import { WakeInputBuffer } from '../terminal/wake-input-buffer'import { FindBar } from '../components/FindBar'@@ -1567,6 +1573,8 @@ export function TerminalNode({const wakeInputBufferRef = useRef(new WakeInputBuffer())const paneWriteRef = useRef<(data: string) => void>(() => {})const wakeRef = useRef<(attempt?: number) => void>(() => {})+ /** The liveness check's own asker, published by its effect for the reveal edge to call. */+ const livenessAskRef = useRef<(() => Promise<void>) | null>(null)wakeRef.current = (attempt = 0): void => {// A wake that could not run YET is retried a couple of times: at mount the spawn is still in// flight, and a node coming back from an offscreen DISPOSE re-registers its pair one render@@ -1584,7 +1592,12 @@ export function TerminalNode({// session instead, leaving `hibernated` unset), but either flag means there is a conversation// this closure knows how to bring back.const stNow = useAgentStatus.getState().byId[id]- if (!stNow?.hibernated && !stNow?.paused) return+ // `dropped` joins the two pause flags here because it is the same job with a different cause:+ // the pane holds a bare shell and there is a conversation this closure knows how to bring back.+ // The resume half is what makes it safe to admit — it re-reads the pane itself and refuses+ // anything that is not a shell, so a node whose CLI came back on its own between the verdict+ // and the click is declined rather than typed into.+ if (!stNow?.hibernated && !stNow?.paused && !stNow?.dropped) returnconst fns = agentHibernateFns(id)if (!fns) return retryLater() // no terminal here yet (mid-spawn, or an offscreen revive)wakeInFlightRef.current = true@@ -1600,6 +1613,9 @@ export function TerminalNode({if (outcome === 'resumed') {useAgentStatus.getState().setHibernated(id, false)useAgentStatus.getState().setPaused(id, false)+ // The resume line is in the pane; the CLI's own SessionStart will confirm it shortly, but+ // the chip must not survive the click that answered it.+ useAgentStatus.getState().setDropped(id, false)return}// 'not-eligible' — usually timing, not a refusal that will stand: at mount the spawn is@@ -1645,6 +1661,74 @@ export function TerminalNode({setNodeOffscreen(id, false)}}, [id])+ /**+ * LIVENESS — did this node's agent CLI die without telling us? (See `agent-liveness.ts` for the+ * rule and every refusal in it; this effect only supplies the pane reading and records the+ * verdict.)+ *+ * WHEN it asks is the whole cost story. `paneCommand` is one tmux `display-message` — measured at+ * 4 ms against a local socket, one exec channel on an existing ControlMaster for an SSH project —+ * but a canvas can hold fifty agent nodes, and fifty of anything on a timer is a background load+ * nobody asked for. So this asks only for a node that is BOTH watched (on screen, or a kanban+ * card modal is open on it) and already believed to be a parked agent: a `done` node that is+ * neither hibernated nor paused. Everything else costs one map lookup and no I/O.+ *+ * The cadence is deliberately coarser than the badge feels: the verdict is about a process that+ * is already gone and is not going to come back on its own, so re-asking fast buys nothing. The+ * reveal edge is what makes it feel immediate — the user looks at the node, and a check runs then.+ *+ * `null` (a lapsed or failed read) leaves the previous verdict ALONE rather than clearing it: a+ * ControlMaster that drops must not quietly retract a DROPPED chip and leave a dead session+ * looking healthy. `looksDropped` already refuses to raise one on `null`; this is the other half.+ */+ useEffect(() => {+ let stopped = false+ let asking = false+ const ask = async (): Promise<void> => {+ if (asking || stopped) return+ const st = useAgentStatus.getState().byId[id]+ // Cheap gate first, so a canvas of healthy or plain-terminal nodes never reaches the pane.+ // Note it admits an ALREADY-dropped node too: that is how the chip clears itself when the+ // user relaunches the CLI by hand (no hook has to arrive for the pane to answer).+ if (!st?.dropped && !looksDroppedCandidate(agentId, st?.state, st?.hibernated, st?.paused))+ return+ if (!isNodeWatched(id)) return+ asking = true+ try {+ const pane = await queryPaneWithin(() => api.pty.paneCommand(id), LIVENESS_QUERY_MS)+ if (stopped || pane === null) return+ // Re-read: the await is long enough for a turn to have started, or for the user to have+ // paused the node from the menu.+ const now = useAgentStatus.getState().byId[id]+ useAgentStatus+ .getState()+ .setDropped(+ id,+ looksDropped({+ agentId,+ state: now?.state,+ hibernated: now?.hibernated,+ paused: now?.paused,+ pane+ })+ )+ } catch {+ // Same contract as `null` — an unreadable pane is never evidence either way.+ } finally {+ asking = false+ }+ }+ // Published for the reveal edge below (the visibility observer is not a subscribable store, so+ // the edge calls this rather than this effect re-running on it). Identity-checked on clear.+ livenessAskRef.current = ask+ void ask()+ const t = setInterval(() => void ask(), LIVENESS_POLL_MS)+ return () => {+ stopped = true+ clearInterval(t)+ if (livenessAskRef.current === ask) livenessAskRef.current = null+ }+ }, [id, agentId, api])// Held launch (canvas-control `--after`). Canvas owns firing it; the node only surfaces that// it is armed, and by WHAT it is blocked — dep titles read straight off the live canvas, since// "waits for term-17" tells the user nothing.@@ -4087,6 +4171,11 @@ export function TerminalNode({const stVisible = useAgentStatus.getState().byId[id]if (visible && !wasVisible && shouldAutoWake(stVisible?.hibernated, stVisible?.paused))wakeRef.current()+ // …and the liveness check, for the same reason and on the same edge: a node whose CLI died+ // while nobody was looking should say so by the time the user has finished panning to it,+ // not on the interval's next tick. Cheap — the asker's own gate returns before any I/O for+ // a node that is not a parked agent.+ if (visible && !wasVisible) void livenessAskRef.current?.()// A visible node is not in an offscreen stretch at all — the next hidden edge starts a// fresh clock for the Eco deferral's cap.if (visible) offscreenSinceRef.current = null@@ -4897,7 +4986,26 @@ export function TerminalNode({revealing the node resumes the conversation. Clickable because the automatic wake canrefuse (a pane that now belongs to something else, a spawn that is still coming up),and a badge with no way forward is a dead end. Muted on purpose: nothing is wrong. */}- {status?.paused ? (+ {/* DROPPED: the CLI left this pane and nothing accounted for it — on a busy host, almost+ always the OOM killer. Unlike SLEEPING/PAUSED this is NOT a state we chose, so it reads+ in the warning colour: the conversation is still on disk, but nothing is running and+ nothing will resume it on its own. Clicking resumes it, through the same closure the+ hibernation wake uses. Ranked ABOVE the two pause chips because they are mutually+ exclusive by construction (`looksDropped` refuses a hibernated or paused node), so the+ ordering is about reading the JSX, not about resolving a conflict. */}+ {status?.dropped ? (+ <button+ className="term-node__status term-node__status--dropped nodrag"+ title="This session's agent process is gone (it did not exit cleanly) — click to resume the conversation"+ onClick={(e) => {+ e.stopPropagation()+ wakeRef.current()+ }}+ >+ <span className="term-node__status-dot" />+ DROPPED+ </button>+ ) : status?.paused ? (<buttonclassName="term-node__status term-node__status--paused nodrag"title="Session paused — click to resume"diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.tsindex 88378c0d7..6f8602598 100644--- a/src/renderer/state/agentStatus.ts+++ b/src/renderer/state/agentStatus.ts@@ -104,6 +104,20 @@ export interface AgentNodeStatus {* same reason: a live state is proof the CLI is running, so a standing `paused` would be wrong.*/paused?: boolean+ /**+ * This node's agent CLI left its pane and NOTHING accounted for it — no SessionEnd hook, no+ * `hibernated`, no `paused`. In practice: the process was killed (the OOM killer, a `pkill`, a+ * host that ran out of memory), or a cold-restore `--resume` failed and fell back to a bare+ * shell. The decision is the pure `terminal/agent-liveness.ts`; this field is only where the+ * node records the verdict so its header and the kanban card can render the DROPPED chip.+ *+ * TRANSIENT, like `state` and for a stronger reason than the other clocks: it is a claim about a+ * pane, and a pane's contents are re-measurable in milliseconds. Persisting it would let a stale+ * verdict survive into a run where the session had been resumed by hand — a chip on a healthy+ * node with nothing left to disprove it, since the check that would clear it only runs for nodes+ * it can still see.+ */+ dropped?: boolean/** Which agent this node is running (claude/codex/gemini/…), when known. */agentId?: AgentId/**@@ -221,6 +235,9 @@ export interface AgentStatusStore {* restarts the idle clock, same as `setHibernated` — a resumed session must not read as having* been idle since before the pause. */setPaused(id: string, on: boolean): void+ /** Record (or withdraw) the verdict that this node's CLI died unannounced. Transient; see+ * `dropped`. Cheap to call repeatedly — it bails when the flag already reads that way. */+ setDropped(id: string, on: boolean): void/** Record that this node just launched a background shell task (see `backgroundTaskAt`).* Transient — nothing is written to localStorage. */markBackgroundTask(id: string): void@@ -534,6 +551,12 @@ export function createAgentStatusSession(// the next deep pause to be typed into recognizing a pane it never measured.if (!next.hibernated) next.hibernatedPane = 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`+ // (a late Stop POST would undo a hibernation we just performed), but it absolutely does+ // disprove "this pane has no CLI in it". Nothing is saved — the flag is transient.+ if (prev.dropped) next.dropped = undefinedconst byId = { ...s.byId, [id]: next }// `state` itself is transient, so a plain transition writes nothing — but dropping a// PERSISTED flag has to reach disk, or a relaunch would restore a hibernated/paused node@@ -663,6 +686,18 @@ export function createAgentStatusSession(return { byId }}),+ setDropped: (id, on) =>+ set((s) => {+ const prev = s.byId[id] ?? EMPTY+ // Bail when nothing changes: the liveness check re-asks on every reveal and on a timer, so+ // the overwhelmingly common call is "still fine, still fine" — and a fresh entry object+ // each time would re-render the node (and the minimap) for no news.+ if (!!prev.dropped === on) return s+ // Transient: cleared by dropping the key, and NO `save()` — see the field comment. An entry+ // holding nothing else durable must not be conjured onto disk by a pane reading.+ return { byId: { ...s.byId, [id]: { ...prev, dropped: on ? true : undefined } } }+ }),+markBackgroundTask: (id) =>set((s) => {const prev = s.byId[id] ?? EMPTYdiff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 2a6cf04af..7088093b7 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -1670,6 +1670,26 @@ body,color: #bf7af0;}+/* DROPPED: the agent process is gone and nothing accounted for it (see agent-liveness.ts). Warn+ colour, not danger — the conversation is intact on disk and one click brings it back — and the+ dot does NOT pulse: nothing is happening, this is a verdict about a process that already died.+ A <button> like SLEEPING/PAUSED, so it needs the same base-chip reset. */+.term-node__status--dropped {+ color: var(--warn);+ background: none;+ border: none;+ padding: 0;+ font: inherit;+ font-size: 9.5px;+ font-weight: 700;+ letter-spacing: 0.06em;+ cursor: pointer;+}++.term-node__status--dropped:hover {+ color: var(--text);+}+/* SLEEPING: the agent CLI was exited to reclaim its RAM (Eco); the session itself is fine, sothis is the quietest chip on the header — grey, no pulse. It is a <button> (click = resume),which the base chip's styling does not cover. */@@ -9513,6 +9533,12 @@ button.group-node__setup:disabled {color: var(--muted);background: rgba(var(--tint-rgb), 0.08);}+/* The agent process is gone and nothing accounted for it. Warn-coloured like NEEDS YOU, because it+ does need the user — but for a different reason, which is why it gets its own label. */+.kanban-badge--dropped {+ color: var(--warn);+ background: rgba(255, 159, 10, 0.12);+}.kanban-card__unread {width: 7px;height: 7px;diff --git a/src/renderer/terminal/agent-liveness.test.ts b/src/renderer/terminal/agent-liveness.test.tsnew file mode 100644index 000000000..272964ed7--- /dev/null+++ b/src/renderer/terminal/agent-liveness.test.ts@@ -0,0 +1,99 @@+import { describe, it, expect } from 'vitest'+import fs from 'node:fs'+import path from 'node:path'+import { looksDropped, looksDroppedCandidate } from './agent-liveness'+import { SESSION_END_CAPABLE } from '@shared/agents/config'++const base = { agentId: 'claude', state: 'done', pane: 'bash' } as const++describe('looksDropped', () => {+ it('flags a done agent node whose pane fell back to a shell', () => {+ expect(looksDropped({ ...base })).toBe(true)+ })++ it('accepts the shells isShellCommand knows, login form included', () => {+ for (const pane of ['bash', 'zsh', '-zsh', 'fish', 'sh', '/bin/bash'])+ expect(looksDropped({ ...base, pane })).toBe(true)+ })++ // The signal's other half: something is still running in there.+ it('is silent while the agent still owns the pane', () => {+ for (const pane of ['claude', 'node', 'vim', 'npm'])+ expect(looksDropped({ ...base, pane })).toBe(false)+ })++ // An unreadable pane is the ControlMaster-is-down case. It must never manufacture a verdict.+ it('never fires on an unreadable pane', () => {+ expect(looksDropped({ ...base, pane: null })).toBe(false)+ })++ // Our own two exits already have their own chips; a third badge would alarm about a feature+ // working as designed.+ it('never fires on a session we ourselves exited', () => {+ expect(looksDropped({ ...base, hibernated: true })).toBe(false)+ expect(looksDropped({ ...base, paused: true })).toBe(false)+ })++ // THE false-positive guard. codex and opencode map no session-end event, so their clean `/quit`+ // is byte-identical to a kill and must stay unjudged.+ it('refuses agents whose hooks do not announce a session end', () => {+ expect(looksDropped({ ...base, agentId: 'codex' })).toBe(false)+ expect(looksDropped({ ...base, agentId: 'opencode' })).toBe(false)+ expect(looksDropped({ ...base, agentId: 'gemini' })).toBe(true)+ expect(looksDropped({ ...base, agentId: 'grok' })).toBe(true)+ })++ // A plain terminal is a shell in a pane by definition — the whole canvas would light up.+ it('refuses a node with no agent at all', () => {+ expect(looksDropped({ ...base, agentId: undefined })).toBe(false)+ })++ it('only judges a parked agent, never one mid-turn or holding a question', () => {+ // `working` is excluded because a tool subprocess can own the pane's foreground: the reading+ // would be a shell on a perfectly healthy agent.+ expect(looksDropped({ ...base, state: 'working' })).toBe(false)+ expect(looksDropped({ ...base, state: 'waiting' })).toBe(false)+ expect(looksDropped({ ...base, state: 'blocked' })).toBe(false)+ // Absent = the app-restart case and the post-SessionEnd (user typed /exit) case at once.+ expect(looksDropped({ ...base, state: undefined })).toBe(false)+ })+})++describe('looksDroppedCandidate', () => {+ it('admits exactly what looksDropped would, given a shell pane', () => {+ // The cheap pre-gate exists only to skip I/O, so it must never exclude something the full+ // predicate would have flagged — that would be a silently missing feature.+ const states = ['done', 'working', 'waiting', 'blocked', undefined]+ const agents = ['claude', 'codex', 'gemini', 'grok', 'opencode', undefined]+ for (const state of states)+ for (const agentId of agents)+ for (const hibernated of [true, false, undefined])+ for (const paused of [true, false, undefined])+ expect(looksDroppedCandidate(agentId, state, hibernated, paused)).toBe(+ looksDropped({ agentId, state, hibernated, paused, pane: 'bash' })+ )+ })+})++describe('SESSION_END_CAPABLE', () => {+ // The list is a CONSEQUENCE of normalize.ts, and its value is entirely in staying that way: an+ // id added here without the normalizer branch would put a DROPPED chip on every session its+ // owner quit on purpose. So assert it against the source it is derived from.+ it('holds exactly the agents whose normalizer maps a session end', () => {+ const src = fs+ .readFileSync(path.join(__dirname, '..', '..', 'shared', 'agents', 'normalize.ts'), 'utf8')+ .replace(/\r\n/g, '\n')+ // Each normalizer is `export function normalizeX(...)`; slice the file at those boundaries and+ // ask which slices contain a session-end mapping.+ const marks = [...src.matchAll(/export function normalize([A-Z]\w*)\(/g)]+ const withEnd = marks+ .filter((m, i) => {+ const body = src.slice(m.index, marks[i + 1]?.index ?? src.length)+ return /sessionPhase: 'end'/.test(body)+ })+ .map((m) => m[1].toLowerCase())+ // `normalizeFor` is the dispatcher, not an agent.+ .filter((n) => n !== 'for')+ expect(withEnd.sort()).toEqual([...SESSION_END_CAPABLE].sort())+ })+})diff --git a/src/renderer/terminal/agent-liveness.ts b/src/renderer/terminal/agent-liveness.tsnew file mode 100644index 000000000..ccf83b6c6--- /dev/null+++ b/src/renderer/terminal/agent-liveness.ts@@ -0,0 +1,117 @@+/**+ * DID THIS NODE'S AGENT CLI DIE WITHOUT TELLING US? — the pure decision behind the DROPPED chip.+ *+ * Every ORDERLY way an agent CLI leaves its pane announces itself. Our own Eco `/exit` sets+ * `hibernated`; the manual "Pause session" sets `paused`; a user typing `/exit` themselves fires+ * the CLI's own SessionEnd hook, which `setState(id, undefined)` records as "no agent here now".+ * A kill announces nothing: the process is gone before it can run a hook, and because tmux's own+ * shell owns the pane, the PTY stays open and the node keeps rendering whatever badge it had. The+ * user is left with a live-looking card over a dead conversation, and — for Claude — the CLI's+ * parting "Resume this session with: claude --resume <uuid>" line plus a stray `^[%` sitting in+ * the pane as the only evidence.+ *+ * Measured on the host that prompted this (2026-09-04): 62 GB RAM with swap fully consumed, the+ * kernel's `oom_kill` counter at 187, and 147 live `claude` processes holding 44 GB. A session+ * dying under memory pressure is not an exotic case on a canvas this size — it is the normal+ * outcome. In the same sweep, 9 of 149 panes sat at a bare shell after a cold-restore+ * `claude --resume <id>` answered "No conversation found with session ID", which this same+ * predicate catches: the CLI is gone and nothing accounted for it, whichever way it went.+ *+ * THE SIGNAL is `#{pane_current_command}` reading as a shell while the status table still believes+ * an agent is sitting there. Each half is necessary and neither is sufficient, and the four+ * refusals below are what keep it from crying wolf — a false DROPPED is worse than no chip at all,+ * because the offered Resume would splice a second CLI into a pane that already has one.+ */+import { isShellCommand } from '@shared/agents/pane'+import { reportsSessionEnd } from '@shared/agents/config'++/**+ * How long one pane reading may take before it counts as unreadable. Generous next to the restart+ * poll's own budget because nothing waits on this answer — no line is about to be typed, and a+ * slow ControlMaster should postpone a badge, never mislabel a session.+ */+export const LIVENESS_QUERY_MS = 6000++/**+ * How often a WATCHED, parked agent node re-asks. Coarse on purpose: the thing being detected is a+ * process that has already died and cannot un-die, so the only thing a faster tick buys is load on+ * somebody's ssh master. The reveal edge is what makes the badge feel prompt.+ */+export const LIVENESS_POLL_MS = 30_000++/**+ * The cheap half of `looksDropped`: everything decidable WITHOUT reading the pane. Callers use it+ * to avoid paying for a tmux round trip on a node that could not be dropped whatever the pane says+ * — a plain terminal, a working agent, a node we hibernated ourselves.+ *+ * Kept beside `looksDropped` and asking the same questions in the same order so the two cannot+ * drift into disagreeing about who is a candidate (pinned by an exhaustive test). The full+ * predicate re-checks every one of these against a freshly read status, because the pane read is+ * an await and a turn can start inside it.+ */+export function looksDroppedCandidate(+ agentId: string | undefined,+ state: string | undefined,+ hibernated: boolean | undefined,+ paused: boolean | undefined+): boolean {+ if (hibernated || paused) return false+ if (!agentId || !reportsSessionEnd(agentId)) return false+ return state === 'done'+}++export interface DroppedCheckInput {+ /** The agent this node was CREATED as (`data.agentId`), not a guess from the pane. */+ agentId?: string+ /** The node's live agent state (`agentStatus.byId[id].state`) — TRANSIENT by design. */+ state?: string+ /** Our own Eco exit put the pane in this state. */+ hibernated?: boolean+ /** The manual "Pause session" put the pane in this state. */+ paused?: boolean+ /**+ * `#{pane_current_command}`, or `null` when the pane could not be read (tmux off, a dead+ * ControlMaster, a lapsed query). `null` is never evidence — the same contract+ * `queryPaneWithin` publishes.+ */+ pane: string | null+}++/**+ * Did this node's agent CLI leave its pane without any of the orderly exits accounting for it?+ *+ * Every `false` below is a deliberate refusal:+ *+ * - **`pane === null` is not evidence.** A lapsed or failed pane query means "we cannot see this+ * pane right now", never "nothing is running in it" — the rule `queryPaneWithin` already sets+ * for the restart poll, and the reason a downed ControlMaster cannot make a canvas full of+ * healthy remote nodes claim they died.+ * - **`hibernated` / `paused` are OUR OWN exits.** The pane is a shell because we asked it to be.+ * Those two already have chips (SLEEPING / PAUSED) that say so and resume on click; a third+ * badge over the same fact would be an alarm about a feature working.+ * - **The agent must report a session end** (`reportsSessionEnd`). This is the gate that keeps a+ * user's own `/exit` from reading as a crash, and it is a MEASURED per-agent fact, not a+ * courtesy: `normalize.ts` maps a session-end for claude, gemini, copilot and grok, and maps+ * none at all for **codex and opencode**. On those two a clean manual quit leaves `state` at+ * `done` and the pane at a shell — byte-identical to a kill — so there is nothing here to tell+ * the two apart and this module refuses to guess. Widening the list without adding the+ * normalizer branch first would put a DROPPED chip on every codex session its owner quit on+ * purpose.+ * - **Only `done`, never `working`.** `done` is the one state that means "the CLI is parked at+ * its own prompt", where a shell reading has no innocent explanation. `working` is excluded+ * even though a mid-turn kill is the likeliest way to die: a turn in flight is exactly when a+ * tool subprocess can own the pane's foreground, and `pane_current_command` would report that+ * subprocess — so the alarm would fire on a perfectly healthy agent running a shell command.+ * `waiting`/`blocked` are excluded for the plainer reason that they already carry a NEEDS YOU+ * badge the user is being called back for. An ABSENT state (`undefined`) is the app-restart+ * case and the post-SessionEnd case at once, and neither is a crash.+ *+ * Note what this deliberately does NOT try to detect: a session whose CLI died BEFORE the app was+ * restarted. `state` is transient, so after a relaunch there is no belief left to contradict, and+ * inventing one from the pane alone would flag every plain terminal on the canvas.+ */+export function looksDropped(i: DroppedCheckInput): boolean {+ if (i.pane === null) return false+ if (!isShellCommand(i.pane)) return false+ return looksDroppedCandidate(i.agentId, i.state, i.hibernated, i.paused)+}diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.tsindex 508258635..a48f4eaed 100644--- a/src/shared/agents/config.ts+++ b/src/shared/agents/config.ts@@ -202,6 +202,21 @@ export const CHAT_CAPABLE = ['claude', 'grok'] as constexport const CLAUDE_TRANSCRIPT_READABLE = ['claude'] as const// Agents whose native transcript we can read + render for cross-agent transfer.export const TRANSFER_SOURCE_CAPABLE = ['claude', 'codex', 'gemini', 'grok'] as const+// Agents whose hooks announce that a session ENDED — i.e. whose orderly `/exit` we will hear about.+//+// Derived by reading `normalize.ts`, not by intent: exactly four normalizers map an event to+// `sessionPhase: 'end'` (claude `SessionEnd`, gemini `SessionEnd`, copilot `SessionEnd`, grok+// `sessionend`). `normalizeCodex` and `normalizeOpencode` map none, which is why they are absent+// here — and their absence is load-bearing, not an oversight to tidy up later.+//+// What it gates today is the DROPPED chip (`terminal/agent-liveness.ts`): "the pane went back to a+// shell but nobody told us the session ended" is only evidence of a CRASH for an agent that WOULD+// have told us. On codex and opencode a deliberate `/quit` and an OOM kill leave byte-identical+// evidence, so a chip there could only be a coin flip shown as a fact.+//+// Before adding an id: find its normalizer's `sessionPhase: 'end'` branch. If there isn't one, the+// branch is the change — this list is a consequence of it, never a substitute for it.+export const SESSION_END_CAPABLE = ['claude', 'gemini', 'copilot', 'grok'] as const// Agents that accept a node title being PUSHED back into the session — the write leg only. The// write is the same literal `/rename <name>` for both, which grok also accepts as `/title`.// The READ leg is TITLE_READ_CAPABLE below, which is a superset: an agent can name its own session@@ -367,6 +382,9 @@ export const canChat = (id: AgentId): boolean => includes(CHAT_CAPABLE, id)export const readsClaudeShapedTranscript = (id: AgentId): boolean =>includes(CLAUDE_TRANSCRIPT_READABLE, id)export const canTransferFrom = (id: AgentId): boolean => includes(TRANSFER_SOURCE_CAPABLE, id)+/** Will this agent's hooks tell us when its session ends? See SESSION_END_CAPABLE — the honest+ * answer for codex and opencode is no, and callers must degrade rather than assume a crash. */+export const reportsSessionEnd = (id: AgentId): boolean => includes(SESSION_END_CAPABLE, id)export const canRename = (id: AgentId): boolean => includes(RENAME_CAPABLE, id)export const canReadTitle = (id: AgentId): boolean => includes(TITLE_READ_CAPABLE, id)export const canControlCanvas = (id: AgentId): boolean => includes(CANVAS_CONTROL_CAPABLE, id)