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
feat(agents): mirror live agent status to agent-status.json
enes72c19ad62da0
diff --git a/src/main/agent-status-mirror.test.ts b/src/main/agent-status-mirror.test.tsnew file mode 100644index 000000000..6c19acfb7--- /dev/null+++ b/src/main/agent-status-mirror.test.ts@@ -0,0 +1,175 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import type { NormalizedAgentEvent } from '@shared/agents/normalize'+import {+ reduceEntry,+ buildFile,+ recordAgentEvent,+ clearNode,+ flush,+ initAgentStatusMirror,+ _resetForTest,+ _snapshot,+ DONE_HOLDOFF_MS,+ EXPIRE_MS,+ type MirrorEntry+} from './agent-status-mirror'++// Minimal event factory — only the fields the reducer reads.+function ev(partial: Partial<NormalizedAgentEvent>): NormalizedAgentEvent {+ return { nodeId: 'n1', agentId: 'claude', kind: 'state', ...partial } as NormalizedAgentEvent+}++describe('reduceEntry (main-state reduction)', () => {+ it('reduces working → done and records the turn end', () => {+ const a = reduceEntry(undefined, ev({ kind: 'state', state: 'working', newTurn: true }), 1000)+ expect(a.state).toBe('working')+ expect(a.updatedAt).toBe(1000)+ const b = reduceEntry(a, ev({ kind: 'state', state: 'done' }), 2000)+ expect(b.state).toBe('done')+ expect(b.updatedAt).toBe(2000)+ })++ it('captures agentId + sessionId off any event', () => {+ const a = reduceEntry(undefined, ev({ agentId: 'codex', sessionId: 'sess-1', state: 'working' }), 1)+ expect(a.agentId).toBe('codex')+ expect(a.sessionId).toBe('sess-1')+ })++ it('holds done against a late non-newTurn working within the holdoff window', () => {+ const done: MirrorEntry = { state: 'done', agentId: 'claude', updatedAt: 5000 }+ const late = reduceEntry(done, ev({ kind: 'state', state: 'working' }), 5000 + DONE_HOLDOFF_MS - 1)+ expect(late.state).toBe('done')+ expect(late.updatedAt).toBe(5000) // timestamp not refreshed — holdoff keeps measuring from done+ })++ it('lets a genuine new turn override done inside the holdoff window', () => {+ const done: MirrorEntry = { state: 'done', agentId: 'claude', updatedAt: 5000 }+ const turn = reduceEntry(done, ev({ kind: 'state', state: 'working', newTurn: true }), 5000 + 1)+ expect(turn.state).toBe('working')+ })++ it('lets working resume after the holdoff window elapses', () => {+ const done: MirrorEntry = { state: 'done', agentId: 'claude', updatedAt: 5000 }+ const after = reduceEntry(done, ev({ kind: 'state', state: 'working' }), 5000 + DONE_HOLDOFF_MS + 1)+ expect(after.state).toBe('working')+ })++ it('subagent + recurring events do NOT clobber the main state', () => {+ let e: MirrorEntry = reduceEntry(undefined, ev({ kind: 'state', state: 'working' }), 1000)+ e = reduceEntry(e, ev({ kind: 'subagent-start', toolUseId: 't1', sessionId: 's9' }), 1100)+ expect(e.state).toBe('working')+ expect(e.sessionId).toBe('s9') // identity still captured+ e = reduceEntry(e, ev({ kind: 'subagent-end', toolUseId: 't1' }), 1200)+ expect(e.state).toBe('working')+ e = reduceEntry(e, ev({ kind: 'recurring', recurringKind: 'cron' }), 1300)+ expect(e.state).toBe('working')+ expect(e.updatedAt).toBe(1000) // identity-only events don't refresh state freshness+ })++ it('session start/end resets the node to idle', () => {+ const working = reduceEntry(undefined, ev({ kind: 'state', state: 'working' }), 1000)+ const started = reduceEntry(working, ev({ kind: 'session', sessionPhase: 'start' }), 2000)+ expect(started.state).toBeUndefined()+ const done = reduceEntry(started, ev({ kind: 'state', state: 'done' }), 3000)+ const ended = reduceEntry(done, ev({ kind: 'session', sessionPhase: 'end' }), 4000)+ expect(ended.state).toBeUndefined()+ expect(ended.agentId).toBe('claude') // identity preserved across reset+ })++ it('refreshes freshness on a same-state working (mid-turn tool events)', () => {+ const a = reduceEntry(undefined, ev({ kind: 'state', state: 'working' }), 1000)+ const b = reduceEntry(a, ev({ kind: 'state', state: 'working' }), 9000)+ expect(b.state).toBe('working')+ expect(b.updatedAt).toBe(9000)+ })+})++describe('buildFile (shape + expiry)', () => {+ it('produces the documented JSON shape', () => {+ const now = 10_000+ const doc = buildFile(+ { n1: { state: 'working', agentId: 'claude', sessionId: 's1', updatedAt: now } },+ now+ )+ expect(doc.v).toBe(1)+ expect(doc.updatedAt).toBe(now)+ expect(doc.nodes.n1).toEqual({+ state: 'working',+ agentId: 'claude',+ sessionId: 's1',+ updatedAt: now+ })+ })++ it('drops entries older than the expiry window', () => {+ const now = EXPIRE_MS + 100_000+ const doc = buildFile(+ {+ fresh: { state: 'working', updatedAt: now - 1000 },+ stale: { state: 'working', updatedAt: now - EXPIRE_MS - 1 }+ },+ now+ )+ expect(Object.keys(doc.nodes)).toEqual(['fresh'])+ })++ it('omits an undefined state (idle node keeps identity)', () => {+ const doc = buildFile({ n1: { agentId: 'claude', sessionId: 's1', updatedAt: 5 } }, 5)+ expect('state' in JSON.parse(JSON.stringify(doc)).nodes.n1).toBe(false)+ expect(JSON.parse(JSON.stringify(doc)).nodes.n1).toEqual({+ agentId: 'claude',+ sessionId: 's1',+ updatedAt: 5+ })+ })+})++describe('recordAgentEvent + atomic write', () => {+ let dir: string+ let file: string++ beforeEach(() => {+ _resetForTest()+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-status-'))+ file = path.join(dir, 'agent-status.json')+ initAgentStatusMirror(file)+ })++ afterEach(() => {+ _resetForTest()+ fs.rmSync(dir, { recursive: true, force: true })+ })++ it('records events into memory and flushes valid JSON to disk', async () => {+ recordAgentEvent(ev({ nodeId: 'n1', state: 'working', sessionId: 's1' }))+ recordAgentEvent(ev({ nodeId: 'n1', state: 'done' }))+ expect(_snapshot().n1.state).toBe('done')++ await flush()+ const doc = JSON.parse(fs.readFileSync(file, 'utf-8'))+ expect(doc.v).toBe(1)+ expect(typeof doc.updatedAt).toBe('number')+ expect(doc.nodes.n1.state).toBe('done')+ expect(doc.nodes.n1.sessionId).toBe('s1')+ expect(doc.nodes.n1.agentId).toBe('claude')+ })++ it('writes the file with 0600 permissions', async () => {+ recordAgentEvent(ev({ state: 'working' }))+ await flush()+ const mode = fs.statSync(file).mode & 0o777+ expect(mode).toBe(0o600)+ })++ it('clearNode removes an entry from the written file', async () => {+ recordAgentEvent(ev({ nodeId: 'a', state: 'working' }))+ recordAgentEvent(ev({ nodeId: 'b', state: 'working' }))+ clearNode('a')+ await flush()+ const doc = JSON.parse(fs.readFileSync(file, 'utf-8'))+ expect(Object.keys(doc.nodes)).toEqual(['b'])+ })+})diff --git a/src/main/agent-status-mirror.ts b/src/main/agent-status-mirror.tsnew file mode 100644index 000000000..a4803d452--- /dev/null+++ b/src/main/agent-status-mirror.ts@@ -0,0 +1,187 @@+import fs from 'fs'+import path from 'path'+import { app } from 'electron'+import type { AgentId } from '@shared/agents/config'+import type { AgentState, NormalizedAgentEvent } from '@shared/agents/normalize'++/**+ * Mirrors the live per-node agent status to a small JSON file so an EXTERNAL reader (the+ * nodeterm mobile host agent) can render running/waiting/blocked/done badges without an IPC+ * connection into the renderer. This is a READ-ONLY side-channel: it never feeds back into the+ * app and never changes renderer behavior.+ *+ * The reduction here intentionally mirrors the renderer store `state/agentStatus.ts` for the+ * MAIN state only:+ * - only `kind:'state'` events (which carry a `state`) move the working/waiting/blocked/done+ * state, guarded by the same done-holdoff (a late, non-newTurn `working` must not resurrect a+ * turn that just finished);+ * - `kind:'session'` (start/end) resets the node to idle (state cleared), like the renderer's+ * `setState(id, undefined)`;+ * - `subagent-start` / `subagent-end` / `recurring` events do NOT touch the main state — they+ * only capture identity (agentId / sessionId), exactly as the renderer routes them to the+ * subagent / loop stores instead of `setState`.+ * `sessionId`/`agentId` are captured off any event (the renderer calls `setSessionId` on every+ * event and threads `agentId` through `setState`).+ */++// Keep in sync with the renderer store's DONE_HOLDOFF_MS: Claude runs hooks in parallel, so a+// late PostToolUse `working` POST can arrive after the `Stop` `done`. Hold `done` against any+// non-newTurn `working` for this long.+export const DONE_HOLDOFF_MS = 3000+// Drop entries whose state hasn't been refreshed in this long, so the file can't accumulate+// unbounded nodes or advertise a stale "working" from a crashed/abandoned session.+export const EXPIRE_MS = 6 * 60 * 60_000+// Coalesce bursty hook POSTs (a single turn fires many tool events) into one disk write.+export const WRITE_DEBOUNCE_MS = 300++export interface MirrorEntry {+ /** working/waiting/blocked/done; undefined = idle/unknown (e.g. after a session reset). */+ state?: AgentState+ agentId?: AgentId+ sessionId?: string+ /**+ * When the state was last asserted (freshness). Drives the done-holdoff and the expiry+ * sweep — refreshed by every state/session reduction (incl. same-state working from tool+ * events), left alone by identity-only (subagent/recurring) events and holdoff-ignored ones.+ */+ updatedAt: number+}++export interface MirrorFile {+ v: 1+ updatedAt: number+ nodes: Record<string, { state?: AgentState; agentId?: AgentId; sessionId?: string; updatedAt: number }>+}++/**+ * Pure reducer: fold one event into a node's entry, mirroring the renderer store's MAIN-state+ * semantics. Returns the next entry (never mutates `prev`). `now` is injected for testability.+ */+export function reduceEntry(+ prev: MirrorEntry | undefined,+ ev: NormalizedAgentEvent,+ now: number+): MirrorEntry {+ const next: MirrorEntry = prev ? { ...prev } : { updatedAt: now }+ // Identity is captured off ANY event (mirrors the renderer's per-event setSessionId ++ // agentId threading). agentId is always present on a NormalizedAgentEvent.+ if (ev.agentId) next.agentId = ev.agentId+ if (ev.sessionId) next.sessionId = ev.sessionId++ if (ev.kind === 'state' && ev.state) {+ // Done-holdoff: a late, non-newTurn `working` (out-of-order parallel hook, or an in-flight+ // tool POST at interrupt) must not resurrect a turn that just finished. Only a genuine new+ // turn (UserPromptSubmit) may. Leave state + updatedAt untouched so the window keeps+ // measuring from the `done`.+ const heldOff =+ ev.state === 'working' &&+ !ev.newTurn &&+ prev?.state === 'done' &&+ now - (prev.updatedAt ?? 0) < DONE_HOLDOFF_MS+ if (!heldOff) {+ next.state = ev.state+ next.updatedAt = now+ }+ } else if (ev.kind === 'session') {+ // SessionStart / SessionEnd both reset the node to idle (renderer: setState(id, undefined)).+ next.state = undefined+ next.updatedAt = now+ }+ // subagent-start / subagent-end / recurring: identity captured above, main state untouched.+ return next+}++/** Prune expired entries and shape the on-disk file. Pure; `now` injected for testability. */+export function buildFile(+ nodes: Record<string, MirrorEntry>,+ now: number,+ expireMs = EXPIRE_MS+): MirrorFile {+ const out: MirrorFile = { v: 1, updatedAt: now, nodes: {} }+ for (const [id, e] of Object.entries(nodes)) {+ if (now - e.updatedAt > expireMs) continue+ // Undefined fields drop out of JSON.stringify — an idle node keeps agentId/sessionId+ // without a `state` key.+ out.nodes[id] = { state: e.state, agentId: e.agentId, sessionId: e.sessionId, updatedAt: e.updatedAt }+ }+ return out+}++// ---- Stateful singleton (production side) --------------------------------------------------++const state = new Map<string, MirrorEntry>()+let targetFile: string | null = null+let writeTimer: NodeJS.Timeout | null = null+let writeSeq = 0++/**+ * Point the mirror at its file. Called once from main on launch; the path defaults to+ * `<userData>/agent-status.json`. Tests pass an explicit path (and thus never touch electron).+ */+export function initAgentStatusMirror(filePath?: string): void {+ targetFile = filePath ?? path.join(app.getPath('userData'), 'agent-status.json')+}++function resolveFile(): string | null {+ if (targetFile) return targetFile+ try {+ targetFile = path.join(app.getPath('userData'), 'agent-status.json')+ return targetFile+ } catch {+ return null+ }+}++/** Fold a normalized agent event into the mirror and schedule a debounced write. */+export function recordAgentEvent(ev: NormalizedAgentEvent): void {+ if (!ev?.nodeId) return+ state.set(ev.nodeId, reduceEntry(state.get(ev.nodeId), ev, Date.now()))+ scheduleWrite()+}++/** Remove a node (call on permanent destroy). Schedules a write so the file drops it. */+export function clearNode(nodeId: string): void {+ if (state.delete(nodeId)) scheduleWrite()+}++function scheduleWrite(): void {+ if (writeTimer) return+ writeTimer = setTimeout(() => {+ writeTimer = null+ void flush()+ }, WRITE_DEBOUNCE_MS)+ // Never let the mirror keep the app alive on quit.+ writeTimer.unref?.()+}++/** Prune + atomically write the file (tmp + rename, mode 0600). Best-effort. */+export async function flush(): Promise<void> {+ const file = resolveFile()+ if (!file) return+ const now = Date.now()+ const doc = buildFile(Object.fromEntries(state), now)+ // Also drop expired entries from memory so the map itself can't grow without bound.+ for (const [id, e] of state) if (now - e.updatedAt > EXPIRE_MS) state.delete(id)+ const tmp = `${file}.${process.pid}.${++writeSeq}.tmp`+ try {+ await fs.promises.writeFile(tmp, JSON.stringify(doc), { mode: 0o600 })+ await fs.promises.rename(tmp, file)+ } catch {+ await fs.promises.rm(tmp, { force: true }).catch(() => {})+ }+}++// ---- Test helpers --------------------------------------------------------------------------++/** Reset all module state (in-memory map + config). Test-only. */+export function _resetForTest(): void {+ state.clear()+ targetFile = null+ if (writeTimer) clearTimeout(writeTimer)+ writeTimer = null+}++/** Snapshot the in-memory map. Test-only. */+export function _snapshot(): Record<string, MirrorEntry> {+ return Object.fromEntries(state)+}diff --git a/src/main/chat-driver.ts b/src/main/chat-driver.tsindex 65b1a3ffd..0a6ddffdd 100644--- a/src/main/chat-driver.ts+++ b/src/main/chat-driver.ts@@ -9,6 +9,7 @@ import { sdkMessageToEvents } from './chat-events'import { ChatInputQueue, createPushIterable } from './chat-queue'import { resolveTranscriptPath } from './transcript-reader'import { claudeConfigDirFor } from './claude-accounts'+import { recordAgentEvent } from './agent-status-mirror'import { AUTH_ENV_STRIP } from './claude-accounts-core'interface PendingPermission { resolve: (d: ChatPermissionDecision) => void }@@ -62,6 +63,7 @@ export class ChatDriver {sessionId: s.sessionId, ...(interrupted ? { interrupted: true } : {})}this.sendToMain(IPC.agentStatus, ev)+ recordAgentEvent(ev)}async ensure(diff --git a/src/main/index.ts b/src/main/index.tsindex 93f4b97a4..dd1f72842 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -14,6 +14,7 @@ import { initUpdater } from './updater'import { fetchCheck } from './check'import { hookServer } from './agents/hook-server'import { setMainWindow, getMainWindow, sendToMain, shouldHideOnClose } from './main-window'+import { initAgentStatusMirror, recordAgentEvent } from './agent-status-mirror'import { retainUntilDismissed } from './notifications'import { installManagedAgentHooks } from './agents/hooks'import { createSubagentTail } from './subagent-tail'@@ -426,6 +427,8 @@ app.whenReady().then(async () => {const win = createWindow()initUpdater(win)+ // Mirror live agent status to <userData>/agent-status.json for the external mobile host agent.+ initAgentStatusMirror()// Agent hooks: install the managed hook script into each agent's config, then start the// local HTTP server that receives hook posts and forwards normalized events to the renderer.@@ -440,14 +443,16 @@ app.whenReady().then(async () => {let nodeId: string | undefinedfor (const [nid, sid] of nodeContextSession) if (sid === sessionId) nodeId = nidif (!nodeId) return- sendToMain(IPC.agentStatus, {+ const taskDoneEvent = {nodeId,agentId: 'claude',sessionId,kind: 'subagent-end',toolUseId: n.toolUseId,result: n.result- } satisfies NormalizedAgentEvent)+ } satisfies NormalizedAgentEvent+ sendToMain(IPC.agentStatus, taskDoneEvent)+ recordAgentEvent(taskDoneEvent)subagentTail.finish(n.toolUseId)remoteSubagentTail.untrack(n.toolUseId)nodeSubagents.get(nodeId)?.delete(n.toolUseId)@@ -603,7 +608,10 @@ app.whenReady().then(async () => {console.warn(`[agent-hooks] account ${acct.id} hook install failed`, e)}}- hookServer.setListener((e) => sendToMain(IPC.agentStatus, e))+ hookServer.setListener((e) => {+ sendToMain(IPC.agentStatus, e)+ recordAgentEvent(e)+ })// Security: hook POSTs now arrive over the remote reverse tunnel too (SSH Phase 2a), so a// forged/remote POST could set transcript_path to an arbitrary LOCAL path (e.g. ~/.ssh/id_rsa)// and have the app read it. The tails read the LOCAL filesystem; legitimate LOCAL transcripts