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(subagents): a new turn clears only the FINISHED cards

enes3181ad454737
diff --git a/CLAUDE.md b/CLAUDE.md
index 588ebeaec..04bbb5f08 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1389,8 +1389,24 @@ else, and its context links must keep classifying across restarts).
as an **ephemeral** `SubagentNode` (display-only card: type + task + working/done) connected by
an **edge** to its parent agent node. These ephemeral nodes/edges live outside the React Flow
`nodes` state (merged only at the `<ReactFlow>` prop), so they're never persisted
- (`flowToNodeStates`) nor in undo/dirty. Fan-out is cleared on the next new turn / session-end /
- node close. (Subagents share the parent's process — no PTY.) Each card shows
+ (`flowToNodeStates`) nor in undo/dirty. **Two different clears, and the difference is
+ load-bearing (issue #547):** the removal paths (node delete, project delete, the cross-project
+ close, the orphan-session kill, `SessionEnd`) call `clearForParent`, which drops everything —
+ a node that is gone has no work left to represent. A **new turn** calls
+ `clearFinishedForParent`, which drops only `state === 'done'`. "The previous fan-out is stale by
+ definition" is true of a finished card and false of a working one: Claude launches subagents
+ **async**, so *"waiting for N background agents to finish"* is exactly the state in which the
+ next prompt gets typed, and nothing rehydrates `byId` afterwards (`start()` fires only from a
+ live `PreToolUse`; a subagent past that emits no second one) — the card was gone for the rest of
+ the run while the agent kept working. The expensive half is not the missing card: Eco's
+ hibernation guard derives `liveSubagents` from this same store, so the wipe let a parent with
+ live background agents read as idle and get its CLI `/exit`ed. Keeping an unfinished card then
+ **owes a decay** — `useAgentNodes.sweepStaleWorking`, on the same 60 s tick and the same
+ `WORKING_STALE_MS` as `agentStatus`'s (imported, never re-chosen: `shared/agents/stale.ts` exists
+ because three surfaces each invented their own timeout) — or a subagent whose end never arrives
+ pins its card, and its parent, forever. It marks the card **done** rather than deleting it, so a
+ late `finish()` is the no-op it already was and the next turn boundary takes it.
+ (Subagents share the parent's process — no PTY.) Each card shows
duration/tokens/tool-uses and **expands** (click) to a **live transcript**:
`core/subagent-tail.ts` resolves the subagent's own transcript file
(`<…>/<sessionId>/subagents/agent-<id>.jsonl`, matched by `tool_use_id` via the sibling
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index e438ba49a..d99734398 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -11036,7 +11036,12 @@ export function Canvas() {
// it was in scope here and dropped on the floor before the store had a field for it.
if (e.state && !stuckRescueSkip)
cs.setState(e.nodeId, e.state, e.agentId, e.newTurn, e.pendingId, e.verified)
- if (e.newTurn) an.clearForParent(e.nodeId) // genuine new turn → drop the previous fan-out
+ // A genuine new turn drops the previous fan-out — but only the cards that FINISHED
+ // (issue #547). Claude launches subagents async, so "waiting for N background agents to
+ // finish" is exactly the state in which the next prompt gets typed, and clearing a
+ // working card there loses it permanently (nothing rehydrates `byId`) while the agent
+ // keeps running — and blinds Eco's live-subagent guard into hibernating its parent.
+ if (e.newTurn) an.clearFinishedForParent(e.nodeId)
if (e.newTurn && e.task) {
// Prompt-prefix fallback for /loop|/schedule|/cron when the natural-language
// phrasing doesn't trigger the tool-based (recurring) detection.
@@ -11132,8 +11137,15 @@ export function Canvas() {
// Safety net for a lost Stop POST / crashed CLI: decay working entries that saw no hook
// event at all for STALE_WORKING_MS (the sweep itself is cheap; see agentStatus.ts).
+ //
+ // The subagent cards decay on the SAME tick and the same number (issue #547): now that a turn
+ // boundary keeps an unfinished card, a subagent whose end never arrives would otherwise pin its
+ // card — and, through Eco's `liveSubagents`, its parent — forever.
useEffect(() => {
- const t = setInterval(() => useAgentStatus.getState().sweepStaleWorking(), 60_000)
+ const t = setInterval(() => {
+ useAgentStatus.getState().sweepStaleWorking()
+ useAgentNodes.getState().sweepStaleWorking()
+ }, 60_000)
return () => clearInterval(t)
}, [])
diff --git a/src/renderer/state/agentNodes.ts b/src/renderer/state/agentNodes.ts
index edb452ee4..14b271950 100644
--- a/src/renderer/state/agentNodes.ts
+++ b/src/renderer/state/agentNodes.ts
@@ -1,4 +1,5 @@
import { create } from 'zustand'
+import { WORKING_STALE_MS } from '@shared/agents/stale'
/**
* Transient visualization of subagents a Claude node spawns (Task/Agent tool), keyed by the
@@ -67,8 +68,49 @@ interface AgentNodesState {
finish(toolUseId: string, result: SubagentResult): void
/** Append a chunk of the subagent's live transcript. */
appendActivity(toolUseId: string, chunk: string): void
- /** Remove all subagents spawned by a given parent node (turn/session ended, or node closed). */
+ /**
+ * Remove ALL subagents spawned by a given parent node, finished or not.
+ *
+ * For the paths where the parent itself is gone or its session has ended — node deleted, project
+ * deleted, cross-project close, orphan-session kill, `SessionEnd`. A node that no longer exists
+ * has no work left to represent, so there is nothing to preserve.
+ *
+ * **NOT for a turn boundary** — see `clearFinishedForParent` and issue #547.
+ */
clearForParent(parentNodeId: string): void
+ /**
+ * Drop only the FINISHED subagent cards of a parent. The turn-boundary clear.
+ *
+ * Issue #547: `clearForParent` ran on every new turn on the assumption that the previous fan-out
+ * is stale by definition. That holds for a card whose subagent has finished and is false for one
+ * that has not — Claude launches subagents async, and "waiting for N background agents to finish"
+ * is exactly the state in which the user types the next prompt. The card vanished permanently
+ * (nothing rehydrates `byId`: `start()` fires only from a live `PreToolUse`, and a subagent past
+ * that emits no second one) while the agent kept working. Same permanent loss as #402, different
+ * trigger.
+ *
+ * The more expensive half is not the missing card. Eco's hibernation guard derives `liveSubagents`
+ * from this same store, so a wiped card let a parent with live background agents read as idle and
+ * get its CLI `/exit`ed — the regression #402 was raised to close.
+ *
+ * `state` already draws the line the fix needs (`'working' | 'done'`, `finish()` idempotent), so
+ * this needs no new concept. What it does need is the decay: see `sweepStaleWorking`.
+ */
+ clearFinishedForParent(parentNodeId: string): void
+ /**
+ * Mark every card still `working` past `staleMs` as done — the decay `clearFinishedForParent`
+ * depends on.
+ *
+ * Without it a subagent whose `finish()` never arrives (crashed CLI, killed pane, slept machine)
+ * pins its card forever AND pins its parent against Eco forever, which is a worse bug than the
+ * one being fixed. The number is `WORKING_STALE_MS`, imported rather than chosen: that module
+ * exists because three surfaces each invented their own timeout, and a subagent card inventing a
+ * fourth would be the same mistake in a new place.
+ *
+ * It marks done rather than deleting, so the card stays readable and the next turn boundary takes
+ * it; `finish()` landing late is a no-op on an entry that is already done.
+ */
+ sweepStaleWorking(now?: number, staleMs?: number): void
/**
* Drop every dragged position/size/expanded override for a parent's subagent cards, snapping
* them back to the default packed grid (`offsetFrom`'s fallback in Canvas) at base dims — an
@@ -107,6 +149,37 @@ function loadLoopOverrides(): Overrides {
}
}
+/** Card ids belonging to one parent. */
+function cardsOf(s: AgentNodesState, parentNodeId: string): string[] {
+ return Object.keys(s.byId).filter((id) => s.byId[id].parentNodeId === parentNodeId)
+}
+
+/**
+ * Drop the given cards and everything keyed by their ids. The one removal body, so the
+ * unconditional clear and the turn-boundary clear cannot drift in what they take with them.
+ */
+function dropCards(s: AgentNodesState, ids: string[]): Partial<AgentNodesState> | AgentNodesState {
+ if (!ids.length) return s
+ const byId = { ...s.byId }
+ const activityById = { ...s.activityById }
+ const positions = { ...s.positions }
+ const sizes = { ...s.sizes }
+ const expanded = { ...s.expanded }
+ // Loop-card overrides (`loop-<pid>`) are deliberately NOT dropped here — the card outlives turns;
+ // its overrides go via clearLoop when the loop itself ends.
+ for (const id of ids) {
+ delete byId[id]
+ delete activityById[id]
+ delete positions[id]
+ delete sizes[id]
+ delete expanded[id]
+ }
+ // A card that just vanished must not stay "selected" — a later card reusing the id would come
+ // back pre-selected.
+ const selectedId = s.selectedId && ids.includes(s.selectedId) ? null : s.selectedId
+ return { byId, activityById, positions, sizes, expanded, selectedId }
+}
+
function saveLoopOverrides(s: Overrides): void {
try {
const pick = <T>(m: Record<string, T>): Record<string, T> =>
@@ -180,27 +253,25 @@ export const useAgentNodes = create<AgentNodesState>((set) => ({
return { activityById: { ...s.activityById, [toolUseId]: activity } }
}),
- clearForParent: (parentNodeId) =>
+ clearForParent: (parentNodeId) => set((s) => dropCards(s, cardsOf(s, parentNodeId))),
+
+ clearFinishedForParent: (parentNodeId) =>
+ set((s) => dropCards(s, cardsOf(s, parentNodeId).filter((id) => s.byId[id].state === 'done'))),
+
+ sweepStaleWorking: (now = Date.now(), staleMs = WORKING_STALE_MS) =>
set((s) => {
- const ids = Object.keys(s.byId).filter((id) => s.byId[id].parentNodeId === parentNodeId)
+ const stale = Object.keys(s.byId).filter(
+ (id) => s.byId[id].state === 'working' && now - s.byId[id].startedAt > staleMs
+ )
+ if (!stale.length) return s
const byId = { ...s.byId }
- const activityById = { ...s.activityById }
- const positions = { ...s.positions }
- const sizes = { ...s.sizes }
- const expanded = { ...s.expanded }
- // Loop-card overrides (`loop-<pid>`) are deliberately NOT dropped here — the card
- // outlives turns; its overrides go via clearLoop when the loop itself ends.
- for (const id of ids) {
- delete byId[id]
- delete activityById[id]
- delete positions[id]
- delete sizes[id]
- delete expanded[id]
+ for (const id of stale) {
+ const prev = byId[id]
+ // No result to report — the completion signal is what went missing. The elapsed time is
+ // still true, and it is `finish()`'s own fallback for the async case.
+ byId[id] = { ...prev, state: 'done', durationMs: prev.durationMs ?? now - prev.startedAt }
}
- // A card that just vanished must not stay "selected" — a later card reusing the id would
- // come back pre-selected.
- const selectedId = s.selectedId && ids.includes(s.selectedId) ? null : s.selectedId
- return { byId, activityById, positions, sizes, expanded, selectedId }
+ return { byId }
}),
tidyFanout: (parentNodeId) =>
diff --git a/src/renderer/state/agentNodes.turn-boundary.test.ts b/src/renderer/state/agentNodes.turn-boundary.test.ts
new file mode 100644
index 000000000..5d431fba6
--- /dev/null
+++ b/src/renderer/state/agentNodes.turn-boundary.test.ts
@@ -0,0 +1,187 @@
+// Issue #547 — the turn boundary must not take a subagent that is still running with it.
+//
+// `clearForParent` ran on every new turn on the assumption that the previous fan-out is stale by
+// definition. That is true of a FINISHED card and false of a working one: Claude launches subagents
+// async, and "waiting for N background agents to finish" is exactly the state in which the next
+// prompt gets typed. Nothing rehydrates `byId` afterwards — `start()` fires only from a live
+// `PreToolUse` and a subagent past that emits no second one — so the card was gone for the rest of
+// the run while the agent kept working.
+//
+// The more expensive half is the Eco consequence, which is why `buildHibernationCandidates` is
+// exercised here rather than left to the store test above it: the guard's evidence ("any card that
+// has not finished pins its parent") is derived from this same store, so the wipe let a parent with
+// live background agents read as idle and get its CLI `/exit`ed.
+import { beforeEach, describe, expect, it } from 'vitest'
+import { useAgentNodes } from './agentNodes'
+import { buildHibernationCandidates } from '../lib/hibernationCandidates'
+import { WORKING_STALE_MS } from '@shared/agents/stale'
+
+const reset = (): void => {
+ useAgentNodes.setState({
+ byId: {},
+ activityById: {},
+ positions: {},
+ sizes: {},
+ expanded: {},
+ selectedId: null
+ })
+}
+
+describe('clearFinishedForParent — the turn boundary (issue #547)', () => {
+ beforeEach(reset)
+
+ it('keeps a card whose subagent is still working', () => {
+ const s = useAgentNodes.getState()
+ s.start('tu-running', { parentNodeId: 'n1', label: 'audit the parser' })
+ s.clearFinishedForParent('n1')
+ expect(useAgentNodes.getState().byId['tu-running']?.state).toBe('working')
+ })
+
+ it('drops the finished ones in the same pass', () => {
+ const s = useAgentNodes.getState()
+ s.start('tu-done', { parentNodeId: 'n1' })
+ s.start('tu-running', { parentNodeId: 'n1' })
+ s.finish('tu-done', { tokens: 10 })
+ s.clearFinishedForParent('n1')
+ const { byId } = useAgentNodes.getState()
+ expect(Object.keys(byId)).toEqual(['tu-running'])
+ })
+
+ it('takes the dropped card’s overrides and leaves the kept card’s alone', () => {
+ const s = useAgentNodes.getState()
+ s.start('tu-done', { parentNodeId: 'n1' })
+ s.start('tu-running', { parentNodeId: 'n1' })
+ s.finish('tu-done', {})
+ s.setPosition('tu-done', { x: 1, y: 1 })
+ s.setPosition('tu-running', { x: 2, y: 2 })
+ s.appendActivity('tu-running', 'still going')
+ s.clearFinishedForParent('n1')
+ const st = useAgentNodes.getState()
+ expect(st.positions['tu-done']).toBeUndefined()
+ expect(st.positions['tu-running']).toEqual({ x: 2, y: 2 })
+ expect(st.activityById['tu-running']).toBe('still going')
+ })
+
+ it('touches no other parent', () => {
+ const s = useAgentNodes.getState()
+ s.start('tu-a', { parentNodeId: 'n1' })
+ s.start('tu-b', { parentNodeId: 'n2' })
+ s.finish('tu-b', {})
+ s.clearFinishedForParent('n1')
+ expect(useAgentNodes.getState().byId['tu-b']).toBeDefined()
+ })
+
+ it('a kept card still accepts its late finish()', () => {
+ // The #402 property this rests on: `finish()` must land on an entry that was KEPT rather than
+ // cleared. If the card had been dropped, the end event would have nothing to write to.
+ const s = useAgentNodes.getState()
+ s.start('tu1', { parentNodeId: 'n1' })
+ s.clearFinishedForParent('n1')
+ useAgentNodes.getState().finish('tu1', { tokens: 42 })
+ expect(useAgentNodes.getState().byId['tu1']).toMatchObject({ state: 'done', tokens: 42 })
+ })
+
+ it('clearForParent is still unconditional — the removal paths lose nothing', () => {
+ // deleteNodes / deleteProject / the cross-project close / the orphan kill / SessionEnd: the node
+ // is gone, so there is no work left to represent.
+ const s = useAgentNodes.getState()
+ s.start('tu1', { parentNodeId: 'n1' })
+ s.clearForParent('n1')
+ expect(useAgentNodes.getState().byId['tu1']).toBeUndefined()
+ })
+
+ it('the selection follows the card that was actually dropped', () => {
+ const s = useAgentNodes.getState()
+ s.start('tu-done', { parentNodeId: 'n1' })
+ s.start('tu-running', { parentNodeId: 'n1' })
+ s.finish('tu-done', {})
+ s.select('tu-running')
+ s.clearFinishedForParent('n1')
+ expect(useAgentNodes.getState().selectedId).toBe('tu-running')
+ useAgentNodes.getState().finish('tu-running', {})
+ useAgentNodes.getState().clearFinishedForParent('n1')
+ expect(useAgentNodes.getState().selectedId).toBeNull()
+ })
+})
+
+describe('sweepStaleWorking — the decay a kept card owes', () => {
+ beforeEach(reset)
+
+ it('marks a card working past WORKING_STALE_MS as done', () => {
+ // Required, not optional: a subagent whose end never arrives (crashed CLI, killed pane, slept
+ // machine) would otherwise pin its card — and its parent, against Eco — forever, which is worse
+ // than the bug being fixed.
+ const s = useAgentNodes.getState()
+ s.start('tu1', { parentNodeId: 'n1' })
+ const startedAt = useAgentNodes.getState().byId['tu1'].startedAt
+ s.sweepStaleWorking(startedAt + WORKING_STALE_MS + 1)
+ const card = useAgentNodes.getState().byId['tu1']
+ expect(card.state).toBe('done')
+ expect(card.durationMs).toBeGreaterThan(WORKING_STALE_MS)
+ })
+
+ it('leaves a card that is merely young alone', () => {
+ const s = useAgentNodes.getState()
+ s.start('tu1', { parentNodeId: 'n1' })
+ const startedAt = useAgentNodes.getState().byId['tu1'].startedAt
+ s.sweepStaleWorking(startedAt + WORKING_STALE_MS - 1)
+ expect(useAgentNodes.getState().byId['tu1'].state).toBe('working')
+ })
+
+ it('does not overwrite a real finish', () => {
+ const s = useAgentNodes.getState()
+ s.start('tu1', { parentNodeId: 'n1' })
+ s.finish('tu1', { durationMs: 500, result: 'ok' })
+ s.sweepStaleWorking(Date.now() + WORKING_STALE_MS * 10)
+ expect(useAgentNodes.getState().byId['tu1']).toMatchObject({ durationMs: 500, result: 'ok' })
+ })
+
+ it('a decayed card is then taken by the next turn boundary', () => {
+ const s = useAgentNodes.getState()
+ s.start('tu1', { parentNodeId: 'n1' })
+ const startedAt = useAgentNodes.getState().byId['tu1'].startedAt
+ s.sweepStaleWorking(startedAt + WORKING_STALE_MS + 1)
+ useAgentNodes.getState().clearFinishedForParent('n1')
+ expect(useAgentNodes.getState().byId['tu1']).toBeUndefined()
+ })
+})
+
+describe('Eco still sees the live subagent after a new turn (issue #547)', () => {
+ beforeEach(reset)
+
+ const candidates = () =>
+ buildHibernationCandidates({
+ nodes: [{ id: 'n1', agentId: 'claude' }],
+ statusById: { n1: { state: 'done', unread: false } },
+ subagents: Object.values(useAgentNodes.getState().byId).map((v) => ({
+ parentNodeId: v.parentNodeId,
+ status: v.state
+ })),
+ isOffscreen: () => true,
+ isRemote: () => false,
+ isWired: () => true
+ })
+
+ it('pins the parent while a background agent is still running', () => {
+ const s = useAgentNodes.getState()
+ s.start('tu1', { parentNodeId: 'n1' })
+ s.clearFinishedForParent('n1') // the new turn
+ expect(candidates()[0].liveSubagents).toBe(true)
+ })
+
+ it('stops pinning once the card finishes and the turn boundary takes it', () => {
+ const s = useAgentNodes.getState()
+ s.start('tu1', { parentNodeId: 'n1' })
+ s.finish('tu1', {})
+ s.clearFinishedForParent('n1')
+ expect(candidates()[0].liveSubagents).toBe(false)
+ })
+
+ it('stops pinning after the decay, so a lost end cannot block Eco forever', () => {
+ const s = useAgentNodes.getState()
+ s.start('tu1', { parentNodeId: 'n1' })
+ const startedAt = useAgentNodes.getState().byId['tu1'].startedAt
+ s.sweepStaleWorking(startedAt + WORKING_STALE_MS + 1)
+ expect(candidates()[0].liveSubagents).toBe(false)
+ })
+})