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(claude): REF-style global env-gated hooks + 4 states + cooldown + persist

enesc34867f5f80f
diff --git a/src/main/claude-hooks.ts b/src/main/claude-hooks.ts
index 9d0bd8b23..288c7ce90 100644
--- a/src/main/claude-hooks.ts
+++ b/src/main/claude-hooks.ts
@@ -1,81 +1,99 @@
-// Robust Claude Code state detection via Claude's own hooks (not terminal-output parsing).
+// Robust Claude Code state detection via Claude's own hooks (the same approach REF uses).
//
-// We write a settings file containing only hooks and launch Claude with `--settings <file>`
-// (non-invasive — it merges over the user's settings for that session only). Each hook
-// command inherits the env we set on the session (NODETERM_NODE_ID / NODETERM_HOOK_DIR) and
-// appends the hook's JSON payload, tagged with the event, to a per-node log file. The main
-// process watches that directory and forwards each event to the renderer over `claude:status`.
+// 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'
-let hookDir = ''
-let settingsPath = ''
+const CLAUDE_EVENTS = ['SessionStart', 'UserPromptSubmit', 'Stop', 'Notification', 'SessionEnd']
-export function claudeHookPaths(): { hookDir: string; settingsPath: string } {
- if (!hookDir) {
- const base = app.getPath('userData')
- hookDir = path.join(base, 'claude-signals')
- settingsPath = path.join(base, 'claude-hooks.json')
- }
- return { hookDir, settingsPath }
-}
+// 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 = ''
-// A POSIX-shell hook command: wrap the stdin payload with the event label and append a line.
-function hookCommand(event: string): string {
- return (
- `mkdir -p "$NODETERM_HOOK_DIR" 2>/dev/null; ` +
- `{ printf '{"event":"${event}","p":'; cat; printf '}\\n'; } ` +
- `>> "$NODETERM_HOOK_DIR/$NODETERM_NODE_ID.log" 2>/dev/null || true`
- )
+export function claudeHookDir(): string {
+ if (!hookDir) hookDir = path.join(app.getPath('userData'), 'claude-signals')
+ return hookDir
}
-function hookEntry(event: string) {
- return [{ hooks: [{ type: 'command', command: hookCommand(event), async: true }] }]
+interface HookDef {
+ hooks?: { type?: string; command?: string }[]
}
-function writeSettings(): void {
- const config = {
- hooks: {
- SessionStart: hookEntry('SessionStart'),
- UserPromptSubmit: hookEntry('UserPromptSubmit'),
- Stop: hookEntry('Stop'),
- Notification: hookEntry('Notification'),
- SessionEnd: hookEntry('SessionEnd')
+/** 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)
}
}
- fs.writeFileSync(settingsPath, JSON.stringify(config, null, 2))
}
-/** Write the hooks settings file, clear stale signals, and watch for new hook events. */
+/** Install hooks, clear stale signals, and watch for new hook events. */
export function initClaudeHooks(win: BrowserWindow): void {
- claudeHookPaths()
+ installHooks()
+ const dir = claudeHookDir()
try {
- fs.mkdirSync(hookDir, { recursive: true })
- // Start fresh each launch so we don't replay a previous run's events.
- for (const f of fs.readdirSync(hookDir)) {
- if (f.endsWith('.log')) fs.rmSync(path.join(hookDir, f), { force: true })
+ fs.mkdirSync(dir, { recursive: true })
+ for (const f of fs.readdirSync(dir)) {
+ if (f.endsWith('.log')) fs.rmSync(path.join(dir, f), { force: true })
}
- writeSettings()
} catch (e) {
- console.error('[claude-hooks] setup failed', e)
+ console.error('[claude-hooks] signal dir setup failed', e)
return
}
const offsets = new Map<string, number>()
- let timer: ReturnType<typeof setTimeout> | null = null
const scan = () => {
let files: string[]
try {
- files = fs.readdirSync(hookDir)
+ files = fs.readdirSync(dir)
} catch {
return
}
for (const f of files) {
if (!f.endsWith('.log')) continue
- const full = path.join(hookDir, f)
+ const full = path.join(dir, f)
let size: number
try {
size = fs.statSync(full).size
@@ -103,12 +121,17 @@ export function initClaudeHooks(win: BrowserWindow): void {
const t = line.trim()
if (!t) continue
try {
- const obj = JSON.parse(t) as { event?: string; p?: { session_id?: string } }
- if (obj.event && !win.isDestroyed()) {
+ const p = JSON.parse(t) as {
+ hook_event_name?: string
+ session_id?: string
+ notification_type?: string
+ }
+ if (p.hook_event_name && !win.isDestroyed()) {
win.webContents.send(IPC.claudeStatus, {
nodeId,
- event: obj.event,
- sessionId: obj.p?.session_id
+ event: p.hook_event_name,
+ sessionId: p.session_id,
+ notificationType: p.notification_type
})
}
} catch {
@@ -118,15 +141,15 @@ export function initClaudeHooks(win: BrowserWindow): void {
}
}
+ let timer: ReturnType<typeof setTimeout> | null = null
try {
- fs.watch(hookDir, () => {
+ fs.watch(dir, () => {
if (timer) clearTimeout(timer)
timer = setTimeout(scan, 40)
})
} catch (e) {
console.error('[claude-hooks] watch failed', e)
}
- // Poll as well: fs.watch on a directory can miss in-file appends on macOS, which would
- // make us see SessionStart but miss the later Stop. Polling a few tiny files is cheap.
+ // Poll too: fs.watch can miss in-file appends on macOS.
setInterval(scan, 800)
}
diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.ts
index 9b80ec881..821515df4 100644
--- a/src/main/pty-manager.ts
+++ b/src/main/pty-manager.ts
@@ -6,7 +6,7 @@ import { app, ipcMain, webContents } from 'electron'
import * as pty from 'node-pty'
import { IPC } from '../shared/ipc'
import { DEFAULT_SETTINGS, type PtyCreateOptions, type Settings } from '../shared/types'
-import { claudeHookPaths } from './claude-hooks'
+import { claudeHookDir } from './claude-hooks'
// A dedicated tmux socket isolates our sessions from the user's own tmux server.
const TMUX_SOCKET = 'node-terminal'
@@ -113,11 +113,11 @@ export class PtyManager {
delete env.TMUX
delete env.TMUX_PANE
- // Claude Code hooks: each session carries its node id + the signal dir + our hooks
- // file, so `claude --settings "$NODETERM_CLAUDE_SETTINGS"` reports state back to us.
- const { hookDir, settingsPath } = claudeHookPaths()
+ // Claude Code hooks: each session carries its node id + the signal dir. Our managed
+ // hook (installed globally in ~/.claude/settings.json, but a no-op without these vars)
+ // then reports state back to us for any `claude` run in this session.
+ const hookDir = claudeHookDir()
env.NODETERM_HOOK_DIR = hookDir
- env.NODETERM_CLAUDE_SETTINGS = settingsPath
if (options.persistKey) env.NODETERM_NODE_ID = options.persistKey
const settings = this.getSettings()
@@ -141,8 +141,6 @@ export class PtyManager {
`NODETERM_NODE_ID=${options.persistKey}`,
'-e',
`NODETERM_HOOK_DIR=${hookDir}`,
- '-e',
- `NODETERM_CLAUDE_SETTINGS=${settingsPath}`,
'-c',
cwd,
'-s',
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 3b678da55..5a226d768 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -795,39 +795,49 @@ export function Canvas() {
useEffect(() => window.nodeTerminal.onFocusNode(focusNodeById), [focusNodeById])
// Claude Code lifecycle, reported by Claude's own hooks (see main/claude-hooks.ts):
- // UserPromptSubmit → working, Stop → finished, Notification → needs input. On a finish
- // while the window is in the background: mark unread + (with consent) notify.
+ // UserPromptSubmit → working, Stop → done, Notification → waiting/blocked. 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>>({})
useEffect(() => {
return window.nodeTerminal.onClaudeStatus((e) => {
const cs = useClaudeStatus.getState()
if (e.sessionId) cs.setSessionId(e.nodeId, e.sessionId)
- const finish = (attention: boolean) => {
- cs.setBusy(e.nodeId, false)
- if (!document.hasFocus()) {
- cs.markUnread(e.nodeId)
- const s = useSettings.getState().settings
- if (s.notifyOnClaudeDone && s.notifyConsentAsked) {
- const node = nodesRef.current.find((n) => n.id === e.nodeId)
- void window.nodeTerminal.notify({
- title: attention ? 'Claude Code needs you' : 'Claude Code finished',
- body: (node?.data.title as string) || 'Claude Code',
- nodeId: e.nodeId
- })
- }
- }
+ const alert = (title: string) => {
+ if (document.hasFocus()) return
+ cs.markUnread(e.nodeId)
+ const s = useSettings.getState().settings
+ if (!(s.notifyOnClaudeDone && s.notifyConsentAsked)) return
+ const now = Date.now()
+ if (now - (notifyCooldownRef.current[e.nodeId] ?? 0) < 5000) return // dedup/cooldown
+ notifyCooldownRef.current[e.nodeId] = now
+ const node = nodesRef.current.find((n) => n.id === e.nodeId)
+ void window.nodeTerminal.notify({
+ title,
+ body: (node?.data.title as string) || 'Claude Code',
+ nodeId: e.nodeId
+ })
}
switch (e.event) {
case 'UserPromptSubmit':
- cs.setBusy(e.nodeId, true)
+ cs.setState(e.nodeId, 'working')
break
case 'Stop':
- finish(false)
+ cs.setState(e.nodeId, 'done')
+ alert('Claude Code finished')
break
case 'Notification':
- finish(true)
+ if (e.notificationType === 'permission_prompt') {
+ cs.setState(e.nodeId, 'blocked')
+ alert('Claude Code needs permission')
+ } else {
+ cs.setState(e.nodeId, 'waiting')
+ alert('Claude Code needs you')
+ }
break
+ case 'SessionStart':
case 'SessionEnd':
- cs.setBusy(e.nodeId, false)
+ cs.setState(e.nodeId, undefined)
break
}
})
@@ -1067,7 +1077,8 @@ export function Canvas() {
nodeColor={(n) => (n.data as { color?: string })?.color ?? '#0a84ff'}
nodeStrokeColor={(n) => {
const st = useClaudeStatus.getState().byId[n.id]
- if (st?.busy) return '#30d158'
+ if (st?.state === 'working') return '#30d158'
+ if (st?.state === 'waiting' || st?.state === 'blocked') return '#ff9f0a'
if (st?.unread) return '#0a84ff'
return (n.data as { color?: string })?.color ?? '#0a84ff'
}}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 46466350e..839bd3c49 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -124,7 +124,7 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {
observer.disconnect()
if (dwellRef.current) clearTimeout(dwellRef.current)
cleanups.forEach((fn) => fn())
- if (isClaude) useClaudeStatus.getState().remove(id)
+ useClaudeStatus.getState().remove(id)
if (sessionId) transport.kill(sessionId)
term.dispose()
termRef.current = null
@@ -170,7 +170,7 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {
dwellRef.current = setTimeout(() => {
setArmed(false)
termRef.current?.focus()
- if (isClaude) useClaudeStatus.getState().clearUnread(id)
+ useClaudeStatus.getState().clearUnread(id)
}, settings.panHoverDelay)
}
const onBodyLeave = () => {
@@ -191,10 +191,10 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {
if (r.ok) updateNodeData(id, { title: r.message })
}
- // Selecting a Claude node clears its unread badge.
+ // Selecting a node clears its unread badge.
useEffect(() => {
- if (isClaude && selected) useClaudeStatus.getState().clearUnread(id)
- }, [isClaude, selected, id])
+ if (selected) useClaudeStatus.getState().clearUnread(id)
+ }, [selected, id])
// Cmd/Ctrl+M toggles markdown view of this terminal's output (only when hovered).
useEffect(() => {
@@ -264,23 +264,35 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {
{data.title || 'Untitled'}
</span>
)}
- {isClaude && status?.session && status.session !== data.title && (
+ {status?.session && status.session !== data.title && (
<span className="term-node__session" title={status.session}>
{status.session}
</span>
)}
- {isClaude && status?.busy && (
+ {status?.state === 'working' && (
<span className="term-node__status term-node__status--busy" title="Claude is working">
<span className="term-node__status-dot" />
RUNNING
</span>
)}
- {isClaude && !status?.busy && status?.unread && (
+ {(status?.state === 'waiting' || status?.state === 'blocked') && (
<span
- className="term-node__status term-node__status--unread"
- title="Finished — click to mark read"
- />
+ className="term-node__status term-node__status--attention"
+ title="Claude needs your input"
+ >
+ <span className="term-node__status-dot" />
+ NEEDS YOU
+ </span>
)}
+ {status?.unread &&
+ status?.state !== 'working' &&
+ status?.state !== 'waiting' &&
+ status?.state !== 'blocked' && (
+ <span
+ className="term-node__status term-node__status--unread"
+ title="Finished — click to mark read"
+ />
+ )}
{!editingTitle && <span className="term-node__spacer" />}
<Tooltip label="Name with AI (from terminal output)">
<button className="term-node__ai nodrag" disabled={naming} onClick={nameWithAi}>
diff --git a/src/renderer/state/claudeStatus.ts b/src/renderer/state/claudeStatus.ts
index 658f44263..4780724d0 100644
--- a/src/renderer/state/claudeStatus.ts
+++ b/src/renderer/state/claudeStatus.ts
@@ -1,26 +1,26 @@
import { create } from 'zustand'
/**
- * Transient per-node status for Claude Code terminals — busy/working, unread, and the
- * Claude session name. Deliberately NOT persisted (kept out of workspace.json); it resets
- * on reload / project switch, which is the desired "clean layout file" behavior.
+ * Transient per-node status for Claude Code sessions, driven by Claude'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 {
- /** Claude is actively processing a turn. */
- busy: boolean
- /** A turn finished while the user wasn't looking; cleared on focus/select. */
+ /** Live activity; undefined = idle/unknown. */
+ state?: ClaudeState
+ /** A turn finished / needs attention while the user wasn't looking. */
unread: boolean
/** Claude's own session name/title (from the terminal title), shown beside the title. */
session?: string
- /** Claude session id (UUID from hooks) — used to resume/branch the conversation. */
+ /** Claude session id (from hooks) — used to resume/branch the conversation. */
sessionId?: string
- /** Timestamp of the last busy→idle transition. */
- finishedAt?: number
}
interface ClaudeStatusState {
byId: Record<string, ClaudeNodeStatus>
- setBusy(id: string, busy: boolean): void
+ setState(id: string, state: ClaudeState | undefined): void
setSession(id: string, session: string): void
setSessionId(id: string, sessionId: string): void
markUnread(id: string): void
@@ -28,56 +28,91 @@ interface ClaudeStatusState {
remove(id: string): void
}
-const EMPTY: ClaudeNodeStatus = { busy: false, unread: false }
+const EMPTY: ClaudeNodeStatus = { unread: false }
+const KEY = 'nodeterm.claudeStatus'
+
+function load(): Record<string, ClaudeNodeStatus> {
+ try {
+ const raw = localStorage.getItem(KEY)
+ if (!raw) return {}
+ const data = JSON.parse(raw) as Record<string, Partial<ClaudeNodeStatus>>
+ const out: Record<string, ClaudeNodeStatus> = {}
+ for (const [id, v] of Object.entries(data)) {
+ out[id] = { unread: !!v.unread, session: v.session, sessionId: v.sessionId }
+ }
+ return out
+ } catch {
+ return {}
+ }
+}
+
+// Persist only the durable fields (not the live `state`).
+function save(byId: Record<string, ClaudeNodeStatus>): void {
+ try {
+ const out: Record<string, Partial<ClaudeNodeStatus>> = {}
+ 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 }
+ }
+ }
+ localStorage.setItem(KEY, JSON.stringify(out))
+ } catch {
+ // ignore quota / serialization errors
+ }
+}
export const useClaudeStatus = create<ClaudeStatusState>((set) => ({
- byId: {},
+ byId: load(),
- setBusy: (id, busy) =>
+ setState: (id, state) =>
set((s) => {
const prev = s.byId[id] ?? EMPTY
- if (prev.busy === busy) return s
- return {
- byId: {
- ...s.byId,
- [id]: { ...prev, busy, finishedAt: busy ? prev.finishedAt : Date.now() }
- }
- }
+ if (prev.state === state) return s
+ return { byId: { ...s.byId, [id]: { ...prev, state } } }
}),
setSession: (id, session) =>
set((s) => {
const prev = s.byId[id] ?? EMPTY
if (prev.session === session) return s
- return { byId: { ...s.byId, [id]: { ...prev, session } } }
+ const byId = { ...s.byId, [id]: { ...prev, session } }
+ save(byId)
+ return { byId }
}),
setSessionId: (id, sessionId) =>
set((s) => {
const prev = s.byId[id] ?? EMPTY
if (prev.sessionId === sessionId) return s
- return { byId: { ...s.byId, [id]: { ...prev, sessionId } } }
+ const byId = { ...s.byId, [id]: { ...prev, sessionId } }
+ save(byId)
+ return { byId }
}),
markUnread: (id) =>
set((s) => {
const prev = s.byId[id] ?? EMPTY
if (prev.unread) return s
- return { byId: { ...s.byId, [id]: { ...prev, unread: true } } }
+ const byId = { ...s.byId, [id]: { ...prev, unread: true } }
+ save(byId)
+ return { byId }
}),
clearUnread: (id) =>
set((s) => {
const prev = s.byId[id]
if (!prev?.unread) return s
- return { byId: { ...s.byId, [id]: { ...prev, unread: false } } }
+ const byId = { ...s.byId, [id]: { ...prev, unread: false } }
+ save(byId)
+ return { byId }
}),
remove: (id) =>
set((s) => {
if (!(id in s.byId)) return s
- const next = { ...s.byId }
- delete next[id]
- return { byId: next }
+ const byId = { ...s.byId }
+ delete byId[id]
+ save(byId)
+ return { byId }
})
}))
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index 19f873dfd..6a121a485 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -84,11 +84,11 @@ export function createTerminalNode(
}
/**
- * Command that launches Claude Code with our hooks settings (for busy/idle/attention
- * detection). `$NODETERM_CLAUDE_SETTINGS` is exported into every terminal session by the
- * PTY manager. Append `-r <id>` to resume a specific session (used by Branch).
+ * Command that launches Claude Code. Detection works via hooks installed globally in
+ * ~/.claude/settings.json (gated by NODETERM_* env that the PTY manager sets), so a plain
+ * `claude` is enough. Append `-r <id>` to resume a specific session (used by Branch).
*/
-export const CLAUDE_LAUNCH = 'claude --settings "$NODETERM_CLAUDE_SETTINGS"'
+export const CLAUDE_LAUNCH = 'claude'
/** Creates a terminal that launches Claude Code (`claude`) on open. */
export function createClaudeNode(
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 0be82bbf1..062734730 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -500,6 +500,14 @@ body,
animation: nt-pulse 1.1s ease-in-out infinite;
}
+.term-node__status--attention {
+ color: #ff9f0a;
+}
+
+.term-node__status--attention .term-node__status-dot {
+ animation: nt-pulse 1.1s ease-in-out infinite;
+}
+
.term-node__status--unread {
margin-left: 8px;
width: 8px;
diff --git a/src/shared/types.ts b/src/shared/types.ts
index d35813436..2855a1662 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -311,6 +311,8 @@ export interface ClaudeStatusEvent {
/** SessionStart | UserPromptSubmit | Stop | Notification | SessionEnd */
event: string
sessionId?: string
+ /** For Notification events: e.g. 'permission_prompt' | 'idle_prompt'. */
+ notificationType?: string
}
export interface NodeTerminalApi {