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(hooks): recognize managed entries on Windows so installs replace instead of appending
enes05d312059cd6
diff --git a/CLAUDE.md b/CLAUDE.mdindex f951fb8c0..d0bbd6b82 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1069,7 +1069,17 @@ else, and its context links must keep classifying across restarts).*healed*, not preserved, on both the local and the SSH path). The per-event **`matcher`** the grokinstaller needs is why events are typed `ManagedHookEvent` (`string | {event, matcher}`): grok'stool matcher is a REGEX and must be `.*` — a bare `*` is invalid and silently stops tool events- firing. Plain-string events keep their byte-identical output for every other agent.+ firing. Plain-string events keep their byte-identical output for every other agent. **Both+ sides of the managed-entry match go through `normalizeHookCommand`** — the marker used to be+ folded to `/` while the stored command was compared raw, so on Windows nodeterm never recognized+ its OWN entry and appended a fresh set every launch (#558: nine copies of nine events, nine+ `claude.sh` processes per Stop, nine 45 s `PermissionRequest` waits racing one prompt). Because+ `mergeManagedHook` drops every managed entry before pushing one fresh, the corrected match IS the+ repair for a file already ruined — it runs at boot via `installManagedAgentHooks` and, being the+ ONE shared merge, heals claude/gemini/grok, every managed Claude account dir and all three SSH+ remote installers at once; a second repair mechanism would be exactly the duplicated rule this+ file warns about. It strips only OUR handler out of a definition, so a hook a user hand-merged+ beside ours survives.- **Per-node hook identity** (`src/core/agents/node-auth-*.ts`, `node-token-*.ts`,`node-identity-policy.ts` — full write-up in **`docs/node-identity.md`**) — the shared bearer proves"a session on this machine", never *which* session, so every node also gets a capability deriveddiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 87822590a..632f286e8 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -86,6 +86,14 @@ registry is missing a field.on POSIX a backslash is legal filename text — do not treat both separators as interchangeableunless the owning filesystem is known to be Windows.+- **Normalize BOTH sides of a path comparison, through one function.** A marker normalized where+ it is built and matched raw where it is used is a no-op on the machine you wrote it on and a+ silent defect on Windows. That is issue #558: the managed-hook marker was folded to `/` while+ the stored command still carried `\`, so nodeterm stopped recognizing its own hook entries and+ appended a fresh copy of all nine on every launch — nine hook processes per event, nine+ concurrent 45 s permission waits racing one prompt. Write the normalizer once, use it on both+ sides, and pin it with a `C:\`-shaped test.+- **Never publish a file with a bare `fs.rename`.** Use `renameAtomic` or `writeFileAtomic` from`src/core/fs-atomic.ts`. On Windows a rename fails with `EPERM` whenever anything has thedestination open — Defender scanning the file you just wrote, the search indexer, OneDrive — sodiff --git a/src/core/agents/hooks/codex.ts b/src/core/agents/hooks/codex.tsindex d3e709139..8bb87d050 100644--- a/src/core/agents/hooks/codex.ts+++ b/src/core/agents/hooks/codex.ts@@ -27,6 +27,7 @@ import {import { randomUUID } from 'crypto'import { renameAtomicSync } from '../../fs-atomic'import { buildManagedScript } from './managed-script'+import { normalizeHookCommand } from './install-helper'import {computeTrustedHash,getCodexCanonicalTrustPath,@@ -101,7 +102,10 @@ function scriptPath(): string {// keys off the path segment, not the exact command string.function isManagedCommand(command: string | undefined): boolean {if (!command) return false- return command.replaceAll('\\', '/').includes(`agent-hooks/${SCRIPT_FILE_NAME}`)+ // Separator folding comes from install-helper so the two installers can never disagree about+ // what makes an entry ours — the drift that made the JSON-settings agents duplicate on Windows+ // (#558). Only the normalizer is shared; codex's merge stays its own (the trust hash).+ return normalizeHookCommand(command).includes(`agent-hooks/${SCRIPT_FILE_NAME}`)}function definitionHasManagedCommand(def: HookDefinition): boolean {diff --git a/src/core/agents/hooks/install-helper.fs.test.ts b/src/core/agents/hooks/install-helper.fs.test.tsnew file mode 100644index 000000000..f12816fa7--- /dev/null+++ b/src/core/agents/hooks/install-helper.fs.test.ts@@ -0,0 +1,83 @@+// The repair issue #558 actually owes the user: their settings.json ON DISK must come back to one+// managed entry per event at the next launch, not just a fresh install. `installManagedAgentHooks`+// runs `installHooksInto` for every agent at boot, so proving it here proves the repair.+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'fs'+import { tmpdir } from 'os'+import path from 'path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// `installManagedHookScript` writes into homedir()/.nodeterm — point that at a temp dir so the+// test never touches the machine's real home.+let home = ''+vi.mock('os', async (orig) => {+ const actual = await orig<typeof import('os')>()+ return { ...actual, default: { ...actual, homedir: () => home }, homedir: () => home }+})++import { installHooksInto, removeHooksFrom } from './install-helper'+import { CLAUDE_HOOK_EVENTS } from '@shared/agents/hook-events'++const WIN_CMD =+ "if [ -r 'C:\\Users\\u\\.nodeterm\\agent-hooks\\claude.sh' ]; then sh 'C:\\Users\\u\\.nodeterm\\agent-hooks\\claude.sh'; else cat >/dev/null 2>&1 || :; fi"+const FOREIGN = { hooks: [{ type: 'command', command: 'sh "C:\\tools\\agent-hooks\\other.sh"' }] }++let dir = ''+const configPath = () => path.join(dir, '.claude', 'settings.json')+const readConfig = () => JSON.parse(readFileSync(configPath(), 'utf8'))+const install = () =>+ installHooksInto({+ agentId: 'claude',+ scriptFileName: 'claude.sh',+ configPath: configPath(),+ events: CLAUDE_HOOK_EVENTS+ })++beforeEach(() => {+ dir = mkdtempSync(path.join(tmpdir(), 'nt-hooks-'))+ home = dir+ mkdirSync(path.join(dir, '.claude'), { recursive: true })+})+afterEach(() => rmSync(dir, { recursive: true, force: true }))++describe('installHooksInto — heals an already-broken settings.json (issue #558)', () => {+ it('collapses 9 accumulated duplicates per event to 1 and keeps the user`s own hooks', () => {+ const hooks: Record<string, unknown[]> = { PreCompact: [FOREIGN] }+ for (const ev of CLAUDE_HOOK_EVENTS) {+ hooks[ev as string] = [FOREIGN, ...Array.from({ length: 9 }, () => ({ hooks: [{ type: 'command', command: WIN_CMD }] }))]+ }+ writeFileSync(configPath(), JSON.stringify({ model: 'opus', hooks }, null, 2), 'utf8')++ install()++ const after = readConfig()+ for (const ev of CLAUDE_HOOK_EVENTS) {+ const defs = after.hooks[ev as string]+ expect(defs, ev as string).toHaveLength(2)+ expect(defs[0], ev as string).toEqual(FOREIGN)+ expect(defs[1].hooks[0].command, ev as string).toContain('agent-hooks')+ }+ // An event we do not manage keeps the foreign hook untouched, and unrelated settings survive.+ expect(after.hooks.PreCompact).toEqual([FOREIGN])+ expect(after.model).toBe('opus')+ })++ it('is idempotent — a second and third run change nothing', () => {+ install()+ const once = readFileSync(configPath(), 'utf8')+ install()+ install()+ expect(readFileSync(configPath(), 'utf8')).toBe(once)+ })+})++describe('removeHooksFrom — uninstall also matched raw before the fix', () => {+ it('removes a windows-path managed entry and keeps a foreign one', () => {+ writeFileSync(+ configPath(),+ JSON.stringify({ hooks: { Stop: [FOREIGN, { hooks: [{ type: 'command', command: WIN_CMD }] }] } }),+ 'utf8'+ )+ removeHooksFrom({ configPath: configPath(), events: CLAUDE_HOOK_EVENTS, scriptFileName: 'claude.sh' })+ expect(readConfig().hooks.Stop).toEqual([FOREIGN])+ })+})diff --git a/src/core/agents/hooks/install-helper.test.ts b/src/core/agents/hooks/install-helper.test.tsindex 00b257fdf..2ab62b751 100644--- a/src/core/agents/hooks/install-helper.test.ts+++ b/src/core/agents/hooks/install-helper.test.ts@@ -1,5 +1,6 @@+import path from 'path'import { describe, expect, it } from 'vitest'-import { buildManagedHookCommand, mergeManagedHook } from './install-helper'+import { buildManagedHookCommand, mergeManagedHook, type HookSettings } from './install-helper'import { CLAUDE_HOOK_EVENTS } from '@shared/agents/hook-events'const cmd = buildManagedHookCommand('/remote/.nodeterm/agent-hooks/claude.sh')@@ -111,3 +112,85 @@ describe('mergeManagedHook — matcher support is opt-in per event', () => {expect(out.hooks!.PreToolUse[0]).toEqual({ matcher: '.*', hooks: [{ type: 'command', command: 'CMD' }] })})})++/**+ * Issue #558 — the marker was normalized to `/` while the stored command was matched raw, so on+ * Windows we never recognized our OWN entry: the filter kept it and every launch appended a fresh+ * set. A user reported nine identical definitions on each of the nine claude events (23,916-byte+ * settings.json) — nine `claude.sh` processes and nine POSTs per Stop, and nine concurrent 45 s+ * `PermissionRequest` waits all entitled to answer the same prompt.+ *+ * These run on any OS: the win32-ness that matters is the SEPARATOR inside the stored command,+ * which `path.win32` gives us without a Windows runner.+ */+describe('mergeManagedHook — Windows path separators (issue #558)', () => {+ const winScript = path.win32.join('C:\\Users\\u', '.nodeterm', 'agent-hooks', 'claude.sh')+ const winCmd = buildManagedHookCommand(winScript)++ it('the command really does carry backslashes (guards the fixture itself)', () => {+ expect(winScript).toBe('C:\\Users\\u\\.nodeterm\\agent-hooks\\claude.sh')+ expect(winCmd).toContain('agent-hooks\\claude.sh')+ })++ it('recognizes its own entry — five installs leave ONE, not five', () => {+ let cfg: HookSettings = {}+ for (let i = 0; i < 5; i++) cfg = mergeManagedHook(cfg, winCmd, ['Stop'])+ expect(cfg.hooks!.Stop).toEqual([{ hooks: [{ type: 'command', command: winCmd }] }])+ })++ it('repairs the file a broken build already wrote: 9 duplicates per event collapse to 1', () => {+ // The reported state, rebuilt: nine byte-identical definitions on every managed event.+ const dup = { hooks: [{ type: 'command', command: winCmd }] }+ const hooks: Record<string, typeof dup[]> = {}+ for (const ev of CLAUDE_HOOK_EVENTS) hooks[ev as string] = Array.from({ length: 9 }, () => ({ ...dup }))+ const out = mergeManagedHook({ hooks }, winCmd, CLAUDE_HOOK_EVENTS)+ for (const ev of CLAUDE_HOOK_EVENTS) {+ expect(out.hooks![ev as string], ev as string).toEqual([{ hooks: [{ type: 'command', command: winCmd }] }])+ }+ })++ it('collapses duplicates written with the OTHER separator too', () => {+ // Same machine, different builds/instances: only the separator spelling differs, and both+ // sides of the comparison are normalized now, so either spelling is recognized as ours.+ const posix = buildManagedHookCommand('/home/u/.nodeterm/agent-hooks/claude.sh')+ const before = {+ hooks: { Stop: [{ hooks: [{ type: 'command', command: winCmd }] }, { hooks: [{ type: 'command', command: posix }] }] }+ }+ expect(mergeManagedHook(before, winCmd, ['Stop']).hooks!.Stop).toEqual([+ { hooks: [{ type: 'command', command: winCmd }] }+ ])+ })++ it("still leaves a foreign tool's windows-path hook alone", () => {+ const foreign = { hooks: [{ type: 'command', command: 'sh "C:\\Users\\u\\.someapp\\agent-hooks\\other.sh"' }] }+ const out = mergeManagedHook({ hooks: { Stop: [foreign, { hooks: [{ type: 'command', command: winCmd }] }] } }, winCmd, ['Stop'])+ expect(out.hooks!.Stop).toEqual([foreign, { hooks: [{ type: 'command', command: winCmd }] }])+ })+})++describe('mergeManagedHook — only OUR handler is removed from a shared definition', () => {+ it("keeps a user's handler that sits beside ours in one definition", () => {+ const mixed = {+ matcher: '.*',+ hooks: [+ { type: 'command', command: 'my-own-hook.sh' },+ { type: 'command', command: cmd }+ ]+ }+ const out = mergeManagedHook({ hooks: { Stop: [mixed] } }, cmd, ['Stop'])+ expect(out.hooks!.Stop).toEqual([+ { matcher: '.*', hooks: [{ type: 'command', command: 'my-own-hook.sh' }] },+ { hooks: [{ type: 'command', command: cmd }] }+ ])+ })++ it('survives a hand-edited definition whose handler has no command at all', () => {+ const junk = { hooks: [{ type: 'command' } as unknown as { type: string; command: string }] }+ expect(() => mergeManagedHook({ hooks: { Stop: [junk] } }, cmd, ['Stop'])).not.toThrow()+ })++ it('leaves a non-array event value we cannot interpret exactly as found', () => {+ const before = { hooks: { SubagentStop: 'nonsense' as unknown as [] } }+ expect(mergeManagedHook(before, cmd, ['Stop']).hooks!.SubagentStop).toBe('nonsense')+ })+})diff --git a/src/core/agents/hooks/install-helper.ts b/src/core/agents/hooks/install-helper.tsindex d9ac17212..1f313f06b 100644--- a/src/core/agents/hooks/install-helper.ts+++ b/src/core/agents/hooks/install-helper.ts@@ -6,7 +6,8 @@// (chmod 0o755, best-effort), then reference it as `sh "<scriptPath>"` from each event;// - idempotent re-install: drop any prior managed entry for that event (command includes// the `agent-hooks` path segment OR the legacy `claude-signals` marker) before pushing-// the fresh one;+// the fresh one — matching on both sides through `normalizeHookCommand`, WITHOUT which+// Windows recognized none of its own entries and appended a fresh set per launch (#558);// - preserve every other hook (other tools', other events);// - fail open: a missing/unparseable settings.json defaults to {} (install) / returns// early (remove); a write error is caught + warned, never thrown.@@ -78,13 +79,70 @@ export function buildManagedHookCommand(scriptPath: string): string {return `if [ -r ${q} ]; then sh ${q}; else cat >/dev/null 2>&1 || :; fi`}+/**+ * The ONE place a hook command is put into comparable form: native path separators folded to `/`.+ *+ * BOTH sides of every managed-entry comparison must go through this. They used not to+ * (issue #558): the marker was normalized here while `isManaged` matched the RAW stored command,+ * so on Windows the marker read `agent-hooks/claude.sh` and the stored command carried+ * `agent-hooks\claude.sh` — `includes()` was false for OUR OWN entry, the filter kept it, and+ * every boot appended one more copy of all nine events. Nine identical entries means nine+ * `claude.sh` processes and nine POSTs per Stop, and nine concurrent 45 s `PermissionRequest`+ * waits each entitled to answer the same prompt. macOS/Linux never saw it because there the two+ * spellings already agree.+ *+ * Only ever used for MATCHING — what we write is the untouched command, whose quoting and+ * separators must stay exactly as the host shell expects. That is also why folding the two+ * separators together is safe despite a backslash being legal filename text on POSIX: the fold+ * decides nothing but whether a command carries our own `agent-hooks/<script>` tail, and it never+ * reaches a path that gets resolved.+ */+export function normalizeHookCommand(command: string): string {+ return command.replaceAll('\\', '/')+}+// The marker identifying OUR entry: the `agent-hooks/<scriptFile>` tail of the managed// command. A bare "agent-hooks" substring is NOT enough — other tools use the same dir// name (e.g. `~/.someapp/agent-hooks/claude-hook.sh`), and matching them would delete a// foreign app's hooks from any event we both subscribe to.function managedMarkerFor(command: string): string {- const m = command.match(/agent-hooks[\\/][^"'\s]+/)- return m ? m[0].replace(/\\/g, '/') : 'agent-hooks'+ const m = normalizeHookCommand(command).match(/agent-hooks\/[^"'\s]+/)+ return m ? m[0] : 'agent-hooks'+}++/**+ * Does one handler's command belong to us? `legacy` also accepts the pre-hook-server+ * `claude-signals` marker (the install path sweeps it; the uninstall path deliberately does not,+ * so it only ever removes what this build wrote).+ *+ * A hand-edited settings.json can hold a definition with no `command` at all — answer false+ * rather than throwing, or one malformed entry skips the whole agent's install.+ */+function managedCommandMatcher(marker: string, legacy: boolean): (command?: string) => boolean {+ return (command?: string) => {+ if (typeof command !== 'string') return false+ const c = normalizeHookCommand(command)+ return c.includes(marker) || (legacy && c.includes('claude-signals'))+ }+}++const defHasManaged = (d: HookDef, isOurs: (command?: string) => boolean): boolean =>+ !!d.hooks?.some((h) => isOurs(h.command))++/**+ * Drop OUR handlers out of a definition list, keeping everything else byte-for-byte.+ *+ * Handler-level, not definition-level: our own entry always holds exactly one handler, so for+ * anything we wrote the two are identical — but a user who hand-merged our command INTO their+ * own definition would otherwise lose their handler alongside ours. A definition left with no+ * handlers disappears; a definition holding none of ours is returned by identity.+ */+function stripManaged(defs: HookDef[], isOurs: (command?: string) => boolean): HookDef[] {+ return defs.flatMap((d) => {+ if (!defHasManaged(d, isOurs)) return [d]+ const kept = (d.hooks ?? []).filter((h) => !isOurs(h.command))+ return kept.length ? [{ ...d, hooks: kept }] : []+ })}/** A subscription's event name, whichever form it was declared in. */@@ -93,13 +151,6 @@ const eventNameOf = (e: ManagedHookEvent): string => (typeof e === 'string' ? e* agents that never needed one (grok's tool events are the only case; see ManagedHookEvent). */const matcherOf = (e: ManagedHookEvent): string | undefined => (typeof e === 'string' ? undefined : e.matcher)-/** A managed entry: matches OUR script under `agent-hooks/` or the legacy `claude-signals` marker. */-function isManaged(d: HookDef, marker: string): boolean {- return !!d.hooks?.some(- (h) => h.command.includes(marker) || h.command.includes('claude-signals')- )-}-/*** Pure: make the config's managed hooks EXACTLY ours — our command on every event in `events`, and* no managed entry anywhere else.@@ -110,18 +161,27 @@ function isManaged(d: HookDef, marker: string): boolean {* 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.+ *+ * It is equally the repair for issue #558: EVERY managed entry on a subscribed event is filtered+ * out before the fresh one is pushed, so a Windows settings.json that accumulated N duplicates+ * collapses to exactly one the next time the installer runs (i.e. at the next app launch — see+ * `installManagedAgentHooks`). That heals the file a user already has, not just a fresh install,+ * and because this one function serves claude, gemini and grok locally, every managed Claude+ * account dir, and all three SSH remote installers, the repair reaches all of them at once. It+ * only ever removes commands carrying OUR marker — a foreign tool's hooks are untouched.*/export function mergeManagedHook(config: HookSettings,command: string,events: readonly ManagedHookEvent[]): HookSettings {- const marker = managedMarkerFor(command)+ const isOurs = managedCommandMatcher(managedMarkerFor(command), true)const next: HookSettings = { ...config, hooks: { ...(config.hooks ?? {}) } }+ const definitionsAt = (ev: string): HookDef[] => (Array.isArray(next.hooks![ev]) ? next.hooks![ev] : [])for (const e of events) {const ev = eventNameOf(e)const matcher = matcherOf(e)- const existing = (next.hooks![ev] ?? []).filter((d) => !isManaged(d, marker))+ const existing = stripManaged(definitionsAt(ev), isOurs)// Spread the matcher CONDITIONALLY: an explicit `matcher: undefined` would serialize as a// missing key here but still change the object shape snapshots compare. The test is// `!== undefined`, not truthiness — the type permits `matcher: ''`, and silently dropping an@@ -132,8 +192,11 @@ export function mergeManagedHook(const managedEvents = new Set(events.map(eventNameOf))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+ const defs = next.hooks![ev]+ // A non-array here is a hand-mangled file we cannot interpret: leave it exactly as found+ // rather than deleting data on a guess (the subscribed events above still get our hook).+ if (!Array.isArray(defs) || !defs.some((d) => defHasManaged(d, isOurs))) continue+ const kept = stripManaged(defs, isOurs)if (kept.length === 0) delete next.hooks![ev]else next.hooks![ev] = kept}@@ -178,7 +241,9 @@ export interface RemoveHooksOptions {export function removeHooksFrom(opts: RemoveHooksOptions): void {const { configPath, events, scriptFileName } = opts- const marker = `agent-hooks/${scriptFileName}`+ // Same normalized comparison as the installer — a raw `includes` left every entry behind on+ // Windows (issue #558), so uninstall silently did nothing there.+ const isOurs = managedCommandMatcher(`agent-hooks/${scriptFileName}`, false)let config: Settingstry {config = JSON.parse(readFileSync(configPath, 'utf8')) as Settings@@ -188,8 +253,8 @@ export function removeHooksFrom(opts: RemoveHooksOptions): void {if (!config.hooks) returnfor (const e of events) {const ev = eventNameOf(e)- if (!config.hooks[ev]) continue- config.hooks[ev] = config.hooks[ev].filter((d) => !d.hooks?.some((h) => h.command.includes(marker)))+ if (!Array.isArray(config.hooks[ev])) continue+ config.hooks[ev] = stripManaged(config.hooks[ev], isOurs)if (config.hooks[ev].length === 0) delete config.hooks[ev]}try {