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.

fix(claude): detect state via Claude hooks instead of output parsing

enes8d300e1197d1
diff --git a/src/main/claude-hooks.ts b/src/main/claude-hooks.ts
new file mode 100644
index 000000000..3bfce3cad
--- /dev/null
+++ b/src/main/claude-hooks.ts
@@ -0,0 +1,129 @@
+// Robust Claude Code state detection via Claude's own hooks (not terminal-output parsing).
+//
+// 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`.
+import fs from 'fs'
+import path from 'path'
+import { app, type BrowserWindow } from 'electron'
+import { IPC } from '../shared/ipc'
+
+let hookDir = ''
+let settingsPath = ''
+
+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 }
+}
+
+// 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`
+ )
+}
+
+function hookEntry(event: string) {
+ return [{ hooks: [{ type: 'command', command: hookCommand(event), async: true }] }]
+}
+
+function writeSettings(): void {
+ const config = {
+ hooks: {
+ SessionStart: hookEntry('SessionStart'),
+ UserPromptSubmit: hookEntry('UserPromptSubmit'),
+ Stop: hookEntry('Stop'),
+ Notification: hookEntry('Notification'),
+ SessionEnd: hookEntry('SessionEnd')
+ }
+ }
+ fs.writeFileSync(settingsPath, JSON.stringify(config, null, 2))
+}
+
+/** Write the hooks settings file, clear stale signals, and watch for new hook events. */
+export function initClaudeHooks(win: BrowserWindow): void {
+ claudeHookPaths()
+ 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 })
+ }
+ writeSettings()
+ } catch (e) {
+ console.error('[claude-hooks] 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)
+ } catch {
+ return
+ }
+ for (const f of files) {
+ if (!f.endsWith('.log')) continue
+ const full = path.join(hookDir, 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 obj = JSON.parse(t) as { event?: string; p?: { session_id?: string } }
+ if (obj.event && !win.isDestroyed()) {
+ win.webContents.send(IPC.claudeStatus, {
+ nodeId,
+ event: obj.event,
+ sessionId: obj.p?.session_id
+ })
+ }
+ } catch {
+ // partial/garbled line; ignore
+ }
+ }
+ }
+ }
+
+ try {
+ fs.watch(hookDir, () => {
+ if (timer) clearTimeout(timer)
+ timer = setTimeout(scan, 40)
+ })
+ } catch (e) {
+ console.error('[claude-hooks] watch failed', e)
+ }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 309022daa..f73e98a83 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -11,6 +11,7 @@ import { GitService } from './git-service'
import { generateCommitMessage, generateTerminalName } from './commit-message'
import { initUpdater } from './updater'
import { fetchAnnouncements } from './announcements'
+import { initClaudeHooks } from './claude-hooks'
const settingsStore = new SettingsStore()
const ptyManager = new PtyManager()
@@ -196,6 +197,7 @@ app.whenReady().then(() => {
const win = createWindow()
mainWin = win
initUpdater(win)
+ initClaudeHooks(win)
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.ts
index f0eb0240b..9b80ec881 100644
--- a/src/main/pty-manager.ts
+++ b/src/main/pty-manager.ts
@@ -6,6 +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'
// A dedicated tmux socket isolates our sessions from the user's own tmux server.
const TMUX_SOCKET = 'node-terminal'
@@ -112,12 +113,21 @@ 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()
+ env.NODETERM_HOOK_DIR = hookDir
+ env.NODETERM_CLAUDE_SETTINGS = settingsPath
+ if (options.persistKey) env.NODETERM_NODE_ID = options.persistKey
+
const settings = this.getSettings()
let file: string
let args: string[]
if (this.tmuxPath && settings.tmuxEnabled && options.persistKey) {
// attach-or-create the persistent session for this node; -D detaches any stale client.
+ // `-e` sets the session environment explicitly (the tmux server is shared, so relying
+ // on the client's inherited env would leak the first session's values into later ones).
file = this.tmuxPath
args = [
'-L',
@@ -127,6 +137,12 @@ export class PtyManager {
'new-session',
'-A',
'-D',
+ '-e',
+ `NODETERM_NODE_ID=${options.persistKey}`,
+ '-e',
+ `NODETERM_HOOK_DIR=${hookDir}`,
+ '-e',
+ `NODETERM_CLAUDE_SETTINGS=${settingsPath}`,
'-c',
cwd,
'-s',
diff --git a/src/preload/index.ts b/src/preload/index.ts
index b27a7fb35..5b12385cd 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -108,6 +108,11 @@ const api: NodeTerminalApi = {
const handler = (_e: unknown, nodeId: string) => listener(nodeId)
ipcRenderer.on(IPC.appFocusNode, handler)
return () => ipcRenderer.removeListener(IPC.appFocusNode, handler)
+ },
+ onClaudeStatus: (listener) => {
+ const handler = (_e: unknown, payload: Parameters<typeof listener>[0]) => listener(payload)
+ ipcRenderer.on(IPC.claudeStatus, handler)
+ return () => ipcRenderer.removeListener(IPC.claudeStatus, handler)
}
}
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 1a433f856..0508dcbc8 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -55,6 +55,7 @@ import { useClaudeStatus } from '../state/claudeStatus'
import { branchClaudeSession } from '../lib/claudeBranch'
import { useSettings } from '../state/settings'
import {
+ CLAUDE_LAUNCH,
COLLAPSED_HEIGHT,
createClaudeNode,
createDiffNode,
@@ -480,19 +481,28 @@ export function Canvas() {
// Run Claude's /branch in this node, then open a new node that resumes the original
// conversation (claude -r <ORIGINAL_ID>). The source node stays on the new branch.
+ // We already know the current session id from the hooks; only fall back to parsing the
+ // terminal output if it's unknown.
const branchClaude = useCallback(
async (nodeId: string) => {
const source = nodesRef.current.find((n) => n.id === nodeId) as CanvasNode | undefined
if (!source) return
- const res = await branchClaudeSession(nodeId)
- if (!res.ok || !res.originalId) {
- setConfirm({ message: res.error ?? 'Branch failed.', onConfirm: () => setConfirm(null) })
- return
+ const known = useClaudeStatus.getState().byId[nodeId]?.sessionId
+ let originalId = known
+ if (known) {
+ await window.nodeTerminal.pty.sendText(nodeId, '/branch')
+ } else {
+ const res = await branchClaudeSession(nodeId)
+ if (!res.ok || !res.originalId) {
+ setConfirm({ message: res.error ?? 'Branch failed.', onConfirm: () => setConfirm(null) })
+ return
+ }
+ originalId = res.originalId
}
const copy = duplicateNode(source)
copy.data = {
...copy.data,
- initialCommand: `claude -r ${res.originalId}`,
+ initialCommand: `${CLAUDE_LAUNCH} -r ${originalId}`,
title: `${source.data.title} (original)`
}
copy.position = {
@@ -776,6 +786,45 @@ 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.
+ 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
+ })
+ }
+ }
+ }
+ switch (e.event) {
+ case 'UserPromptSubmit':
+ cs.setBusy(e.nodeId, true)
+ break
+ case 'Stop':
+ finish(false)
+ break
+ case 'Notification':
+ finish(true)
+ break
+ case 'SessionEnd':
+ cs.setBusy(e.nodeId, false)
+ break
+ }
+ })
+ }, [])
+
// 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.tsx
index 7d0197dec..f0d678be1 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -9,7 +9,6 @@ import { NodeTags } from '../components/NodeTags'
import { Tooltip } from '../components/Tooltip'
import { useSettings } from '../state/settings'
import { useClaudeStatus } from '../state/claudeStatus'
-import { createClaudeBusyDetector } from '../terminal/claudeBusy'
import { COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'
/**
@@ -36,9 +35,6 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {
const tags = (data.tags as string[]) ?? []
const isClaude = tags.includes('claude')
const status = useClaudeStatus((s) => s.byId[id])
- // Latest data for use inside the once-only lifecycle effect (avoids stale closures).
- const dataRef = useRef(data)
- dataRef.current = data
// Terminal lifecycle — set up exactly once.
useEffect(() => {
@@ -65,35 +61,14 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {
let disposed = false
const cleanups: Array<() => void> = []
- // Claude Code nodes: watch the output for working/idle transitions.
- const onBusyChange = (busy: boolean) => {
- const cs = useClaudeStatus.getState()
- cs.setBusy(id, busy)
- // On a turn finishing while the user isn't looking: mark unread + (maybe) notify.
- // Notifications only fire once consent has been given (Canvas shows a one-time prompt
- // the first time a background completion happens).
- if (!busy && !document.hasFocus()) {
- cs.markUnread(id)
- const s = useSettings.getState().settings
- if (s.notifyOnClaudeDone && s.notifyConsentAsked) {
- void window.nodeTerminal.notify({
- title: 'Claude Code finished',
- body: dataRef.current.title || 'Claude Code',
- nodeId: id
- })
- }
- }
- }
- const detector = isClaude
- ? createClaudeBusyDetector((busy) => onBusyChange(busy))
- : null
- if (detector) cleanups.push(term.onBell(() => detector.bell()).dispose)
+ // 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.
if (isClaude) {
- // Claude sets the terminal title to the conversation topic; surface it as a chip.
- // Ignore path/prompt-like titles (e.g. "user@host: ~/dir") which aren't session names.
cleanups.push(
term.onTitleChange((t) => {
const title = t.trim()
+ // Ignore path/prompt-like titles (e.g. "user@host: ~/dir") which aren't session names.
if (title && !/[/:~]/.test(title)) useClaudeStatus.getState().setSession(id, title)
}).dispose
)
@@ -107,12 +82,7 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {
return
}
sessionId = sid
- cleanups.push(
- transport.onData(sid, (chunk) => {
- term.write(chunk)
- detector?.feed(chunk)
- })
- )
+ cleanups.push(transport.onData(sid, (chunk) => term.write(chunk)))
cleanups.push(
transport.onExit(sid, (code) => {
term.write(`\r\n\x1b[90m[process exited with code ${code}]\x1b[0m\r\n`)
@@ -142,7 +112,6 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {
observer.disconnect()
if (dwellRef.current) clearTimeout(dwellRef.current)
cleanups.forEach((fn) => fn())
- detector?.dispose()
if (isClaude) useClaudeStatus.getState().remove(id)
if (sessionId) transport.kill(sessionId)
term.dispose()
diff --git a/src/renderer/state/claudeStatus.ts b/src/renderer/state/claudeStatus.ts
index 751d34926..658f44263 100644
--- a/src/renderer/state/claudeStatus.ts
+++ b/src/renderer/state/claudeStatus.ts
@@ -10,8 +10,10 @@ export interface ClaudeNodeStatus {
busy: boolean
/** A turn finished while the user wasn't looking; cleared on focus/select. */
unread: boolean
- /** Claude's own session name/title, shown alongside the terminal title. */
+ /** 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. */
+ sessionId?: string
/** Timestamp of the last busy→idle transition. */
finishedAt?: number
}
@@ -20,6 +22,7 @@ interface ClaudeStatusState {
byId: Record<string, ClaudeNodeStatus>
setBusy(id: string, busy: boolean): void
setSession(id: string, session: string): void
+ setSessionId(id: string, sessionId: string): void
markUnread(id: string): void
clearUnread(id: string): void
remove(id: string): void
@@ -49,6 +52,13 @@ export const useClaudeStatus = create<ClaudeStatusState>((set) => ({
return { byId: { ...s.byId, [id]: { ...prev, session } } }
}),
+ setSessionId: (id, sessionId) =>
+ set((s) => {
+ const prev = s.byId[id] ?? EMPTY
+ if (prev.sessionId === sessionId) return s
+ return { byId: { ...s.byId, [id]: { ...prev, sessionId } } }
+ }),
+
markUnread: (id) =>
set((s) => {
const prev = s.byId[id] ?? EMPTY
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index b71c6290a..19f873dfd 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -83,6 +83,13 @@ 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).
+ */
+export const CLAUDE_LAUNCH = 'claude --settings "$NODETERM_CLAUDE_SETTINGS"'
+
/** Creates a terminal that launches Claude Code (`claude`) on open. */
export function createClaudeNode(
index: number,
@@ -102,7 +109,7 @@ export function createClaudeNode(
group: null,
tags: ['claude'],
cwd,
- initialCommand: 'claude'
+ initialCommand: CLAUDE_LAUNCH
}
}
}
diff --git a/src/renderer/terminal/claudeBusy.ts b/src/renderer/terminal/claudeBusy.ts
deleted file mode 100644
index 767c5373d..000000000
--- a/src/renderer/terminal/claudeBusy.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-// Detects whether a Claude Code session is actively working, from its terminal output.
-//
-// Signals (layered, so it works regardless of which ones a given Claude build emits):
-// - PRIMARY: the working line Claude redraws each frame while a turn runs — it contains
-// "esc to interrupt" plus a spinner glyph. While that keeps appearing we stay "busy".
-// - COMPLETION: when the working line stops appearing for IDLE_MS, we flip to idle. A
-// terminal bell (if Claude rings one on turn end) shortens that wait.
-// We test the raw chunk: "esc to interrupt" is contiguous ASCII (ANSI color codes wrap the
-// whole line, not the phrase), so no escape-sequence stripping is needed. If Claude changes
-// its UI wording, update WORKING below — it's the single source of truth.
-
-const WORKING =
- /esc to interrupt|[✶✻✽✺✳✢⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]\s|\b(?:Working|Thinking|Forging|Cogitating|Pondering|Brewing|Herding|Simmering|Spelunking|Reticulating)…?/i
-
-const IDLE_MS = 1500
-const BELL_IDLE_MS = 400
-
-export interface ClaudeBusyDetector {
- /** Feed a raw output chunk. */
- feed(chunk: string): void
- /** Call when the terminal bell fires. */
- bell(): void
- dispose(): void
-}
-
-export function createClaudeBusyDetector(
- onChange: (busy: boolean) => void
-): ClaudeBusyDetector {
- let busy = false
- let idleTimer: ReturnType<typeof setTimeout> | null = null
-
- const setBusy = (b: boolean) => {
- if (b === busy) return
- busy = b
- onChange(b)
- }
-
- const armIdle = (ms = IDLE_MS) => {
- if (idleTimer) clearTimeout(idleTimer)
- idleTimer = setTimeout(() => setBusy(false), ms)
- }
-
- return {
- feed(chunk) {
- if (WORKING.test(chunk)) {
- setBusy(true)
- armIdle()
- }
- },
- bell() {
- // A bell usually marks the end of a turn; flip to idle soon (unless work resumes).
- if (busy) armIdle(BELL_IDLE_MS)
- },
- dispose() {
- if (idleTimer) clearTimeout(idleTimer)
- idleTimer = null
- }
- }
-}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index c6add9f97..c58c23ef2 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -14,6 +14,7 @@ export const IPC = {
appCloseWindow: 'app:close-window',
appNotify: 'app:notify',
appFocusNode: 'app:focus-node',
+ claudeStatus: 'claude:status',
appUpdateAvailable: 'app:update-available',
appUpdateDownloaded: 'app:update-downloaded',
appRestartToUpdate: 'app:restart-to-update',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 371ac331e..8c0b3bf58 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -303,6 +303,14 @@ export interface NotifyPayload {
nodeId: string
}
+/** A Claude Code lifecycle hook event, forwarded from the main process. */
+export interface ClaudeStatusEvent {
+ nodeId: string
+ /** SessionStart | UserPromptSubmit | Stop | Notification | SessionEnd */
+ event: string
+ sessionId?: string
+}
+
export interface NodeTerminalApi {
pty: PtyApi
workspace: WorkspaceApi
@@ -324,4 +332,6 @@ export interface NodeTerminalApi {
notify(payload: NotifyPayload): Promise<boolean>
/** Fires when a notification is clicked, asking the renderer to focus a node. Returns unsubscribe. */
onFocusNode(listener: (nodeId: string) => void): () => void
+ /** Fires on each Claude Code hook event (start/working/idle/attention). Returns unsubscribe. */
+ onClaudeStatus(listener: (e: ClaudeStatusEvent) => void): () => void
}