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
fix(agent-hooks): one machine, one hook script — a second instance can't silently kill them
enesecaac6ab8ceb
diff --git a/src/core/agents/hooks/claude.ts b/src/core/agents/hooks/claude.tsindex 60e9ee2bf..8af35a886 100644--- a/src/core/agents/hooks/claude.ts+++ b/src/core/agents/hooks/claude.ts@@ -5,21 +5,8 @@ import path from 'path'import { installHooksInto, removeHooksFrom } from './install-helper'import { ensureFullscreenTuiInFile } from './claude-tui'import { claudeCliCaps } from '../../claude-cli'+import { CLAUDE_HOOK_EVENTS } from '@shared/agents/hook-events'-const CLAUDE_EVENTS = [- 'SessionStart',- 'UserPromptSubmit',- 'Stop',- // Fires INSTEAD of Stop when the turn ends on an API/model error — without it the- // status badge sticks on "working" after any errored turn.- 'StopFailure',- 'Notification',- // Dedicated permission-prompt signal (→ blocked), more direct than Notification.- 'PermissionRequest',- 'SessionEnd',- 'PreToolUse',- 'PostToolUse'-] as constconst SCRIPT_FILE_NAME = 'claude.sh'@@ -32,7 +19,7 @@ export function installClaudeHooks(): void {agentId: 'claude',scriptFileName: SCRIPT_FILE_NAME,configPath: configPath(),- events: CLAUDE_EVENTS+ events: CLAUDE_HOOK_EVENTS})}@@ -42,7 +29,7 @@ export function installClaudeHooksInto(configDir: string): void {agentId: 'claude',scriptFileName: SCRIPT_FILE_NAME,configPath: path.join(configDir, 'settings.json'),- events: CLAUDE_EVENTS+ events: CLAUDE_HOOK_EVENTS})}@@ -66,7 +53,7 @@ export async function ensureClaudeFullscreenTuiInto(configDir: string): Promise<export function removeClaudeHooks(): void {removeHooksFrom({configPath: configPath(),- events: CLAUDE_EVENTS,+ events: CLAUDE_HOOK_EVENTS,scriptFileName: SCRIPT_FILE_NAME})}diff --git a/src/core/agents/hooks/codex.ts b/src/core/agents/hooks/codex.tsindex 02c05273a..58ba26659 100644--- a/src/core/agents/hooks/codex.ts+++ b/src/core/agents/hooks/codex.ts@@ -26,7 +26,6 @@ import {unlinkSync} from 'fs'import { randomUUID } from 'crypto'-import { platform } from '../../platform'import { buildManagedScript } from './managed-script'import {computeTrustedHash,@@ -83,8 +82,9 @@ function configTomlPath(): string {return path.join(codexHome(), 'config.toml')}+/** Stable, machine-wide — the same rule as install-helper's `scriptPathFor` (see its note). */function scriptPath(): string {- return path.join(platform().userDataDir, 'agent-hooks', SCRIPT_FILE_NAME)+ return path.join(homedir(), '.nodeterm', 'agent-hooks', SCRIPT_FILE_NAME)}// Why: match managed entries by the `agent-hooks/codex.sh` path segment (notdiff --git a/src/core/agents/hooks/gemini.ts b/src/core/agents/hooks/gemini.tsindex fff06d336..3fc416e3b 100644--- a/src/core/agents/hooks/gemini.ts+++ b/src/core/agents/hooks/gemini.ts@@ -1,10 +1,10 @@// Gemini hook service. Installs the managed script into ~/.gemini/settings.json under// each Gemini hook event. Thin wrapper over the shared install helper.import { homedir } from 'os'+import { GEMINI_HOOK_EVENTS } from '@shared/agents/hook-events'import path from 'path'import { installHooksInto, removeHooksFrom } from './install-helper'-const GEMINI_EVENTS = ['BeforeAgent', 'AfterAgent', 'AfterTool', 'BeforeTool'] as constconst SCRIPT_FILE_NAME = 'gemini.sh'@@ -17,14 +17,14 @@ export function installGeminiHooks(): void {agentId: 'gemini',scriptFileName: SCRIPT_FILE_NAME,configPath: configPath(),- events: GEMINI_EVENTS+ events: GEMINI_HOOK_EVENTS})}export function removeGeminiHooks(): void {removeHooksFrom({configPath: configPath(),- events: GEMINI_EVENTS,+ events: GEMINI_HOOK_EVENTS,scriptFileName: SCRIPT_FILE_NAME})}diff --git a/src/core/agents/hooks/install-helper.test.ts b/src/core/agents/hooks/install-helper.test.tsindex 98085ca21..3f88a25f6 100644--- a/src/core/agents/hooks/install-helper.test.ts+++ b/src/core/agents/hooks/install-helper.test.ts@@ -64,3 +64,29 @@ describe('mergeManagedHook', () => {expect(out.hooks!.Stop).toEqual([{ hooks: [{ type: 'command', command: cmd }] }])})})++describe('mergeManagedHook — repair sweep', () => {+ const cmd = "if [ -r '/home/u/.nodeterm/agent-hooks/claude.sh' ]; then sh '/home/u/.nodeterm/agent-hooks/claude.sh'; else cat >/dev/null 2>&1 || :; fi"+ const stale = "if [ -r '/tmp/gone/agent-hooks/claude.sh' ]; then sh '/tmp/gone/agent-hooks/claude.sh'; else cat >/dev/null 2>&1 || :; fi"++ it("drops another instance's managed entry from events we don't subscribe to", () => {+ // The field state: a second nodeterm wrote its own (since-deleted) script path, and every+ // event outside OUR list kept pointing at it — silently doing nothing forever.+ const before = {+ hooks: {+ Stop: [{ hooks: [{ type: 'command', command: stale }] }],+ SubagentStop: [{ hooks: [{ type: 'command', command: stale }] }]+ }+ }+ const out = mergeManagedHook(before, cmd, ['Stop'])+ expect(out.hooks!.Stop).toEqual([{ hooks: [{ type: 'command', command: cmd }] }])+ expect(out.hooks!.SubagentStop).toBeUndefined()+ })++ it('never touches a foreign tool on an event we do not manage', () => {+ const foreign = { hooks: [{ type: 'command', command: '~/.someapp/agent-hooks/other.sh' }] }+ const before = { hooks: { SubagentStop: [foreign, { hooks: [{ type: 'command', command: stale }] }] } }+ const out = mergeManagedHook(before, cmd, ['Stop'])+ expect(out.hooks!.SubagentStop).toEqual([foreign])+ })+})diff --git a/src/core/agents/hooks/install-helper.ts b/src/core/agents/hooks/install-helper.tsindex 6b571fab2..3cb9515aa 100644--- a/src/core/agents/hooks/install-helper.ts+++ b/src/core/agents/hooks/install-helper.ts@@ -10,7 +10,7 @@// - fail open: a missing/unparseable settings.json defaults to {} (install) / returns// early (remove); a write error is caught + warned, never thrown.import path from 'path'-import { platform } from '../../platform'+import { homedir } from 'os'import { readFileSync, writeFileSync, mkdirSync, chmodSync } from 'fs'import { buildManagedScript } from './managed-script'@@ -20,8 +20,20 @@ type Settings = { hooks?: Record<string, HookDef[]>; [k: string]: unknown }/** Public alias for the hook settings shape, shared by local + remote merge callers. */export type HookSettings = Settings+/**+ * ONE script location per MACHINE — `~/.nodeterm/agent-hooks/<agent>.sh` — not one per instance.+ *+ * `settings.json` is shared by every agent session on the machine, but the path used to come from+ * each instance's own `userDataDir`. So a second nodeterm (a Server Edition install, a dev build,+ * an E2E run started with `--data-dir` under a temp path) rewrote the hook to ITS copy, and when+ * that data dir later vanished the guarded command silently swallowed every event: hooks "worked"+ * and did nothing, on every session on the box, until something reinstalled (field report).+ *+ * Every instance now writes identical bytes to the same stable path — which is also where the SSH+ * remote installer already puts it (`$HOME/.nodeterm/agent-hooks/`), so local and remote agree.+ */function scriptPathFor(scriptFileName: string): string {- return path.join(platform().userDataDir, 'agent-hooks', scriptFileName)+ return path.join(homedir(), '.nodeterm', 'agent-hooks', scriptFileName)}/**@@ -62,7 +74,17 @@ function isManaged(d: HookDef, marker: string): boolean {)}-/** Pure: merge the managed `command` into each event, dropping any prior managed entry. */+/**+ * Pure: make the config's managed hooks EXACTLY ours — our command on every event in `events`, and+ * no managed entry anywhere else.+ *+ * The second half is the repair. A managed entry is recognized by our own `agent-hooks/<agent>.sh`+ * tail, so it is ours (or another nodeterm instance's) by construction — never a foreign tool's.+ * Sweeping the events we DON'T subscribe to is what heals a settings.json two installers have+ * fought over: whoever wrote last used to leave the loser's command behind on every event its own+ * list lacked, and if the loser's script had since been deleted those events silently did nothing.+ * It also cleans up after ourselves when an event leaves the list between versions.+ */export function mergeManagedHook(config: HookSettings, command: string, events: readonly string[]): HookSettings {const marker = managedMarkerFor(command)const next: HookSettings = { ...config, hooks: { ...(config.hooks ?? {}) } }@@ -71,6 +93,14 @@ export function mergeManagedHook(config: HookSettings, command: string, events:existing.push({ hooks: [{ type: 'command', command }] })next.hooks![ev] = existing}+ const managedEvents = new Set(events)+ for (const ev of Object.keys(next.hooks!)) {+ if (managedEvents.has(ev)) continue+ const kept = next.hooks![ev].filter((d) => !isManaged(d, marker))+ if (kept.length === next.hooks![ev].length) continue+ if (kept.length === 0) delete next.hooks![ev]+ else next.hooks![ev] = kept+ }return next}diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.tsindex f3fc90a3e..bd31fdb35 100644--- a/src/main/remote-ssh/remote-hooks.ts+++ b/src/main/remote-ssh/remote-hooks.ts@@ -5,6 +5,7 @@// setup returns null (or, for codex, the agent simply runs without status). Takes an INJECTED// runner so the flow is unit-testable without real ssh/electron.import { childArgs, hookForwardArgs, hookForwardCancelArgs, remoteEndpointFileContents } from '../../core/remote-ssh/control-master'+import { CLAUDE_HOOK_EVENTS, GEMINI_HOOK_EVENTS } from '@shared/agents/hook-events'import { buildManagedScript } from '../../core/agents/hooks/managed-script'import { buildManagedHookCommand, mergeManagedHook, type HookSettings } from '../../core/agents/hooks/install-helper'import {@@ -46,17 +47,13 @@ export interface RemoteRunner {// Paths are relative to the remote $HOME and are made absolute once it is resolved at setup// (a literal `~` is NOT expanded inside double quotes or when passed as data, so the merged// hook command / endpoint file / `-R` bind path would otherwise carry an unexpanded tilde).-const AGENT_TARGETS: { agentId: string; config: string; events: string[] }[] = [- {- agentId: 'claude',- config: '.claude/settings.json',- events: ['Stop', 'Notification', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'SessionStart', 'SessionEnd', 'SubagentStop']- },- {- agentId: 'gemini',- config: '.gemini/settings.json',- events: ['Stop', 'Notification', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse']- }+// The SAME lists the local installer uses (shared/agents/hook-events.ts). They were duplicated+// here and had drifted: claude was missing StopFailure/PermissionRequest (an errored remote turn+// stuck on "working"), and gemini was subscribed to CLAUDE's event names, which it never fires —+// so remote gemini nodes reported nothing at all.+const AGENT_TARGETS: { agentId: string; config: string; events: readonly string[] }[] = [+ { agentId: 'claude', config: '.claude/settings.json', events: CLAUDE_HOOK_EVENTS },+ { agentId: 'gemini', config: '.gemini/settings.json', events: GEMINI_HOOK_EVENTS }]export class RemoteHooks {diff --git a/src/server/config.ts b/src/server/config.tsindex 3604da17d..2743864e5 100644--- a/src/server/config.ts+++ b/src/server/config.ts@@ -25,10 +25,11 @@ export type ServerConfig = {/*** Merge the managed agent hooks into the user's real agent config dirs (~/.claude,* ~/.codex, ~/.gemini) at boot. Defaults to true — the server needs them to receive- * agent status. Tests MUST pass false: the installed hook points at- * `<dataDir>/agent-hooks/<agent>.sh`, so a temp dataDir that gets removed after the run- * would leave a dangling hook behind in the developer's real settings.json, breaking- * every subsequent agent session on the machine.+ * agent status. Tests MUST pass false: installing rewrites the machine's REAL settings.json+ * (the script lives at the stable `~/.nodeterm/agent-hooks/<agent>.sh`, shared by every+ * instance), so a test run would silently take over the developer's own hooks — and, before+ * that path was stabilized, leave them pointing into a temp dataDir that gets removed after+ * the run, which is exactly how a machine ends up with hooks that quietly do nothing.*/installHooks?: boolean/**diff --git a/src/shared/agents/hook-events.ts b/src/shared/agents/hook-events.tsnew file mode 100644index 000000000..01fee751e--- /dev/null+++ b/src/shared/agents/hook-events.ts@@ -0,0 +1,31 @@+// The hook events each agent's managed installer subscribes to — ONE list per agent, shared by+// every installer (local desktop, Server Edition, and the SSH remote installer).+//+// They used to be declared twice, and the copies had drifted: the remote installer subscribed+// claude to `SessionStart`/`SubagentStop` but NOT to `StopFailure`/`PermissionRequest` (so a+// remote agent's errored turn stuck on "working" and its permission prompts arrived late), and it+// subscribed gemini to CLAUDE's event names, which gemini never fires — remote gemini nodes+// reported no status at all.+//+// The drift also produced a broken settings.json on any machine where two installers ran: each+// rewrites only the events IT knows, so a stale instance's command survived on every event the+// other list lacked. Keeping the lists here is what makes an install a complete rewrite.++/** Claude Code hook events. Each maps to a `NormalizedAgentEvent` in shared/agents/normalize.ts. */+export const CLAUDE_HOOK_EVENTS = [+ 'SessionStart',+ 'UserPromptSubmit',+ 'Stop',+ // Fires INSTEAD of Stop when the turn ends on an API/model error — without it the+ // status badge sticks on "working" after any errored turn.+ 'StopFailure',+ 'Notification',+ // Dedicated permission-prompt signal (→ blocked), more direct than Notification.+ 'PermissionRequest',+ 'SessionEnd',+ 'PreToolUse',+ 'PostToolUse'+] as const++/** Gemini CLI hook events — its own names, NOT Claude's (see normalizeGemini). */+export const GEMINI_HOOK_EVENTS = ['BeforeAgent', 'AfterAgent', 'AfterTool', 'BeforeTool'] as const