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
chore(agents): remove dead claude-hooks; rename store types; update project docs
enes7f21ee8f404f
diff --git a/src/main/claude-hooks.ts b/src/main/claude-hooks.tsdeleted file mode 100644index f5d88a744..000000000--- a/src/main/claude-hooks.ts+++ /dev/null@@ -1,220 +0,0 @@-// Robust Claude Code state detection via Claude's own hooks (the same approach REF uses).-//-// We install ONE managed hook command into the user's ~/.claude/settings.json (merged,-// preserving their existing config; idempotent). The command is env-gated: it does nothing-// unless NODETERM_NODE_ID is set, so it's a no-op in the user's normal terminals and only-// activates in sessions nodeterm spawns (which set NODETERM_NODE_ID/NODETERM_HOOK_DIR via-// tmux `-e`). When active it appends the hook's JSON payload to a per-node log file; the-// main process watches that dir and forwards each event to the renderer over `claude:status`.-// Because the hook lives in the global settings, ANY `claude` run inside nodeterm (including-// one the user types by hand) is detected — not just the managed Claude Code node.-import fs from 'fs'-import os from 'os'-import path from 'path'-import { app, type BrowserWindow } from 'electron'-import { IPC } from '../shared/ipc'-import { createSubagentTail } from './subagent-tail'-import { createContextTail } from './context-tail'--const CLAUDE_EVENTS = [- 'SessionStart',- 'UserPromptSubmit',- 'Stop',- 'Notification',- 'SessionEnd',- 'PreToolUse',- 'PostToolUse'-]--// Tool names that represent a spawned subagent.-const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])-// Tools that set up a recurring task (drive the loop/schedule/cron node).-const RECURRING_TOOLS = new Set(['Skill', 'CronCreate', 'ScheduleWakeup'])--// The single managed hook command, registered under each event above. Must stay byte-stable-// so install is idempotent and uninstall can find it. Reads the hook payload from stdin and-// appends it (Claude's payload already carries hook_event_name + session_id).-const MANAGED_CMD =- '[ -z "$NODETERM_NODE_ID" ] && exit 0; mkdir -p "$NODETERM_HOOK_DIR" 2>/dev/null; { cat; printf "\\n"; } >> "$NODETERM_HOOK_DIR/$NODETERM_NODE_ID.log" 2>/dev/null || true'--let hookDir = ''--export function claudeHookDir(): string {- if (!hookDir) hookDir = path.join(app.getPath('userData'), 'claude-signals')- return hookDir-}--interface HookDef {- hooks?: { type?: string; command?: string }[]-}--/** Merge our managed hook into ~/.claude/settings.json, preserving everything else. */-function installHooks(): void {- const cfgPath = path.join(os.homedir(), '.claude', 'settings.json')- let config: { hooks?: Record<string, HookDef[]>; [k: string]: unknown } = {}- if (fs.existsSync(cfgPath)) {- try {- config = JSON.parse(fs.readFileSync(cfgPath, 'utf-8'))- } catch {- // Don't risk corrupting an unparseable settings file.- console.error('[claude-hooks] ~/.claude/settings.json is not valid JSON; skipping install')- return- }- }- if (!config.hooks || typeof config.hooks !== 'object') config.hooks = {}- let changed = false- for (const ev of CLAUDE_EVENTS) {- const existing = config.hooks[ev]- if (existing && !Array.isArray(existing)) continue // leave unexpected shapes alone- const list = Array.isArray(existing) ? existing : (config.hooks[ev] = [])- const present = list.some((d) => (d.hooks ?? []).some((h) => h.command === MANAGED_CMD))- if (!present) {- list.push({ hooks: [{ type: 'command', command: MANAGED_CMD }] })- changed = true- }- }- if (changed) {- try {- fs.mkdirSync(path.dirname(cfgPath), { recursive: true })- fs.writeFileSync(cfgPath, JSON.stringify(config, null, 2))- } catch (e) {- console.error('[claude-hooks] failed writing ~/.claude/settings.json', e)- }- }-}--/** Install hooks, clear stale signals, and watch for new hook events. */-export function initClaudeHooks(win: BrowserWindow): void {- installHooks()- const dir = claudeHookDir()- try {- fs.mkdirSync(dir, { recursive: true })- for (const f of fs.readdirSync(dir)) {- if (f.endsWith('.log')) fs.rmSync(path.join(dir, f), { force: true })- }- } catch (e) {- console.error('[claude-hooks] signal dir setup failed', e)- return- }-- const offsets = new Map<string, number>()- const subagentTail = createSubagentTail(win)- const contextTail = createContextTail(win)-- const scan = () => {- let files: string[]- try {- files = fs.readdirSync(dir)- } catch {- return- }- for (const f of files) {- if (!f.endsWith('.log')) continue- const full = path.join(dir, f)- let size: number- try {- size = fs.statSync(full).size- } catch {- continue- }- const prev = offsets.get(f) ?? 0- if (size <= prev) {- offsets.set(f, size)- continue- }- let chunk = ''- try {- const fd = fs.openSync(full, 'r')- const buf = Buffer.alloc(size - prev)- fs.readSync(fd, buf, 0, buf.length, prev)- fs.closeSync(fd)- chunk = buf.toString('utf-8')- } catch {- continue- }- offsets.set(f, size)- const nodeId = f.slice(0, -4)- for (const line of chunk.split('\n')) {- const t = line.trim()- if (!t) continue- try {- const p = JSON.parse(t) as {- hook_event_name?: string- session_id?: string- transcript_path?: string- notification_type?: string- last_assistant_message?: string- prompt?: string- tool_name?: string- tool_use_id?: string- tool_input?: {- subagent_type?: string- description?: string- prompt?: string- skill?: string- cron?: string- }- tool_response?: {- status?: string- content?: { type?: string; text?: string }[]- totalDurationMs?: number- totalTokens?: number- totalToolUseCount?: number- }- }- if (!p.hook_event_name || win.isDestroyed()) continue- // Context-window meter: tail the session transcript (any event carries both fields).- if (p.session_id && p.transcript_path) contextTail.track(p.session_id, p.transcript_path)- if (p.hook_event_name === 'SessionEnd' && p.session_id) contextTail.untrack(p.session_id)- // Tool events flood (every Bash/Edit) — only forward subagent + recurring tools.- const name = p.tool_name ?? ''- const isTool = p.hook_event_name === 'PreToolUse' || p.hook_event_name === 'PostToolUse'- if (isTool && !SUBAGENT_TOOLS.has(name) && !RECURRING_TOOLS.has(name)) continue- // Tail the subagent's live transcript while it runs (subagent tools only).- if (SUBAGENT_TOOLS.has(name) && p.tool_use_id) {- if (p.hook_event_name === 'PreToolUse') subagentTail.track(p.tool_use_id, p.transcript_path)- else if (p.hook_event_name === 'PostToolUse') subagentTail.finish(p.tool_use_id)- }- const tr = p.tool_response- const result = tr?.content- ?.filter((c) => c.type === 'text' && c.text)- .map((c) => c.text)- .join('\n')- win.webContents.send(IPC.agentStatus, {- nodeId,- event: p.hook_event_name,- sessionId: p.session_id,- notificationType: p.notification_type,- lastMessage: p.last_assistant_message,- prompt: p.prompt,- toolName: p.tool_name,- toolUseId: p.tool_use_id,- subagentType: p.tool_input?.subagent_type,- taskLabel: p.tool_input?.description || p.tool_input?.prompt,- skill: p.tool_input?.skill,- schedule: p.tool_input?.cron,- status: tr?.status,- durationMs: tr?.totalDurationMs,- tokens: tr?.totalTokens,- toolUses: tr?.totalToolUseCount,- result- })- } catch {- // partial/garbled line; ignore- }- }- }- }-- // Event-driven only (no polling): fs.watch on the dir fires on every append here, and- // scan() reads offset-based, so each line is delivered exactly once.- let timer: ReturnType<typeof setTimeout> | null = null- try {- fs.watch(dir, () => {- if (timer) clearTimeout(timer)- timer = setTimeout(scan, 40)- })- } catch (e) {- console.error('[claude-hooks] watch failed', e)- }-}diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 228263cfd..8fa6f8326 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -1209,8 +1209,9 @@ export function Canvas() {[])- // Claude Code lifecycle, reported by Claude's own hooks (see main/claude-hooks.ts):- // UserPromptSubmit → working, Stop → done, Notification → waiting/blocked. On a turn+ // Agent lifecycle, reported by each agent's own hooks via the main-process hook server+ // (`main/agents/hook-server.ts`) and mapped to the shared 4-state model by the per-agent+ // normalizers (`shared/agents/normalize.ts`): working / waiting / blocked / done. On a turn// finishing / needing attention while the window is in the background: mark unread +// (with consent, throttled) notify.const notifyCooldownRef = useRef<Record<string, number>>({})diff --git a/src/renderer/components/Dock.tsx b/src/renderer/components/Dock.tsxindex aced3806f..f290fcc6f 100644--- a/src/renderer/components/Dock.tsx+++ b/src/renderer/components/Dock.tsx@@ -68,7 +68,7 @@ export function Dock({{customAgents.map((c) => (<button key={c.id} onClick={pick(() => onAddAgent(c.id))}><TerminalIcon />- <span>New {c.label}</span>+ <span>{c.label}</span></button>))}<button onClick={pick(onAddSticky)}>diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 83505a3a3..701ed1344 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -109,9 +109,9 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {let disposed = falseconst cleanups: Array<() => void> = []- // Claude Code state (busy/idle/attention) comes from Claude's own hooks via the- // claude:status IPC (handled centrally in Canvas) — not from parsing the output here.- // We only surface the conversation topic from the terminal title, when Claude sets one.+ // Agent state (busy/idle/attention) comes from the agent's own hooks via the+ // agent:status IPC (handled centrally in Canvas) — not from parsing the output here.+ // We only surface the conversation topic from the terminal title, when the agent sets one.if (showStatus) {cleanups.push(term.onTitleChange((t) => {@@ -337,7 +337,7 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {type="source"position={Position.Right}className="bridge-handle bridge-handle--out"- data-tip="Bridge out — drag to another Claude node to link their sessions"+ data-tip="Bridge out — drag to another bridge-capable node to link their sessions"/><Handleid="bridge-in"diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.tsindex 045d43dfb..bfea43b29 100644--- a/src/renderer/state/agentStatus.ts+++ b/src/renderer/state/agentStatus.ts@@ -1,16 +1,15 @@import { create } from 'zustand'import type { AgentId } from '@shared/agents/config'+import type { AgentState } from '@shared/agents/normalize'/*** Transient per-node status for agent (e.g. Claude Code) sessions, driven by the agent's hooks.* `unread`, `session` and `sessionId` are persisted to localStorage so they survive a* reload/restart; the live `state` (working/waiting/…) is not (it'd be stale on relaunch).*/-export type ClaudeState = 'working' | 'waiting' | 'blocked' | 'done'--export interface ClaudeNodeStatus {+export interface AgentNodeStatus {/** Live activity; undefined = idle/unknown. */- state?: ClaudeState+ state?: AgentState/** Which agent this node is running (claude/codex/gemini/…), when known. */agentId?: AgentId/** A turn finished / needs attention while the user wasn't looking. */@@ -32,12 +31,12 @@ export interface ClaudeNodeStatus {}}-interface ClaudeStatusState {- byId: Record<string, ClaudeNodeStatus>+interface AgentStatusStore {+ byId: Record<string, AgentNodeStatus>/** The terminal node the user is currently focused in (for unread decisions). */activeId: string | nullsetActive(id: string, active: boolean): void- setState(id: string, state: ClaudeState | undefined, agentId?: AgentId): void+ setState(id: string, state: AgentState | undefined, agentId?: AgentId): voidsetSession(id: string, session: string): voidsetSessionId(id: string, sessionId: string): voidmarkUnread(id: string): void@@ -54,7 +53,7 @@ interface ClaudeStatusState {remove(id: string): void}-const EMPTY: ClaudeNodeStatus = { unread: false }+const EMPTY: AgentNodeStatus = { unread: false }const KEY = 'nodeterm.agentStatus'// One-time localStorage migration from the old key. Runs before the store hydrates.@@ -68,12 +67,12 @@ try {/* ignore */}-function load(): Record<string, ClaudeNodeStatus> {+function load(): Record<string, AgentNodeStatus> {try {const raw = localStorage.getItem(KEY)if (!raw) return {}- const data = JSON.parse(raw) as Record<string, Partial<ClaudeNodeStatus>>- const out: Record<string, ClaudeNodeStatus> = {}+ const data = JSON.parse(raw) as Record<string, Partial<AgentNodeStatus>>+ const out: Record<string, AgentNodeStatus> = {}for (const [id, v] of Object.entries(data)) {out[id] = { unread: !!v.unread, session: v.session, sessionId: v.sessionId }}@@ -84,9 +83,9 @@ function load(): Record<string, ClaudeNodeStatus> {}// Persist only the durable fields (not the live `state`).-function save(byId: Record<string, ClaudeNodeStatus>): void {+function save(byId: Record<string, AgentNodeStatus>): void {try {- const out: Record<string, Partial<ClaudeNodeStatus>> = {}+ const out: Record<string, Partial<AgentNodeStatus>> = {}for (const [id, v] of Object.entries(byId)) {if (v.unread || v.session || v.sessionId) {out[id] = { unread: v.unread, session: v.session, sessionId: v.sessionId }@@ -98,7 +97,7 @@ function save(byId: Record<string, ClaudeNodeStatus>): void {}}-export const useAgentStatus = create<ClaudeStatusState>((set) => ({+export const useAgentStatus = create<AgentStatusStore>((set) => ({byId: load(),activeId: null,diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.tsindex 4425f9922..bcaff84a5 100644--- a/src/shared/agents/normalize.ts+++ b/src/shared/agents/normalize.ts@@ -91,7 +91,10 @@ export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | nudurationMs: p.tool_response?.totalDurationMs,tokens: p.tool_response?.totalTokens,toolUses: p.tool_response?.totalToolUseCount,- result: p.tool_response?.content?.map((c) => c.text ?? '').join('')+ result: p.tool_response?.content+ ?.filter((c) => c.type === 'text' && c.text)+ .map((c) => c.text)+ .join('\n')}}if (ev === 'PreToolUse' && RECURRING_TOOLS.has(tool)) {