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): don't let the status badge stick on RUNNING after the turn ended
enesf0524f1755b1
diff --git a/src/main/agents/hooks/claude.ts b/src/main/agents/hooks/claude.tsindex 87d8fe35d..b8237327f 100644--- a/src/main/agents/hooks/claude.ts+++ b/src/main/agents/hooks/claude.ts@@ -8,7 +8,12 @@ const CLAUDE_EVENTS = ['SessionStart','UserPromptSubmit','Stop',+ // Fires INSTEAD of Stop when the turn ends on an API/model error — without it the+ // status badge sticks on "working" after any errored turn.+ 'StopFailure','Notification',+ // Dedicated permission-prompt signal (→ blocked), more direct than Notification.+ 'PermissionRequest','SessionEnd','PreToolUse','PostToolUse'@@ -32,6 +37,7 @@ export function installClaudeHooks(): void {export function removeClaudeHooks(): void {removeHooksFrom({configPath: configPath(),- events: CLAUDE_EVENTS+ events: CLAUDE_EVENTS,+ scriptFileName: SCRIPT_FILE_NAME})}diff --git a/src/main/agents/hooks/gemini.ts b/src/main/agents/hooks/gemini.tsindex 3013aba47..fff06d336 100644--- a/src/main/agents/hooks/gemini.ts+++ b/src/main/agents/hooks/gemini.ts@@ -24,6 +24,7 @@ export function installGeminiHooks(): void {export function removeGeminiHooks(): void {removeHooksFrom({configPath: configPath(),- events: GEMINI_EVENTS+ events: GEMINI_EVENTS,+ scriptFileName: SCRIPT_FILE_NAME})}diff --git a/src/main/agents/hooks/install-helper.test.ts b/src/main/agents/hooks/install-helper.test.tsindex af3a7f7bc..07dcc52f1 100644--- a/src/main/agents/hooks/install-helper.test.ts+++ b/src/main/agents/hooks/install-helper.test.ts@@ -16,6 +16,21 @@ describe('mergeManagedHook', () => {const twice = mergeManagedHook(once, cmd, ['Stop'])expect(twice.hooks!.Stop).toEqual([{ hooks: [{ type: 'command', command: cmd }] }])})+ it("leaves another app's agent-hooks entry alone (e.g. REF's claude-hook.sh)", () => {+ // REF's hook command also contains "agent-hooks" — a substring match would delete a+ // foreign tool's hooks the moment we install into an event it also uses (StopFailure).+ const REF = {+ hooks: [+ {+ type: 'command',+ command:+ "if [ -x '/Users/x/.REF/agent-hooks/claude-hook.sh' ]; then /bin/sh '/Users/x/.REF/agent-hooks/claude-hook.sh'; fi"+ }+ ]+ }+ const out = mergeManagedHook({ hooks: { StopFailure: [REF] } }, cmd, ['StopFailure'])+ expect(out.hooks!.StopFailure).toEqual([REF, { hooks: [{ type: 'command', command: cmd }] }])+ })it('drops a legacy claude-signals managed entry too', () => {const out = mergeManagedHook({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'sh /x/claude-signals.sh' }] }] } },diff --git a/src/main/agents/hooks/install-helper.ts b/src/main/agents/hooks/install-helper.tsindex 8630a28ae..b476a0d41 100644--- a/src/main/agents/hooks/install-helper.ts+++ b/src/main/agents/hooks/install-helper.ts@@ -24,18 +24,28 @@ function scriptPathFor(scriptFileName: string): string {return path.join(app.getPath('userData'), 'agent-hooks', scriptFileName)}-/** A managed entry: matches the live `agent-hooks/` path or the legacy `claude-signals` marker. */-function isManaged(d: HookDef): boolean {+// The marker identifying OUR entry: the `agent-hooks/<scriptFile>` tail of the managed+// command. A bare "agent-hooks" substring is NOT enough — other tools use the same dir+// name (REF's `~/.REF/agent-hooks/claude-hook.sh`), and matching them would delete a+// foreign app's hooks from any event we both subscribe to.+function managedMarkerFor(command: string): string {+ const m = command.match(/agent-hooks[\\/][^"'\s]+/)+ return m ? m[0].replace(/\\/g, '/') : 'agent-hooks'+}++/** A managed entry: matches OUR script under `agent-hooks/` or the legacy `claude-signals` marker. */+function isManaged(d: HookDef, marker: string): boolean {return !!d.hooks?.some(- (h) => h.command.includes('agent-hooks') || h.command.includes('claude-signals')+ (h) => h.command.includes(marker) || h.command.includes('claude-signals'))}/** Pure: merge the managed `command` into each event, dropping any prior managed entry. */export function mergeManagedHook(config: HookSettings, command: string, events: readonly string[]): HookSettings {+ const marker = managedMarkerFor(command)const next: HookSettings = { ...config, hooks: { ...(config.hooks ?? {}) } }for (const ev of events) {- const existing = (next.hooks![ev] ?? []).filter((d) => !isManaged(d))+ const existing = (next.hooks![ev] ?? []).filter((d) => !isManaged(d, marker))existing.push({ hooks: [{ type: 'command', command }] })next.hooks![ev] = existing}@@ -85,10 +95,13 @@ export function installHooksInto(opts: InstallHooksOptions): void {export interface RemoveHooksOptions {configPath: stringevents: readonly string[]+ /** Our script's file name — narrows the match so foreign agent-hooks entries survive. */+ scriptFileName: string}export function removeHooksFrom(opts: RemoveHooksOptions): void {- const { configPath, events } = opts+ const { configPath, events, scriptFileName } = opts+ const marker = `agent-hooks/${scriptFileName}`let config: Settingstry {config = JSON.parse(readFileSync(configPath, 'utf8')) as Settings@@ -98,7 +111,7 @@ export function removeHooksFrom(opts: RemoveHooksOptions): void {if (!config.hooks) returnfor (const ev of events) {if (!config.hooks[ev]) continue- config.hooks[ev] = config.hooks[ev].filter((d) => !d.hooks?.some((h) => h.command.includes('agent-hooks')))+ config.hooks[ev] = config.hooks[ev].filter((d) => !d.hooks?.some((h) => h.command.includes(marker)))if (config.hooks[ev].length === 0) delete config.hooks[ev]}try {diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 8950c573e..fea5fddd8 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -2584,7 +2584,7 @@ export function Canvas() {const an = useAgentNodes.getState()switch (e.kind) {case 'state':- if (e.state) cs.setState(e.nodeId, e.state, e.agentId)+ if (e.state) cs.setState(e.nodeId, e.state, e.agentId, e.newTurn)if (e.newTurn) an.clearForParent(e.nodeId) // genuine new turn → drop the previous fan-outif (e.newTurn && e.task) {// Prompt-prefix fallback for /loop|/schedule|/cron when the natural-language@@ -2592,7 +2592,9 @@ export function Canvas() {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') {+ if (e.state === 'done' && !e.interrupted) {+ // 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.cs.bumpLoop(e.nodeId, e.lastMessage) // count loop iterations + summary (no-op if not looping)alert('finished', `${agentLabel} finished its turn.`)}@@ -2634,6 +2636,13 @@ 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).+ useEffect(() => {+ const t = setInterval(() => useAgentStatus.getState().sweepStaleWorking(), 60_000)+ return () => clearInterval(t)+ }, [])+// When the palette opens, capture each terminal's visible buffer (cached ~3s) so the// search can match text shown in terminals/Claude sessions.useEffect(() => {diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex ce4d0bb95..800526f38 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -26,7 +26,7 @@ import { useTerminalSearch } from '../terminal/useTerminalSearch'import { ContextMeter } from '../components/ContextMeter'import { isZoomModifierHeld } from '../lib/zoomModifier'import { useSettings } from '../state/settings'-import { useAgentStatus } from '../state/agentStatus'+import { useAgentStatus, inferInterruptAfterSettle } from '../state/agentStatus'import { useAgentNodes } from '../state/agentNodes'import { useProjects } from '../state/projects'import { useSshConn } from '../state/sshConn'@@ -410,7 +410,15 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNterm.write(`\r\n\x1b[90m[process exited with code ${code}]\x1b[0m\r\n`)}))- cleanups.push(term.onData((input) => transport.write(sid, input)).dispose)+ cleanups.push(+ term.onData((input) => {+ // Lone Esc / Ctrl-C while the agent works: Claude Code fires NO hook on a user+ // interrupt, so probe the cancelled turn (still-silent working → done). Exact+ // match — arrow keys etc. arrive as multi-byte \x1b[… sequences.+ if (showStatus && (input === '\x1b' || input === '\x03')) inferInterruptAfterSettle(id)+ transport.write(sid, input)+ }).dispose+ )// Run a one-shot command on first open (e.g. "gh auth login" or the agent CLI), then// forget it.if (data.initialCommand) {diff --git a/src/renderer/state/agentStatus.test.ts b/src/renderer/state/agentStatus.test.tsnew file mode 100644index 000000000..a3a6d65b6--- /dev/null+++ b/src/renderer/state/agentStatus.test.ts@@ -0,0 +1,108 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import {+ useAgentStatus,+ inferInterruptAfterSettle,+ DONE_HOLDOFF_MS,+ STALE_WORKING_MS+} from './agentStatus'++let seq = 0+const nid = (): string => `node-${++seq}`++beforeEach(() => {+ vi.useFakeTimers()+})+afterEach(() => {+ vi.useRealTimers()+})++describe('done-holdoff race guard', () => {+ // Claude Code runs hooks in parallel: the last PostToolUse's curl can land AFTER the+ // Stop's curl. Without a holdoff that late "working" resurrects a finished turn.+ it('ignores a non-newTurn working arriving right after done', () => {+ const id = nid()+ const s = useAgentStatus.getState()+ s.setState(id, 'working', 'claude')+ s.setState(id, 'done', 'claude')+ vi.advanceTimersByTime(1000)+ useAgentStatus.getState().setState(id, 'working', 'claude')+ expect(useAgentStatus.getState().byId[id].state).toBe('done')+ })++ it('a genuine new turn (newTurn) overrides the holdoff', () => {+ const id = nid()+ const s = useAgentStatus.getState()+ s.setState(id, 'done', 'claude')+ vi.advanceTimersByTime(1000)+ useAgentStatus.getState().setState(id, 'working', 'claude', true)+ expect(useAgentStatus.getState().byId[id].state).toBe('working')+ })++ it('working is accepted again once the holdoff has passed', () => {+ const id = nid()+ useAgentStatus.getState().setState(id, 'done', 'claude')+ vi.advanceTimersByTime(DONE_HOLDOFF_MS + 500)+ useAgentStatus.getState().setState(id, 'working', 'claude')+ expect(useAgentStatus.getState().byId[id].state).toBe('working')+ })+})++describe('stale-working sweeper', () => {+ it('clears a working entry whose last event is older than the stale threshold', () => {+ const id = nid()+ useAgentStatus.getState().setState(id, 'working', 'claude')+ vi.advanceTimersByTime(STALE_WORKING_MS + 60_000)+ useAgentStatus.getState().sweepStaleWorking()+ expect(useAgentStatus.getState().byId[id].state).toBeUndefined()+ })++ it('keeps a working entry fresh as long as events keep arriving', () => {+ const id = nid()+ useAgentStatus.getState().setState(id, 'working', 'claude')+ // Repeated same-state events (each tool use) must refresh freshness.+ vi.advanceTimersByTime(STALE_WORKING_MS - 60_000)+ useAgentStatus.getState().setState(id, 'working', 'claude')+ vi.advanceTimersByTime(120_000)+ useAgentStatus.getState().sweepStaleWorking()+ expect(useAgentStatus.getState().byId[id].state).toBe('working')+ })++ it('never touches done/waiting entries', () => {+ const a = nid()+ const b = nid()+ useAgentStatus.getState().setState(a, 'done', 'claude')+ useAgentStatus.getState().setState(b, 'waiting', 'claude')+ vi.advanceTimersByTime(STALE_WORKING_MS * 2)+ useAgentStatus.getState().sweepStaleWorking()+ expect(useAgentStatus.getState().byId[a].state).toBe('done')+ expect(useAgentStatus.getState().byId[b].state).toBe('waiting')+ })+})++describe('interrupt inference (Esc/Ctrl-C with no final hook)', () => {+ it('flips a still-working node to done after the settle window', () => {+ const id = nid()+ useAgentStatus.getState().setState(id, 'working', 'claude')+ inferInterruptAfterSettle(id, 1500)+ vi.advanceTimersByTime(1500)+ expect(useAgentStatus.getState().byId[id].state).toBe('done')+ })++ it('aborts when any hook event lands during the settle window (agent still alive)', () => {+ const id = nid()+ useAgentStatus.getState().setState(id, 'working', 'claude')+ inferInterruptAfterSettle(id, 1500)+ vi.advanceTimersByTime(700)+ useAgentStatus.getState().setState(id, 'working', 'claude') // e.g. next PreToolUse+ vi.advanceTimersByTime(800)+ expect(useAgentStatus.getState().byId[id].state).toBe('working')+ })++ it('is a no-op when the node is not working (Esc at an idle prompt)', () => {+ const id = nid()+ useAgentStatus.getState().setState(id, 'done', 'claude')+ inferInterruptAfterSettle(id, 1500)+ vi.advanceTimersByTime(1500)+ expect(useAgentStatus.getState().byId[id].state).toBe('done')+ })+})diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.tsindex bfea43b29..6cb3b669d 100644--- a/src/renderer/state/agentStatus.ts+++ b/src/renderer/state/agentStatus.ts@@ -10,6 +10,12 @@ import type { AgentState } from '@shared/agents/normalize'export interface AgentNodeStatus {/** Live activity; undefined = idle/unknown. */state?: AgentState+ /**+ * When the LAST hook event asserted the current state (freshness, not transition time).+ * Never rendered — drives the done-holdoff guard, the stale-working sweeper, and the+ * interrupt-inference baseline. Same-state events refresh it in place (no re-render).+ */+ stateAt?: number/** Which agent this node is running (claude/codex/gemini/…), when known. */agentId?: AgentId/** A turn finished / needs attention while the user wasn't looking. */@@ -36,7 +42,10 @@ interface AgentStatusStore {/** The terminal node the user is currently focused in (for unread decisions). */activeId: string | nullsetActive(id: string, active: boolean): void- setState(id: string, state: AgentState | undefined, agentId?: AgentId): void+ /** `newTurn` marks a genuine UserPromptSubmit — the only working that may follow a fresh done. */+ setState(id: string, state: AgentState | undefined, agentId?: AgentId, newTurn?: boolean): void+ /** Clear `working` entries whose last event is older than `staleMs` (lost-Stop safety net). */+ sweepStaleWorking(staleMs?: number): voidsetSession(id: string, session: string): voidsetSessionId(id: string, sessionId: string): voidmarkUnread(id: string): void@@ -56,6 +65,18 @@ interface AgentStatusStore {const EMPTY: AgentNodeStatus = { unread: false }const KEY = 'nodeterm.agentStatus'+// Claude Code runs hooks in PARALLEL, so the last PostToolUse's POST can arrive after the+// Stop's POST — hold done against any non-newTurn working for this long.+export const DONE_HOLDOFF_MS = 3000+// Last-resort net for a lost Stop POST / crashed CLI: a working entry that saw no event at+// all for this long decays to idle. Long on purpose (mirrors REF's 30 min freshness TTL):+// a single silent tool run (e.g. a long build) fires no hooks between Pre- and PostToolUse,+// so anything shorter would flip genuinely-running turns to idle.+export const STALE_WORKING_MS = 30 * 60_000+// Esc/Ctrl-C interrupt inference: how long to wait for a hook event before concluding the+// turn was cancelled without a final Stop.+export const INTERRUPT_SETTLE_MS = 1500+// One-time localStorage migration from the old key. Runs before the store hydrates.const LEGACY_KEY = 'nodeterm.claudeStatus'try {@@ -107,15 +128,46 @@ export const useAgentStatus = create<AgentStatusStore>((set) => ({return s.activeId === id ? { activeId: null } : s}),- setState: (id, state, agentId) =>+ setState: (id, state, agentId, newTurn) =>set((s) => {const prev = s.byId[id] ?? EMPTY- if (prev.state === state && (agentId === undefined || prev.agentId === agentId)) return s- const next = { ...prev, state }+ const now = Date.now()+ // Done-holdoff: a late working event (parallel hook curls arrive out of order, or a+ // tool POST that was in flight when the user interrupted) must not resurrect a turn+ // that just finished. Only a genuine new turn (UserPromptSubmit) may.+ if (+ state === 'working' &&+ !newTurn &&+ prev.state === 'done' &&+ now - (prev.stateAt ?? 0) < DONE_HOLDOFF_MS+ ) {+ return s+ }+ if (prev.state === state && (agentId === undefined || prev.agentId === agentId)) {+ // Same-state event: refresh freshness in place — stateAt is never rendered, and a+ // new object here would re-render every node header on each tool event.+ if (s.byId[id]) s.byId[id].stateAt = now+ return s+ }+ const next = { ...prev, state, stateAt: now }if (agentId !== undefined) next.agentId = agentIdreturn { byId: { ...s.byId, [id]: next } }}),+ sweepStaleWorking: (staleMs = STALE_WORKING_MS) =>+ set((s) => {+ const now = Date.now()+ let changed = false+ const byId = { ...s.byId }+ for (const [id, v] of Object.entries(byId)) {+ if (v.state === 'working' && now - (v.stateAt ?? 0) > staleMs) {+ byId[id] = { ...v, state: undefined, stateAt: now }+ changed = true+ }+ }+ return changed ? { byId } : s+ }),+setSession: (id, session) =>set((s) => {const prev = s.byId[id] ?? EMPTY@@ -189,3 +241,24 @@ export const useAgentStatus = create<AgentStatusStore>((set) => ({return { byId }})}))++/**+ * Esc/Ctrl-C interrupt inference (REF-style): Claude Code fires NO hook when the user+ * cancels a turn, so a node interrupted mid-work would sit on "working" forever. Called+ * from the terminal's input path on a lone Esc / Ctrl-C: wait one settle window; if the+ * node is still `working` and NOT ONE hook event arrived since the keystroke (stateAt+ * unchanged), conclude the turn was cancelled and flip it to done. A wrong guess+ * self-corrects: the next real hook event sets working again (it's past the holdoff).+ */+export function inferInterruptAfterSettle(id: string, settleMs = INTERRUPT_SETTLE_MS): void {+ const st = useAgentStatus.getState().byId[id]+ if (st?.state !== 'working') return+ const baseline = st.stateAt+ setTimeout(() => {+ const cur = useAgentStatus.getState()+ const now = cur.byId[id]+ if (now?.state === 'working' && now.stateAt === baseline) {+ cur.setState(id, 'done', now.agentId)+ }+ }, settleMs)+}diff --git a/src/shared/agents/normalize.test.ts b/src/shared/agents/normalize.test.tsnew file mode 100644index 000000000..780dde14f--- /dev/null+++ b/src/shared/agents/normalize.test.ts@@ -0,0 +1,40 @@+import { describe, it, expect } from 'vitest'+import { normalizeClaude, type RawHookEnvelope } from './normalize'++function env(payload: Record<string, unknown>): RawHookEnvelope {+ return { nodeId: 'n1', agentId: 'claude', payload }+}++describe('normalizeClaude — turn-end signals', () => {+ it('Stop → done, not interrupted', () => {+ const e = normalizeClaude(env({ hook_event_name: 'Stop', session_id: 's1' }))+ expect(e).toMatchObject({ kind: 'state', state: 'done', sessionId: 's1' })+ expect(e?.interrupted).toBeFalsy()+ })++ it('Stop with is_interrupt → done + interrupted (user pressed Esc)', () => {+ const e = normalizeClaude(env({ hook_event_name: 'Stop', is_interrupt: true }))+ expect(e).toMatchObject({ kind: 'state', state: 'done', interrupted: true })+ })++ // Claude Code skips the normal Stop hook when the turn dies on an API/model error and+ // fires StopFailure instead — without mapping it, the badge sticks on RUNNING forever.+ it('StopFailure → done (API-error turn end)', () => {+ const e = normalizeClaude(env({ hook_event_name: 'StopFailure' }))+ expect(e).toMatchObject({ kind: 'state', state: 'done' })+ })+})++describe('normalizeClaude — permission signals', () => {+ it('PermissionRequest → blocked', () => {+ const e = normalizeClaude(env({ hook_event_name: 'PermissionRequest' }))+ expect(e).toMatchObject({ kind: 'state', state: 'blocked' })+ })++ it('Notification permission_prompt still maps to blocked', () => {+ const e = normalizeClaude(+ env({ hook_event_name: 'Notification', notification_type: 'permission_prompt' })+ )+ expect(e).toMatchObject({ kind: 'state', state: 'blocked' })+ })+})diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.tsindex edabaef37..a54b481f9 100644--- a/src/shared/agents/normalize.ts+++ b/src/shared/agents/normalize.ts@@ -9,6 +9,9 @@ export interface NormalizedAgentEvent {agentId: AgentIdkind: 'state' | 'subagent-start' | 'subagent-end' | 'recurring' | 'session'state?: AgentState+ // done only: the turn ended because the user interrupted (Esc/Ctrl-C) — the renderer+ // skips the completion alert/unread for these (the user was right there).+ interrupted?: boolean// true only for a genuine new turn (Claude UserPromptSubmit), so the renderer can// clear per-turn fan-out without clearing on every mid-turn tool event.newTurn?: boolean@@ -47,6 +50,7 @@ interface ClaudePayload {hook_event_name?: stringsession_id?: stringnotification_type?: string+ is_interrupt?: booleanlast_assistant_message?: stringprompt?: stringtool_name?: string@@ -122,8 +126,23 @@ export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | nureturn { ...base, kind: 'state', state: 'working', task: p.prompt, newTurn: true }}if (ev === 'Stop') {+ return {+ ...base,+ kind: 'state',+ state: 'done',+ interrupted: p.is_interrupt === true,+ lastMessage: p.last_assistant_message+ }+ }+ // The turn died on an API/model error — Claude Code skips the normal Stop hook here,+ // so without this the node would sit on "working" forever.+ if (ev === 'StopFailure') {return { ...base, kind: 'state', state: 'done', lastMessage: p.last_assistant_message }}+ // The dedicated permission hook (more direct than Notification's permission_prompt).+ if (ev === 'PermissionRequest') {+ return { ...base, kind: 'state', state: 'blocked', lastMessage: p.last_assistant_message }+ }if (ev === 'Notification') {const state: AgentState = p.notification_type === 'permission_prompt' ? 'blocked' : 'waiting'return { ...base, kind: 'state', state, lastMessage: p.last_assistant_message }