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.

feat(server): agent-status wiring — hook listeners + tails route over platform.broadcast

enesd2e8bebb2bf7
diff --git a/src/server/agent-status.test.ts b/src/server/agent-status.test.ts
new file mode 100644
index 000000000..e2c64f5a6
--- /dev/null
+++ b/src/server/agent-status.test.ts
@@ -0,0 +1,98 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { ServerPlatform } from './platform-server'
+import { wireAgentStatus } from './agent-status'
+import { IPC } from '../shared/ipc'
+import { decodePtyData } from '../shared/rpc'
+
+// A fake hook server that captures the listeners wireAgentStatus installs, so the test can
+// fire raw + normalized events without binding a real port.
+function fakeHooks() {
+ let listener: ((e: unknown) => void) | undefined
+ let raw: ((agentId: string, nodeId: string, payload: Record<string, unknown>) => void) | undefined
+ return {
+ hooks: {
+ setListener: (cb: (e: unknown) => void) => {
+ listener = cb
+ },
+ setRawListener: (cb: typeof raw) => {
+ raw = cb
+ }
+ },
+ fireNormalized: (e: unknown) => listener?.(e),
+ fireRaw: (agentId: string, nodeId: string, payload: Record<string, unknown>) =>
+ raw?.(agentId, nodeId, payload)
+ }
+}
+
+// A recording tail so we can assert track/finish without touching the filesystem.
+function recTail() {
+ const calls: Array<{ m: string; args: unknown[] }> = []
+ return {
+ tail: {
+ track: (...args: unknown[]) => calls.push({ m: 'track', args }),
+ finish: (...args: unknown[]) => calls.push({ m: 'finish', args }),
+ untrack: (...args: unknown[]) => calls.push({ m: 'untrack', args })
+ },
+ calls
+ }
+}
+
+let dir: string, platform: ServerPlatform, sent: Array<{ channel: string; args: unknown[] }>
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-agst-'))
+ platform = new ServerPlatform({ userDataDir: dir, appVersion: '0' })
+ sent = []
+ // capture broadcasts by attaching a recording sink
+ platform.attach({
+ sendText: (json) => sent.push(JSON.parse(json)),
+ sendBinary: (buf) => {
+ const f = decodePtyData(buf)
+ if (f) sent.push({ channel: `pty:data:${f.sessionId}`, args: [f.data] })
+ }
+ })
+})
+afterEach(() => fs.rmSync(dir, { recursive: true, force: true }))
+
+describe('wireAgentStatus', () => {
+ it('broadcasts a normalized agent event on agent:status', () => {
+ const fh = fakeHooks()
+ wireAgentStatus(platform, { hooks: fh.hooks as never })
+ const ev = { nodeId: 'n1', agentId: 'claude', kind: 'state', state: 'working' }
+ fh.fireNormalized(ev)
+ expect(sent).toContainEqual({ t: 'ev', channel: IPC.agentStatus, args: [ev] })
+ })
+
+ it('tracks a subagent on PreToolUse(Task) and finishes it on PostToolUse', () => {
+ const fh = fakeHooks()
+ const sub = recTail()
+ wireAgentStatus(platform, { hooks: fh.hooks as never, subagentTail: sub.tail as never })
+ // PreToolUse for a subagent tool → track
+ fh.fireRaw('claude', 'n1', {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Task',
+ tool_use_id: 'tu1',
+ session_id: 's1'
+ })
+ expect(sub.calls.some((c) => c.m === 'track' && c.args[0] === 'tu1')).toBe(true)
+ // PostToolUse (non-async) → finish
+ fh.fireRaw('claude', 'n1', {
+ hook_event_name: 'PostToolUse',
+ tool_name: 'Task',
+ tool_use_id: 'tu1',
+ session_id: 's1',
+ tool_response: { status: 'success' }
+ })
+ expect(sub.calls.some((c) => c.m === 'finish' && c.args[0] === 'tu1')).toBe(true)
+ })
+
+ it('ignores non-claude raw events', () => {
+ const fh = fakeHooks()
+ const sub = recTail()
+ wireAgentStatus(platform, { hooks: fh.hooks as never, subagentTail: sub.tail as never })
+ fh.fireRaw('codex', 'n1', { hook_event_name: 'PreToolUse', tool_name: 'Task', tool_use_id: 'x' })
+ expect(sub.calls).toEqual([])
+ })
+})
diff --git a/src/server/agent-status.ts b/src/server/agent-status.ts
new file mode 100644
index 000000000..2d1f57bee
--- /dev/null
+++ b/src/server/agent-status.ts
@@ -0,0 +1,144 @@
+// Server-side agent-status wiring: a faithful transcription of the LOCAL (non-SSH) branch of
+// the hook-wiring block in `src/main/index.ts`, with the Electron seams swapped for the
+// headless server platform. Installs the hook server's normalized + raw listeners so agent
+// status badges, subagent live transcripts, and the context-window meter all reach the
+// browser over `platform.broadcast`. The SSH branch (remote tails / RemoteFile) is dropped —
+// the server has no SSH-project manager — so the raw listener falls straight through to the
+// local logic.
+//
+// This module must import nothing from electron or `../main` (see no-electron.test.ts).
+import { resolve } from 'path'
+import { homedir } from 'os'
+import { hookServer } from '../core/agents/hook-server'
+import { recordAgentEvent } from '../core/agent-status-mirror'
+import { createSubagentTail, type SubagentTail } from '../core/subagent-tail'
+import { createContextTail, type ContextTail, type TaskNotification } from '../core/context-tail'
+import { setNodeTranscript } from '../core/context-link'
+import { isSafeLocalTranscriptPath } from '../core/claude-accounts-core'
+import { isAsyncSubagentLaunch, type NormalizedAgentEvent } from '../shared/agents/normalize'
+import { IPC } from '../shared/ipc'
+import type { ServerPlatform } from './platform-server'
+
+/** The narrow surface of the hook server this module needs — injectable for tests. */
+export interface HookLike {
+ setListener(cb: (e: NormalizedAgentEvent) => void): void
+ setRawListener(cb: (agentId: string, nodeId: string, payload: Record<string, unknown>) => void): void
+}
+
+export interface WireAgentStatusOptions {
+ hooks?: HookLike
+ subagentTail?: SubagentTail
+ contextTail?: ContextTail
+}
+
+/**
+ * Install the hook listeners that drive agent-status badges, subagent viz, and the context
+ * meter, routing every push over `platform.broadcast`. Injectable seams (`opts`) let tests
+ * fire events without binding a real port or touching the filesystem; production defaults use
+ * the real `hookServer` singleton and real tails.
+ *
+ * Does NOT call `hookServer.start()` — the boot step owns starting the server.
+ */
+export function wireAgentStatus(platform: ServerPlatform, opts: WireAgentStatusOptions = {}): void {
+ const hooks = opts.hooks ?? hookServer
+ // nodeId → claude sessionId
+ const nodeContextSession = new Map<string, string>()
+ // nodeId → active subagent tool_use_ids
+ const nodeSubagents = new Map<string, Set<string>>()
+
+ const subagentTail =
+ opts.subagentTail ??
+ createSubagentTail(({ toolUseId, chunk }) => {
+ platform.broadcast(IPC.agentSubagentActivity, { toolUseId, chunk })
+ })
+
+ // Async subagents (Claude's default) end via a <task-notification> queued into the PARENT
+ // transcript — their PostToolUse is only a launch ack. The context tail reads that transcript,
+ // surfaces the notification here, and we emit the synthetic subagent-end the hooks never send,
+ // then release the subagent transcript tail.
+ const onTaskNotification = (sessionId: string, n: TaskNotification): void => {
+ let nodeId: string | undefined
+ for (const [nid, sid] of nodeContextSession) if (sid === sessionId) nodeId = nid
+ if (!nodeId) return
+ const taskDoneEvent = {
+ nodeId,
+ agentId: 'claude',
+ sessionId,
+ kind: 'subagent-end',
+ toolUseId: n.toolUseId,
+ result: n.result
+ } satisfies NormalizedAgentEvent
+ platform.broadcast(IPC.agentStatus, taskDoneEvent)
+ recordAgentEvent(taskDoneEvent)
+ subagentTail.finish(n.toolUseId)
+ nodeSubagents.get(nodeId)?.delete(n.toolUseId)
+ }
+
+ const contextTail =
+ opts.contextTail ??
+ createContextTail(
+ (payload) => {
+ platform.broadcast(IPC.contextUpdate, payload)
+ },
+ { onTaskNotification }
+ )
+
+ hooks.setListener((e) => {
+ platform.broadcast(IPC.agentStatus, e)
+ recordAgentEvent(e)
+ })
+
+ // Security: hook POSTs can be forged, so a forged 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 live under the system default
+ // `~/.claude/projects` OR a managed account's `{userData}/claude-accounts/<id>/projects`
+ // (id-validated so a forged POST can't traverse out — see isSafeLocalTranscriptPath). Jail
+ // transcript_path to those roots and skip the read otherwise.
+ const safeTranscriptPath = (tp: string | undefined): string | undefined => {
+ if (!tp) return undefined
+ const abs = resolve(tp)
+ return isSafeLocalTranscriptPath(abs, homedir(), platform.userDataDir) ? abs : undefined
+ }
+
+ const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])
+ hooks.setRawListener((agentId, nodeId, payload) => {
+ if (agentId !== 'claude') return
+ const p = payload as {
+ hook_event_name?: string
+ session_id?: string
+ transcript_path?: string
+ tool_name?: string
+ tool_use_id?: string
+ tool_response?: { status?: string; isAsync?: boolean }
+ }
+ // An async subagent's PostToolUse is only the launch ack — keep tailing its transcript;
+ // the real end (task-notification via the context tail) releases it.
+ const asyncLaunch = p.hook_event_name === 'PostToolUse' && isAsyncSubagentLaunch(p.tool_response)
+ const transcriptPath = safeTranscriptPath(p.transcript_path)
+ // Context-window meter: tail the session transcript (any event carrying both fields).
+ if (p.session_id && transcriptPath) contextTail.track(p.session_id, transcriptPath)
+ if (nodeId && p.session_id) nodeContextSession.set(nodeId, p.session_id)
+ if (nodeId && p.session_id && transcriptPath) setNodeTranscript(nodeId, p.session_id, transcriptPath)
+ if (p.hook_event_name === 'SessionEnd' && p.session_id) contextTail.untrack(p.session_id)
+ // Subagent live transcript: track on PreToolUse / finish on PostToolUse for subagent tools.
+ if (p.tool_use_id && p.tool_name && SUBAGENT_TOOLS.has(p.tool_name)) {
+ if (p.hook_event_name === 'PreToolUse') {
+ subagentTail.track(p.tool_use_id, transcriptPath)
+ if (nodeId) {
+ const set = nodeSubagents.get(nodeId) ?? new Set<string>()
+ set.add(p.tool_use_id)
+ nodeSubagents.set(nodeId, set)
+ }
+ } else if (p.hook_event_name === 'PostToolUse' && !asyncLaunch) {
+ subagentTail.finish(p.tool_use_id)
+ if (nodeId) nodeSubagents.get(nodeId)?.delete(p.tool_use_id)
+ }
+ }
+ // Session over → release any still-tracked async subagent tails for this node (their
+ // task-notifications will never arrive once the session is gone).
+ if (p.hook_event_name === 'SessionEnd' && nodeId) {
+ for (const toolUseId of nodeSubagents.get(nodeId) ?? []) subagentTail.finish(toolUseId)
+ nodeSubagents.delete(nodeId)
+ }
+ })
+}