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.

refactor(agent-status): extract the listener's store writes into applyAgentEvent

review4fafbb9f7e6d
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 7fdd15d28..01861c717 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -22,7 +22,6 @@ import { useContextLinkSync } from './useContextLinkSync'
import { useMirrorIdentitySeed } from './useMirrorIdentitySeed'
import { useShallow } from 'zustand/react/shallow'
import { playSfx, primeSfx } from '@renderer/lib/sfx'
-import { fanoutStillWorking } from '@renderer/lib/completionAlert'
import { publishCanvasZoom } from '@renderer/lib/canvasZoomVar'
import {
addEdge,
@@ -528,7 +527,8 @@ import {
writeSeenExplorerPinHint
} from '../lib/explorerPinHint'
import { addRelayTab, sameSshEndpoint, setKanbanPublishHook, setStoredCanvasPublishHook, useProjects } from '../state/projects'
-import { useAgentStatus, recordsTurnInterrupt } from '../state/agentStatus'
+import { useAgentStatus } from '../state/agentStatus'
+import { applyAgentEvent } from '../state/applyAgentEvent'
import { countUnreadInProjects, orphanStatusIds, unreadIdSet, unreadIdsSig } from '../lib/unreadBadge'
import { usePendingPause, startPendingPauseWatcher } from '../state/pendingPause'
import {
@@ -17276,18 +17276,6 @@ export function Canvas() {
}
return api.onAgentStatus((e: NormalizedAgentEvent) => {
const cs = useAgentStatus.getState()
- if (e.sessionId) cs.setSessionId(e.nodeId, e.sessionId)
- // Which Claude account the posting session is ACTUALLY on — a hook-derived LABEL, captured
- // off any event that carries one, exactly like `sessionId` above: a plain terminal running
- // `CLAUDE_CONFIG_DIR=~/.claude-2 claude` announces its identity nowhere else.
- //
- // The `remote` flag is stamped HERE and nowhere else. The classifier in core is deliberately
- // host-agnostic — two of its rules exist precisely to name a REMOTE dir — and core holds only
- // the hook payload, which never says which machine posted it. This listener is the first
- // layer that can ask, because it can reach the node and the project that owns it, and a dir
- // that names another machine's filesystem must not reach any LOCAL affordance (see
- // `observationIsRemote` and the consumers in lib/accountChip.ts).
- if (e.account) cs.setAccount(e.nodeId, { ...e.account, remote: observationIsRemote(originOf(e.nodeId)) })
const agentLabel = agentConfig(e.agentId)?.label ?? 'Agent'
// "<folder> — Claude finished" + last assistant message as the body.
const alert = (
@@ -17339,153 +17327,22 @@ export function Canvas() {
nodeId: e.nodeId
})
}
- const an = useAgentNodes.getState()
- switch (e.kind) {
- case 'state': {
- // An `idle` done (the CLI went quiet at its prompt — see normalize) is a RESCUE for a
- // node stuck on `working` after an Esc that ran no turn-end hook. It may ONLY move a
- // working node: blocked/waiting is also "idle at the prompt", and clearing it there
- // would drop a live approval off the badge. Same rule as the mirror's reduceEntry.
- const stuckRescueSkip = e.idle === true && cs.byId[e.nodeId]?.state !== 'working'
- // `pendingId` (deterministic approvals) rides a `blocked` event; the store keeps it only
- // while blocked so the header's Approve/Deny buttons appear + vanish with the state.
- // `e.verified` is the identity evidence for this very transition (hook-server labels it);
- // 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,
- e.errored,
- e.held,
- recordsTurnInterrupt(e)
- )
- // Claude's Stop names the BACKGROUND tasks still running (async subagents, nested ones,
- // background shells). A background subagent that ends its turn while its own work runs
- // fires SubagentStop — its card goes done — and is resumed later, so the card alone would
- // let Eco or the bulk restart type /exit over live work. The existing background-task
- // stamp is the guard both already read; a turn start clears it, the next Stop re-decides.
- if (e.state === 'done' && !stuckRescueSkip && e.backgroundTaskIds?.length) cs.markBackgroundTask(e.nodeId)
- // 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.
- const m = e.task.match(/^\s*\/(loop|schedule|cron)\b/)
- if (m) cs.setLoop(e.nodeId, true, m[1] as 'loop' | 'schedule' | 'cron', { task: e.task })
- }
- if (e.state === 'done' && !e.interrupted && !stuckRescueSkip) {
- // Interrupted turns (Esc/Ctrl-C) alert nobody: the user did it themselves, and
- // the turn didn't complete, so it isn't a loop iteration either.
- // An IGNORED rescue is silent for the same reason it moves no badge: it claims a turn
- // ended for a node this surface never saw running, so the "finished" is unfounded —
- // and it arrives from a second source of truth (the main-process mirror drives the SSH
- // reconnect resync, this store drives the alert), which can legitimately disagree after
- // a renderer reload. Gating the badge but not the sound/notification would half-enforce
- // the flag and leave the expensive error — a false completion — fully reachable.
- cs.bumpLoop(e.nodeId, e.lastMessage) // count loop iterations + summary (no-op if not looping)
- // Issue #708: a turn that ended only because a BACKGROUND SUBAGENT reported back is
- // not the fan-out finishing — the parent is about to be woken again by the next one.
- // Read fresh (not the `an` snapshot taken at listener entry): `clearFinishedForParent`
- // may have run just above. It only drops DONE cards, so the verdict is the same either
- // way, and depending on that is exactly the kind of coupling that rots.
- const fanoutBusy = fanoutStillWorking(
- Object.values(useAgentNodes.getState().byId),
- e.nodeId
- )
- alert('finished', `${agentLabel} finished its turn.`, 'done', { quiet: fanoutBusy })
- }
- if (e.state === 'blocked')
- alert('needs input', `${agentLabel} needs permission to continue.`, 'needsYou')
- else if (e.state === 'waiting')
- alert('needs input', `${agentLabel} is waiting for your response.`, 'needsYou')
- break
- }
- case 'subagent-start':
- if (e.toolUseId) {
- an.start(
- e.toolUseId,
- {
- parentNodeId: e.nodeId,
- type: e.subagentType,
- label: e.taskLabel,
- startedAt: e.subagentStartedAt,
- lastActivityAt: e.subagentLastActivityAt
- },
- // A Claude native card replacing the card its tool call drew (claude-subagent-lifecycle).
- e.supersedes
- )
- }
- break
- case 'subagent-end':
- if (e.toolUseId)
- an.finish(e.toolUseId, {
- durationMs: e.durationMs,
- tokens: e.tokens,
- toolUses: e.toolUses,
- result: e.result
- })
- break
- case 'background-task':
- // A background shell task runs INSIDE the CLI process, so the `/exit` Eco hibernation
- // and the bulk restart type would kill it silently. Stamp the node so both skip it.
- // The write mints a new entry object, so whole-map subscribers (minimap, the node) do
- // re-render — once per background launch, which is rarer than any state event.
- cs.markBackgroundTask(e.nodeId)
- break
- case 'recurring':
- if (e.recurringEnd) {
- // The recurring job itself was removed (CronDelete) — take the card down.
- cs.setLoop(e.nodeId, false)
- an.clearLoop(e.nodeId)
- } else if (e.recurringKind) {
- cs.setLoop(e.nodeId, true, e.recurringKind, { schedule: e.schedule, task: e.task })
- }
- break
- case 'session':
- if (e.sessionTitle) cs.setSession(e.nodeId, e.sessionTitle)
- if (e.sessionPhase === 'start') {
- cs.setState(e.nodeId, undefined, e.agentId)
- // A SessionStart is proof a CLI just LAUNCHED in that pane, so a hibernated flag on
- // this node is now false — our own `/exit` produces a SessionEnd, never a
- // SessionStart. This is the residual `setState`'s live-state self-heal cannot reach:
- // a user who relaunches the agent by hand and then takes no turn would keep a SLEEPING
- // chip on a running CLI (and the sweep, which skips hibernated nodes, would leave that
- // session exempt from Eco for good). Deliberately NOT the same as clearing on `done`,
- // which would let a late Stop POST undo a hibernation we just performed. The setter
- // bails when the flag is already unset, so this is free for every other session start.
- cs.setHibernated(e.nodeId, false)
- // Same self-heal, same reason, for the deep "pause & end session" case: that depth
- // recycles the tmux session instead of leaving `hibernated` set, so this SessionStart
- // (the cold-restore's own resume, or a hand-launched relaunch) is the only live proof
- // that node was watching for.
- cs.setPaused(e.nodeId, false)
- // A new CLI is in the pane: whatever exited before it no longer describes this node.
- cs.setSessionEnded(e.nodeId, false)
- }
- if (e.sessionPhase === 'end') {
- cs.setState(e.nodeId, undefined, e.agentId)
- // Recorded as its OWN fact, after the state: `state: undefined` alone is what an idle
- // agent looks like, and the memory levers would keep protecting a pane that now holds
- // only a shell (see `agentProcessInPane`).
- cs.setSessionEnded(e.nodeId, true)
- // In-session /loop dies with its session; cron (and scheduled cloud routines)
- // keep running after it — their cards stay until CronDelete / manual dismiss.
- const kind = cs.byId[e.nodeId]?.loop?.kind
- if (kind === 'loop') {
- cs.setLoop(e.nodeId, false)
- an.clearLoop(e.nodeId)
- }
- an.clearForParent(e.nodeId)
- }
- break
+ // Every store write the event implies (session id, account, state, subagent cards, loop,
+ // session lifecycle) is the reducer's, against the DEFAULT stores this listener has always
+ // written; what it hands back is the alert, and what that alert DOES is this window's own
+ // business (above). The account's `remote` flag is stamped here because this listener is the
+ // first layer that can reach the node and the project that owns it (see `observationIsRemote`).
+ const r = applyAgentEvent(useAgentStatus, useAgentNodes, e, {
+ observationRemote: observationIsRemote(originOf(e.nodeId))
+ })
+ if (r.alert?.kind === 'finished') {
+ alert('finished', `${agentLabel} finished its turn.`, 'done', { quiet: r.alert.quiet })
+ } else if (r.alert?.kind === 'needs-input') {
+ const fallback =
+ e.state === 'blocked'
+ ? `${agentLabel} needs permission to continue.`
+ : `${agentLabel} is waiting for your response.`
+ alert('needs input', fallback, 'needsYou')
}
})
}, [])
diff --git a/src/renderer/canvas/agent-event-listener.source.test.ts b/src/renderer/canvas/agent-event-listener.source.test.ts
new file mode 100644
index 000000000..576afc80a
--- /dev/null
+++ b/src/renderer/canvas/agent-event-listener.source.test.ts
@@ -0,0 +1,48 @@
+// Canvas's agent-status listener after the reducer split: the store writes live in
+// `state/applyAgentEvent.ts` (behaviour-tested there, against real stores), and what stays in the
+// listener is this window's own business — the unread mark and its ack, the sound, the OS
+// notification and the handoff fold. Pinned over the source because the listener lives inside one
+// of Canvas.tsx's effects and no harness can dispatch an event at it.
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+const read = (rel: string): string => readFileSync(resolve(__dirname, '..', rel), 'utf8').replace(/\r\n/g, '\n')
+
+/** From `return api.onAgentStatus(` to the `})` that closes it (the effect's own `}, [])` follows). */
+function listenerBody(src: string): string {
+ const start = src.indexOf('return api.onAgentStatus(')
+ expect(start, 'Canvas must still subscribe to agent:status').toBeGreaterThan(-1)
+ const end = src.indexOf('\n })\n }, [])', start)
+ expect(end, 'the listener must still close its own effect').toBeGreaterThan(start)
+ return src.slice(start, end + '\n })'.length)
+}
+
+/** The body of the listener's `alert` closure: everything before the reducer call. */
+function alertBody(body: string): string {
+ const start = body.indexOf('const alert = (')
+ expect(start, 'the listener must still build its alert closure').toBeGreaterThan(-1)
+ const end = body.indexOf('const r = applyAgentEvent(', start)
+ expect(end).toBeGreaterThan(start)
+ return body.slice(start, end)
+}
+
+describe('Canvas agent-status listener — reducer split', () => {
+ it('the Canvas listener delegates its store writes to applyAgentEvent', () => {
+ const body = listenerBody(read('canvas/Canvas.tsx'))
+ expect(body).toContain('applyAgentEvent(useAgentStatus, useAgentNodes, e, {')
+ expect(body).not.toMatch(/\.setState\(e\.nodeId/) // no store write left inline
+ expect(body).not.toMatch(
+ /cs\.(setSessionId|setAccount|setSession|setLoop|bumpLoop|markBackgroundTask|setHibernated|setPaused|setSessionEnded)\(/
+ )
+ expect(body).not.toContain('useAgentNodes.getState()')
+ expect(body).toContain('suppressDoneAfterHandoff') // local-only side effects stay here
+ })
+
+ it('alert still marks unread only when not watching, then acks, sounds and notifies locally', () => {
+ const alertFn = alertBody(listenerBody(read('canvas/Canvas.tsx')))
+ expect(alertFn).toMatch(/!watching[\s\S]*markUnread/)
+ expect(alertFn).toContain('ackDone')
+ expect(alertFn).toContain('playSfx')
+ })
+})
diff --git a/src/renderer/canvas/agent-status-rescue.test.ts b/src/renderer/canvas/agent-status-rescue.test.ts
index 8c0dca355..4230d0a60 100644
--- a/src/renderer/canvas/agent-status-rescue.test.ts
+++ b/src/renderer/canvas/agent-status-rescue.test.ts
@@ -13,18 +13,20 @@
// is no harness that can dispatch an `agent:status` event at it (the renderer's component tests all
// mount small leaf components), and building one for this fix would be a far bigger change than the
// fix. So the invariant is pinned over the source, like `core/no-electron.test.ts` pins its
-// boundary: both gates in the `state` branch must consult the same skip flag.
+// boundary: both gates in the `state` branch must consult the same skip flag. The listener's store
+// writes have since moved into `state/applyAgentEvent.ts` (behaviour-tested in its own suite), so
+// that is the source read here.
import { describe, it, expect } from 'vitest'
import fs from 'fs'
import path from 'path'
-const src = fs.readFileSync(path.resolve(__dirname, 'Canvas.tsx'), 'utf8')
+const src = fs.readFileSync(path.resolve(__dirname, '../state/applyAgentEvent.ts'), 'utf8')
/** The `case 'state':` body of the agent-status listener. */
function stateBranch(): string {
const start = src.indexOf('const stuckRescueSkip')
- expect(start, 'Canvas must still compute a stuck-rescue skip flag').toBeGreaterThan(-1)
+ expect(start, 'the agent-event reducer must still compute a stuck-rescue skip flag').toBeGreaterThan(-1)
const end = src.indexOf("case 'subagent-start'", start)
expect(end).toBeGreaterThan(start)
return src.slice(start, end)
diff --git a/src/renderer/canvas/claude-subagent-wiring.source.test.ts b/src/renderer/canvas/claude-subagent-wiring.source.test.ts
index b11675c8e..63ad39ea5 100644
--- a/src/renderer/canvas/claude-subagent-wiring.source.test.ts
+++ b/src/renderer/canvas/claude-subagent-wiring.source.test.ts
@@ -1,15 +1,16 @@
// Canvas's agent-status listener, for Claude's native subagent hooks (core/claude-subagent-lifecycle.ts).
// Pinned over the source for the reason agent-status-rescue.test.ts gives: the listener lives inside
-// one of Canvas.tsx's effects and no harness can dispatch an event at it.
+// one of Canvas.tsx's effects and no harness can dispatch an event at it. Its store writes now live
+// in state/applyAgentEvent.ts, so that is the source read here.
import { describe, it, expect } from 'vitest'
import fs from 'fs'
import path from 'path'
-const src = fs.readFileSync(path.resolve(__dirname, 'Canvas.tsx'), 'utf8').replace(/\r\n/g, '\n')
+const src = fs.readFileSync(path.resolve(__dirname, '../state/applyAgentEvent.ts'), 'utf8').replace(/\r\n/g, '\n')
function between(from: string, to: string): string {
const a = src.indexOf(from)
- expect(a, `Canvas must still contain ${from}`).toBeGreaterThan(-1)
+ expect(a, `the agent-event reducer must still contain ${from}`).toBeGreaterThan(-1)
const b = src.indexOf(to, a)
expect(b).toBeGreaterThan(a)
return src.slice(a, b)
diff --git a/src/renderer/canvas/fanout-chime.test.ts b/src/renderer/canvas/fanout-chime.test.ts
index ec8278505..07f335762 100644
--- a/src/renderer/canvas/fanout-chime.test.ts
+++ b/src/renderer/canvas/fanout-chime.test.ts
@@ -6,31 +6,34 @@
// `agent-status-rescue.test.ts`, which pins its sibling invariant the same way). The DECISION is
// pure and behaviourally tested in `renderer/lib/completionAlert.test.ts`; what only the source can
// show is that Canvas asks it, asks it for the right event, and puts the quiet gate BELOW the
-// unread write rather than above it.
+// unread write rather than above it. The asking now happens in the listener's store half,
+// `state/applyAgentEvent.ts`, which hands the verdict back as the alert's `quiet`.
import { describe, it, expect } from 'vitest'
import fs from 'fs'
import path from 'path'
const src = fs.readFileSync(path.resolve(__dirname, 'Canvas.tsx'), 'utf8').replace(/\r\n/g, '\n')
+const reducerSrc = fs
+ .readFileSync(path.resolve(__dirname, '../state/applyAgentEvent.ts'), 'utf8')
+ .replace(/\r\n/g, '\n')
/** The body of the `alert` closure in the agent-status listener. */
function alertBody(): string {
const start = src.indexOf('const alert = (')
expect(start, 'Canvas must still build its alert closure').toBeGreaterThan(-1)
- const end = src.indexOf('const an = useAgentNodes.getState()', start)
+ const end = src.indexOf('const r = applyAgentEvent(', start)
expect(end).toBeGreaterThan(start)
return src.slice(start, end)
}
describe('Canvas completion alert — background fan-out (issue #708)', () => {
it('asks the shared predicate rather than re-deriving "still working" inline', () => {
- expect(src).toContain("import { fanoutStillWorking } from '@renderer/lib/completionAlert'")
+ expect(reducerSrc).toContain("import { fanoutStillWorking } from '@renderer/lib/completionAlert'")
// The verdict must be computed from the LIVE store, not from the `an` snapshot taken at
// listener entry, and it must be handed to the alert as `quiet`.
- expect(src).toMatch(
- /fanoutStillWorking\(\s*Object\.values\(useAgentNodes\.getState\(\)\.byId\),\s*e\.nodeId\s*\)/
- )
+ expect(reducerSrc).toMatch(/fanoutStillWorking\(\s*Object\.values\(nodes\.getState\(\)\.byId\),\s*e\.nodeId\s*\)/)
+ expect(reducerSrc).toMatch(/alert = \{ kind: 'finished', quiet: fanoutBusy \}/)
})
it('gates only the completion alert, never "needs input"', () => {
diff --git a/src/renderer/state/agentStatus.test.ts b/src/renderer/state/agentStatus.test.ts
index 134cf227a..2e54efe8d 100644
--- a/src/renderer/state/agentStatus.test.ts
+++ b/src/renderer/state/agentStatus.test.ts
@@ -42,10 +42,11 @@ describe('sessionEnded — an announced exit is its own fact, not an idle state'
expect(useAgentStatus.getState().byId[id]?.sessionEnded).toBeUndefined()
})
- it('Canvas records it on SessionEnd and withdraws it on SessionStart', () => {
+ it('the agent-event reducer records it on SessionEnd and withdraws it on SessionStart', () => {
// A store flag with no writer is the bug in a new place: the levers would type-check and stay
// protected forever. Pinned at source level, like the setState argument list above.
- const src = readFileSync(resolve(__dirname, '../../..', 'src/renderer/canvas/Canvas.tsx'), 'utf8')
+ // (The listener's store writes moved out of Canvas into state/applyAgentEvent.ts.)
+ const src = readFileSync(resolve(__dirname, '../../..', 'src/renderer/state/applyAgentEvent.ts'), 'utf8')
const end = src.slice(src.indexOf("if (e.sessionPhase === 'end') {"))
expect(end.slice(0, 600)).toMatch(/cs\.setSessionEnded\(e\.nodeId, true\)/)
const start = src.slice(src.indexOf("if (e.sessionPhase === 'start') {"), src.indexOf("if (e.sessionPhase === 'end') {"))
@@ -300,10 +301,11 @@ describe('the verified evidence for a transition', () => {
expect(useAgentStatus.getState().byId[id].stateVerified).toBe(false)
})
- it('Canvas hands the event\'s flag to the store — the drop this whole change exists to fix', () => {
+ it('the agent-event reducer hands the event\'s flag to the store — the drop this whole change exists to fix', () => {
// A store field with no writer is the same bug in a new place, and this one is a plain
// argument list: nothing else in the suite would notice if the last argument disappeared.
- const src = readFileSync(resolve(__dirname, '../../..', 'src/renderer/canvas/Canvas.tsx'), 'utf8')
+ // (The listener's store writes moved out of Canvas into state/applyAgentEvent.ts.)
+ const src = readFileSync(resolve(__dirname, '../../..', 'src/renderer/state/applyAgentEvent.ts'), 'utf8')
expect(src).toMatch(
/cs\.setState\(\s*e\.nodeId,\s*e\.state,\s*e\.agentId,\s*e\.newTurn,\s*e\.pendingId,\s*e\.verified,\s*e\.errored,\s*e\.held,\s*recordsTurnInterrupt\(e\)\s*\)/
)
diff --git a/src/renderer/state/applyAgentEvent.test.ts b/src/renderer/state/applyAgentEvent.test.ts
new file mode 100644
index 000000000..e0c4ae782
--- /dev/null
+++ b/src/renderer/state/applyAgentEvent.test.ts
@@ -0,0 +1,200 @@
+// The store half of the agent-status listener, run against REAL stores: a fresh agent-status session
+// per test (in-memory, no persist key) and the real subagent-card store reset to empty. Canvas used
+// to hold these writes inside one of its effects, where nothing could dispatch an event at them; the
+// reducer exists so a relay session's own store can receive the same writes (bug D).
+import { beforeEach, describe, expect, it } from 'vitest'
+import type { NormalizedAgentEvent } from '@shared/agents/normalize'
+import { createAgentStatusSession } from './agentStatus'
+import { useAgentNodes } from './agentNodes'
+import { applyAgentEvent } from './applyAgentEvent'
+
+const N = 'term-node-a'
+
+const ev = (over: Partial<NormalizedAgentEvent> = {}): NormalizedAgentEvent => ({
+ nodeId: N,
+ agentId: 'claude',
+ kind: 'state',
+ ...over
+})
+
+const LOCAL = { observationRemote: false }
+
+let status: ReturnType<typeof createAgentStatusSession>['store']
+
+beforeEach(() => {
+ status = createAgentStatusSession(undefined).store
+ useAgentNodes.setState({
+ byId: {},
+ activityById: {},
+ lastActivityAt: {},
+ positions: {},
+ sizes: {},
+ expanded: {},
+ selectedId: null,
+ autoHideFinished: false
+ })
+})
+
+const entry = (id = N) => status.getState().byId[id]
+
+describe('applyAgentEvent', () => {
+ it('records state, agent and session id', () => {
+ const r = applyAgentEvent(status, useAgentNodes, ev({ state: 'working', newTurn: true, sessionId: 'sess-1' }), LOCAL)
+ expect(r).toEqual({ nodeId: N, alert: null })
+ expect(entry().state).toBe('working')
+ expect(entry().agentId).toBe('claude')
+ expect(entry().sessionId).toBe('sess-1')
+ })
+
+ it('a clean done answers a finished alert', () => {
+ applyAgentEvent(status, useAgentNodes, ev({ state: 'working', newTurn: true }), LOCAL)
+ const r = applyAgentEvent(status, useAgentNodes, ev({ state: 'done', lastMessage: 'all green' }), LOCAL)
+ expect(r.alert).toEqual({ kind: 'finished', quiet: false })
+ expect(entry().state).toBe('done')
+ })
+
+ it('an interrupted done answers no alert', () => {
+ applyAgentEvent(status, useAgentNodes, ev({ state: 'working', newTurn: true }), LOCAL)
+ const r = applyAgentEvent(status, useAgentNodes, ev({ state: 'done', interrupted: true }), LOCAL)
+ expect(r.alert).toBeNull()
+ // The badge still moves: the turn ended, nobody needs telling.
+ expect(entry().state).toBe('done')
+ expect(entry().lastTurnInterrupted).toBeDefined()
+ })
+
+ it('the idle rescue on a node that was not working answers no alert', () => {
+ applyAgentEvent(status, useAgentNodes, ev({ state: 'working', newTurn: true }), LOCAL)
+ applyAgentEvent(status, useAgentNodes, ev({ state: 'done' }), LOCAL)
+ const before = entry()
+ const r = applyAgentEvent(status, useAgentNodes, ev({ state: 'done', idle: true, lastMessage: 'x' }), LOCAL)
+ expect(r.alert).toBeNull()
+ // Skipped outright: no state write, no loop bump — the entry is the very same object.
+ expect(entry()).toBe(before)
+ })
+
+ it('blocked and waiting answer needs-input', () => {
+ const blocked = applyAgentEvent(status, useAgentNodes, ev({ state: 'blocked', pendingId: 'p-1' }), LOCAL)
+ expect(blocked.alert).toEqual({ kind: 'needs-input' })
+ expect(entry().state).toBe('blocked')
+ expect(entry().pendingId).toBe('p-1')
+ const waiting = applyAgentEvent(status, useAgentNodes, ev({ nodeId: 'term-node-b', state: 'waiting' }), LOCAL)
+ expect(waiting).toEqual({ nodeId: 'term-node-b', alert: { kind: 'needs-input' } })
+ expect(entry('term-node-b').state).toBe('waiting')
+ })
+
+ it('a done while a subagent card still works is quiet', () => {
+ applyAgentEvent(status, useAgentNodes, ev({ state: 'working', newTurn: true }), LOCAL)
+ applyAgentEvent(
+ status,
+ useAgentNodes,
+ ev({ kind: 'subagent-start', toolUseId: 'tool-1', subagentType: 'Explore', taskLabel: 'scan' }),
+ LOCAL
+ )
+ expect(useAgentNodes.getState().byId['tool-1']).toMatchObject({ parentNodeId: N, state: 'working' })
+ const r = applyAgentEvent(status, useAgentNodes, ev({ state: 'done' }), LOCAL)
+ expect(r.alert).toEqual({ kind: 'finished', quiet: true })
+ // Once the card reports done, the next turn end is a real finish again.
+ applyAgentEvent(status, useAgentNodes, ev({ kind: 'subagent-end', toolUseId: 'tool-1', tokens: 10 }), LOCAL)
+ expect(useAgentNodes.getState().byId['tool-1']).toMatchObject({ state: 'done', tokens: 10 })
+ applyAgentEvent(status, useAgentNodes, ev({ state: 'working', newTurn: true }), LOCAL)
+ // The new turn dropped the finished card (and only finished ones).
+ expect(useAgentNodes.getState().byId['tool-1']).toBeUndefined()
+ expect(applyAgentEvent(status, useAgentNodes, ev({ state: 'done' }), LOCAL).alert).toEqual({
+ kind: 'finished',
+ quiet: false
+ })
+ })
+
+ it('a /loop prompt sets the loop and a done bumps it', () => {
+ applyAgentEvent(status, useAgentNodes, ev({ state: 'working', newTurn: true, task: '/loop watch CI' }), LOCAL)
+ expect(entry().loop).toMatchObject({ kind: 'loop', count: 0, task: '/loop watch CI' })
+ applyAgentEvent(status, useAgentNodes, ev({ state: 'done', lastMessage: 'iteration one' }), LOCAL)
+ expect(entry().loop).toMatchObject({ kind: 'loop', count: 1, items: ['iteration one'] })
+ })
+
+ it('session start clears hibernated, paused and sessionEnded; session end sets sessionEnded', () => {
+ const s = status.getState()
+ s.setState(N, 'done', 'claude')
+ s.setHibernated(N, true)
+ s.setPaused(N, true)
+ s.setSessionEnded(N, true)
+ expect(entry()).toMatchObject({ hibernated: true, paused: true, sessionEnded: true })
+
+ const start = applyAgentEvent(status, useAgentNodes, ev({ kind: 'session', sessionPhase: 'start', sessionTitle: 'fix the build' }), LOCAL)
+ expect(start.alert).toBeNull()
+ expect(entry().state).toBeUndefined()
+ expect(entry().session).toBe('fix the build')
+ expect(entry().hibernated).toBeFalsy()
+ expect(entry().paused).toBeFalsy()
+ expect(entry().sessionEnded).toBeFalsy()
+
+ applyAgentEvent(status, useAgentNodes, ev({ state: 'working', newTurn: true }), LOCAL)
+ const end = applyAgentEvent(status, useAgentNodes, ev({ kind: 'session', sessionPhase: 'end' }), LOCAL)
+ expect(end.alert).toBeNull()
+ expect(entry().state).toBeUndefined()
+ expect(entry().sessionEnded).toBe(true)
+ })
+
+ it('a session end clears an in-session loop but keeps a cron card', () => {
+ const C = 'term-node-cron'
+ applyAgentEvent(status, useAgentNodes, ev({ kind: 'recurring', recurringKind: 'loop', task: 'poll' }), LOCAL)
+ applyAgentEvent(
+ status,
+ useAgentNodes,
+ ev({ nodeId: C, kind: 'recurring', recurringKind: 'cron', schedule: '*/5 * * * *', task: 'report' }),
+ LOCAL
+ )
+ useAgentNodes.getState().setPosition(`loop-${N}`, { x: 10, y: 20 })
+ useAgentNodes.getState().setPosition(`loop-${C}`, { x: 30, y: 40 })
+ // A subagent card of the ending session goes with it, finished or not.
+ applyAgentEvent(status, useAgentNodes, ev({ kind: 'subagent-start', toolUseId: 'tool-9' }), LOCAL)
+
+ applyAgentEvent(status, useAgentNodes, ev({ kind: 'session', sessionPhase: 'end' }), LOCAL)
+ applyAgentEvent(status, useAgentNodes, ev({ nodeId: C, kind: 'session', sessionPhase: 'end' }), LOCAL)
+
+ expect(entry().loop).toBeUndefined()
+ expect(useAgentNodes.getState().positions[`loop-${N}`]).toBeUndefined()
+ expect(useAgentNodes.getState().byId['tool-9']).toBeUndefined()
+ expect(entry(C).loop).toMatchObject({ kind: 'cron', schedule: '*/5 * * * *', task: 'report' })
+ expect(useAgentNodes.getState().positions[`loop-${C}`]).toEqual({ x: 30, y: 40 })
+ })
+
+ it('with nodes = null, subagent events change nothing and do not throw', () => {
+ // A card on the DEFAULT store proves a null `nodes` reads it no more than it writes it.
+ useAgentNodes.getState().start('tool-local', { parentNodeId: N, type: 'Explore' })
+ const cards = useAgentNodes.getState().byId
+ const before = status.getState().byId
+ expect(() => {
+ applyAgentEvent(status, null, ev({ kind: 'subagent-start', toolUseId: 'tool-1', taskLabel: 'scan' }), LOCAL)
+ applyAgentEvent(status, null, ev({ kind: 'subagent-end', toolUseId: 'tool-local', tokens: 3 }), LOCAL)
+ }).not.toThrow()
+ expect(status.getState().byId).toBe(before)
+ expect(useAgentNodes.getState().byId).toBe(cards)
+
+ // The turn and session paths that clear cards skip them too, and a done is never quiet.
+ expect(() => {
+ applyAgentEvent(status, null, ev({ state: 'working', newTurn: true, task: '/loop poll' }), LOCAL)
+ }).not.toThrow()
+ expect(applyAgentEvent(status, null, ev({ state: 'done' }), LOCAL).alert).toEqual({
+ kind: 'finished',
+ quiet: false
+ })
+ expect(() => {
+ applyAgentEvent(status, null, ev({ kind: 'recurring', recurringEnd: true }), LOCAL)
+ applyAgentEvent(status, null, ev({ kind: 'session', sessionPhase: 'end' }), LOCAL)
+ }).not.toThrow()
+ expect(useAgentNodes.getState().byId).toBe(cards)
+ expect(entry().sessionEnded).toBe(true)
+ })
+
+ it('setAccount carries opts.observationRemote', () => {
+ const account = { configDir: '/home/u/.claude-2', accountId: 'acct-2', known: true }
+ applyAgentEvent(status, useAgentNodes, ev({ state: 'working', newTurn: true, account }), {
+ observationRemote: true
+ })
+ expect(entry().account?.remote).toBe(true)
+ expect(entry().account?.configDir).toBe('/home/u/.claude-2')
+ applyAgentEvent(status, useAgentNodes, ev({ nodeId: 'term-node-b', state: 'working', newTurn: true, account }), LOCAL)
+ expect(entry('term-node-b').account?.remote).toBe(false)
+ })
+})
diff --git a/src/renderer/state/applyAgentEvent.ts b/src/renderer/state/applyAgentEvent.ts
new file mode 100644
index 000000000..2dba61073
--- /dev/null
+++ b/src/renderer/state/applyAgentEvent.ts
@@ -0,0 +1,203 @@
+import type { StoreApi } from 'zustand'
+import type { NormalizedAgentEvent } from '@shared/agents/normalize'
+import { fanoutStillWorking } from '@renderer/lib/completionAlert'
+import { recordsTurnInterrupt, type AgentStatusStore } from './agentStatus'
+import type { useAgentNodes } from './agentNodes'
+
+/**
+ * The store half of the agent-status listener: one `NormalizedAgentEvent` in, the agent-status and
+ * subagent-card writes it implies, and the alert it raises out.
+ *
+ * Moved out of Canvas's `onAgentStatus` listener unchanged so the same writes can run against a
+ * store other than the default one — a relay session's own `SessionStores.agentStatus` (bug D: a
+ * team tab never showed agent status, because the only subscriber wrote the DEFAULT store). The
+ * caller passes the store it means; nothing here reaches for a module singleton.
+ *
+ * What stays with the caller is everything that is a LOCAL interrupt or a fact about this window:
+ * the unread mark and its ack (they depend on which terminal has focus), the sound, the OS
+ * notification and the handoff fold. The reducer only says which alert the event raised.
+ */
+
+type AgentNodesState = ReturnType<typeof useAgentNodes.getState>
+
+/** `finished` = a turn ended cleanly; `quiet` silences the interrupts (chime, OS notification) and
+ * never the unread record — see `fanoutStillWorking`. `needs-input` = blocked or waiting. */
+export type AgentEventAlert = { kind: 'finished'; quiet: boolean } | { kind: 'needs-input' }
+
+export interface ApplyAgentEventOptions {
+ /** The `remote` flag `setAccount` records. Canvas: observationIsRemote(originOf(id)); relay: true. */
+ observationRemote: boolean
+}
+
+export interface AgentEventResult {
+ nodeId: string
+ alert: AgentEventAlert | null
+}
+
+export function applyAgentEvent(
+ status: Pick<StoreApi<AgentStatusStore>, 'getState'>,
+ nodes: Pick<StoreApi<AgentNodesState>, 'getState'> | null, // null = no subagent cards (relay)
+ e: NormalizedAgentEvent,
+ opts: ApplyAgentEventOptions
+): AgentEventResult {
+ const cs = status.getState()
+ let alert: AgentEventAlert | null = null
+ if (e.sessionId) cs.setSessionId(e.nodeId, e.sessionId)
+ // Which Claude account the posting session is ACTUALLY on — a hook-derived LABEL, captured
+ // off any event that carries one, exactly like `sessionId` above: a plain terminal running
+ // `CLAUDE_CONFIG_DIR=~/.claude-2 claude` announces its identity nowhere else.
+ //
+ // The `remote` flag is decided by the CALLER and nowhere else. The classifier in core is
+ // deliberately host-agnostic — two of its rules exist precisely to name a REMOTE dir — and core
+ // holds only the hook payload, which never says which machine posted it. The listener is the
+ // first layer that can ask, because it can reach the node and the project that owns it, and a
+ // dir that names another machine's filesystem must not reach any LOCAL affordance (see
+ // `observationIsRemote` and the consumers in lib/accountChip.ts).
+ if (e.account) cs.setAccount(e.nodeId, { ...e.account, remote: opts.observationRemote })
+ // No subagent cards on this surface (`nodes` null): every card write below is skipped.
+ const an = nodes ? nodes.getState() : null
+ switch (e.kind) {
+ case 'state': {
+ // An `idle` done (the CLI went quiet at its prompt — see normalize) is a RESCUE for a
+ // node stuck on `working` after an Esc that ran no turn-end hook. It may ONLY move a
+ // working node: blocked/waiting is also "idle at the prompt", and clearing it there
+ // would drop a live approval off the badge. Same rule as the mirror's reduceEntry.
+ const stuckRescueSkip = e.idle === true && cs.byId[e.nodeId]?.state !== 'working'
+ // `pendingId` (deterministic approvals) rides a `blocked` event; the store keeps it only
+ // while blocked so the header's Approve/Deny buttons appear + vanish with the state.
+ // `e.verified` is the identity evidence for this very transition (hook-server labels it);
+ // 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,
+ e.errored,
+ e.held,
+ recordsTurnInterrupt(e)
+ )
+ // Claude's Stop names the BACKGROUND tasks still running (async subagents, nested ones,
+ // background shells). A background subagent that ends its turn while its own work runs
+ // fires SubagentStop — its card goes done — and is resumed later, so the card alone would
+ // let Eco or the bulk restart type /exit over live work. The existing background-task
+ // stamp is the guard both already read; a turn start clears it, the next Stop re-decides.
+ if (e.state === 'done' && !stuckRescueSkip && e.backgroundTaskIds?.length) cs.markBackgroundTask(e.nodeId)
+ // 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.
+ const m = e.task.match(/^\s*\/(loop|schedule|cron)\b/)
+ if (m) cs.setLoop(e.nodeId, true, m[1] as 'loop' | 'schedule' | 'cron', { task: e.task })
+ }
+ if (e.state === 'done' && !e.interrupted && !stuckRescueSkip) {
+ // Interrupted turns (Esc/Ctrl-C) alert nobody: the user did it themselves, and
+ // the turn didn't complete, so it isn't a loop iteration either.
+ // An IGNORED rescue is silent for the same reason it moves no badge: it claims a turn
+ // ended for a node this surface never saw running, so the "finished" is unfounded —
+ // and it arrives from a second source of truth (the main-process mirror drives the SSH
+ // reconnect resync, this store drives the alert), which can legitimately disagree after
+ // a renderer reload. Gating the badge but not the sound/notification would half-enforce
+ // the flag and leave the expensive error — a false completion — fully reachable.
+ cs.bumpLoop(e.nodeId, e.lastMessage) // count loop iterations + summary (no-op if not looping)
+ // Issue #708: a turn that ended only because a BACKGROUND SUBAGENT reported back is
+ // not the fan-out finishing — the parent is about to be woken again by the next one.
+ // Read fresh (not the `an` snapshot taken at entry): `clearFinishedForParent` may have
+ // run just above. It only drops DONE cards, so the verdict is the same either way, and
+ // depending on that is exactly the kind of coupling that rots. No cards = never quiet.
+ const fanoutBusy = nodes
+ ? fanoutStillWorking(Object.values(nodes.getState().byId), e.nodeId)
+ : false
+ alert = { kind: 'finished', quiet: fanoutBusy }
+ }
+ if (e.state === 'blocked' || e.state === 'waiting') alert = { kind: 'needs-input' }
+ break
+ }
+ case 'subagent-start':
+ if (e.toolUseId && an) {
+ an.start(
+ e.toolUseId,
+ {
+ parentNodeId: e.nodeId,
+ type: e.subagentType,
+ label: e.taskLabel,
+ startedAt: e.subagentStartedAt,
+ lastActivityAt: e.subagentLastActivityAt
+ },
+ // A Claude native card replacing the card its tool call drew (claude-subagent-lifecycle).
+ e.supersedes
+ )
+ }
+ break
+ case 'subagent-end':
+ if (e.toolUseId && an)
+ an.finish(e.toolUseId, {
+ durationMs: e.durationMs,
+ tokens: e.tokens,
+ toolUses: e.toolUses,
+ result: e.result
+ })
+ break
+ case 'background-task':
+ // A background shell task runs INSIDE the CLI process, so the `/exit` Eco hibernation
+ // and the bulk restart type would kill it silently. Stamp the node so both skip it.
+ // The write mints a new entry object, so whole-map subscribers (minimap, the node) do
+ // re-render — once per background launch, which is rarer than any state event.
+ cs.markBackgroundTask(e.nodeId)
+ break
+ case 'recurring':
+ if (e.recurringEnd) {
+ // The recurring job itself was removed (CronDelete) — take the card down.
+ cs.setLoop(e.nodeId, false)
+ an?.clearLoop(e.nodeId)
+ } else if (e.recurringKind) {
+ cs.setLoop(e.nodeId, true, e.recurringKind, { schedule: e.schedule, task: e.task })
+ }
+ break
+ case 'session':
+ if (e.sessionTitle) cs.setSession(e.nodeId, e.sessionTitle)
+ if (e.sessionPhase === 'start') {
+ cs.setState(e.nodeId, undefined, e.agentId)
+ // A SessionStart is proof a CLI just LAUNCHED in that pane, so a hibernated flag on
+ // this node is now false — our own `/exit` produces a SessionEnd, never a
+ // SessionStart. This is the residual `setState`'s live-state self-heal cannot reach:
+ // a user who relaunches the agent by hand and then takes no turn would keep a SLEEPING
+ // chip on a running CLI (and the sweep, which skips hibernated nodes, would leave that
+ // session exempt from Eco for good). Deliberately NOT the same as clearing on `done`,
+ // which would let a late Stop POST undo a hibernation we just performed. The setter
+ // bails when the flag is already unset, so this is free for every other session start.
+ cs.setHibernated(e.nodeId, false)
+ // Same self-heal, same reason, for the deep "pause & end session" case: that depth
+ // recycles the tmux session instead of leaving `hibernated` set, so this SessionStart
+ // (the cold-restore's own resume, or a hand-launched relaunch) is the only live proof
+ // that node was watching for.
+ cs.setPaused(e.nodeId, false)
+ // A new CLI is in the pane: whatever exited before it no longer describes this node.
+ cs.setSessionEnded(e.nodeId, false)
+ }
+ if (e.sessionPhase === 'end') {
+ cs.setState(e.nodeId, undefined, e.agentId)
+ // Recorded as its OWN fact, after the state: `state: undefined` alone is what an idle
+ // agent looks like, and the memory levers would keep protecting a pane that now holds
+ // only a shell (see `agentProcessInPane`).
+ cs.setSessionEnded(e.nodeId, true)
+ // In-session /loop dies with its session; cron (and scheduled cloud routines)
+ // keep running after it — their cards stay until CronDelete / manual dismiss.
+ const kind = cs.byId[e.nodeId]?.loop?.kind
+ if (kind === 'loop') {
+ cs.setLoop(e.nodeId, false)
+ an?.clearLoop(e.nodeId)
+ }
+ an?.clearForParent(e.nodeId)
+ }
+ break
+ }
+ return { nodeId: e.nodeId, alert }
+}