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(antigravity): harden the hook install for POSIX and for the user's own config
reviewc2e67a26a052
diff --git a/src/core/agents/hook-server.hook-event-field.test.ts b/src/core/agents/hook-server.hook-event-field.test.tsindex 4137b6d79..ede2f2557 100644--- a/src/core/agents/hook-server.hook-event-field.test.ts+++ b/src/core/agents/hook-server.hook-event-field.test.ts@@ -84,7 +84,7 @@ describe('the nodeterm_hook_event form field', () => {expect(events[0].state).toBe('working')})- it('without the field, a planted value is all there is — and a POST without either maps to nothing', async () => {+ it('a POST without the field maps to nothing', async () => {const res = await post('antigravity', {nodeId: 'term-agy-1',payload: JSON.stringify({ fullyIdle: true, conversationId: 'x' })@@ -117,6 +117,26 @@ describe('the nodeterm_hook_event form field', () => {expect(raws[0]).not.toHaveProperty('nodeterm_hook_event')})+ it('without the field, a value planted in the agent JSON is DELETED, not trusted', async () => {+ // The form is the one source for antigravity: the script always sends it, so a payload that+ // names its own event (it never does) is someone else's word and must not stand.+ await post('antigravity', {+ nodeId: 'term-agy-1',+ payload: JSON.stringify({ nodeterm_hook_event: 'Stop', fullyIdle: true, conversationId: 'x' })+ })+ expect(events).toHaveLength(0)+ expect(raws[0]).not.toHaveProperty('nodeterm_hook_event')+ })++ it('is merged for antigravity only — another agent never sees the field in its payload', async () => {+ await post('claude', {+ nodeId: 'term-claude-1',+ nodeterm_hook_event: 'PreInvocation',+ payload: JSON.stringify({ hook_event_name: 'Stop', session_id: 's' })+ })+ expect(raws[0]).not.toHaveProperty('nodeterm_hook_event')+ })+it('does not change what a claude POST normalizes to', async () => {await post('claude', {nodeId: 'term-claude-1',diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex 608e5b6af..2c1786daf 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -837,7 +837,12 @@ export class HookServer {// JSON. Deliberately NOT `hook_event_name`: that is a real payload field for claude, codex,// gemini and copilot, and a name of our own cannot collide with any of them. The value is// only ever compared against a closed set (normalizeAntigravity), never interpolated.- if (form.nodeterm_hook_event) payload.nodeterm_hook_event = form.nodeterm_hook_event+ // Antigravity only: no other normalizer reads it, and for antigravity the form is the ONE+ // source — an empty field DELETES a value planted in the JSON rather than letting it stand.+ if (agentId === 'antigravity') {+ if (form.nodeterm_hook_event) payload.nodeterm_hook_event = form.nodeterm_hook_event+ else delete payload.nodeterm_hook_event+ }// Raw listener first: it drives the transcript-tailing features (which need// transcript_path). Inside the try so a throwing raw listener still ends 204.this.rawListener?.(agentId, nodeId, payload, {diff --git a/src/core/agents/hooks/antigravity-script.test.ts b/src/core/agents/hooks/antigravity-script.test.tsindex d1fdd313e..572809604 100644--- a/src/core/agents/hooks/antigravity-script.test.ts+++ b/src/core/agents/hooks/antigravity-script.test.ts@@ -40,13 +40,23 @@ interface Run {stdout: stringstderr: stringstatus: number | null+ /** Wall time of the script run — what agy waits for before it reads the decision. */+ elapsedMs: number/** Every fake-curl invocation's argv, once the (backgrounded) POST has finished. */posts: () => string[]}-/** A stand-in curl that appends its argv (and nothing to stdout) to a log. */-const FAKE_CURL = (log: string): string =>- ['#!/bin/sh', `printf 'ARGV %s\\n' "$*" >> '${log.replaceAll('\\', '/')}'`, 'cat >/dev/null', 'exit 0', ''].join('\n')+/** A stand-in curl that appends its argv (and nothing to stdout) to a log. `delaySec` makes it+ * behave like an endpoint that accepts and never answers (curl's own --max-time is 1.5 s). */+const FAKE_CURL = (log: string, delaySec = 0): string =>+ [+ '#!/bin/sh',+ ...(delaySec > 0 ? [`sleep ${delaySec}`] : []),+ `printf 'ARGV %s\\n' "$*" >> '${log.replaceAll('\\', '/')}'`,+ 'cat >/dev/null',+ 'exit 0',+ ''+ ].join('\n')function runScript(opts: {event?: string@@ -56,6 +66,8 @@ function runScript(opts: {append?: string/** No endpoint file at all: the POST has nowhere to go. */noEndpoint?: boolean+ /** Seconds the fake curl stalls before it answers (a blackholed endpoint). */+ curlDelaySec?: number}): Run {const dir = join(root, `case-${++seq}`)const bin = join(dir, 'bin')@@ -63,7 +75,7 @@ function runScript(opts: {mkdirSync(bin, { recursive: true })mkdirSync(join(home, '.nodeterm'), { recursive: true })const log = join(dir, 'curl.log')- writeFileSync(join(bin, 'curl'), FAKE_CURL(log), { encoding: 'utf8', mode: 0o755 })+ writeFileSync(join(bin, 'curl'), FAKE_CURL(log, opts.curlDelaySec), { encoding: 'utf8', mode: 0o755 })const endpoint = join(home, '.nodeterm', 'hook-endpoint.env')if (!opts.noEndpoint) {writeFileSync(endpoint, 'NODETERM_HOOK_PORT=45999\nNODETERM_HOOK_TOKEN=t\nNODETERM_HOOK_VERSION=2\n', 'utf8')@@ -79,9 +91,12 @@ function runScript(opts: {if (process.env.SystemRoot) env.SystemRoot = process.env.SystemRootif (opts.nodeId !== null) env.NODETERM_NODE_ID = opts.nodeId ?? 'term-agy-1'if (opts.event !== undefined) env[ANTIGRAVITY_EVENT_ENV] = opts.event+ const started = Date.now()const res = spawnSync('sh', [script], { input: opts.input ?? '{"conversationId":"c1"}', env, timeout: T })+ const elapsedMs = Date.now() - startedreturn {dir,+ elapsedMs,stdout: res.stdout.toString('utf8'),stderr: res.stderr.toString('utf8'),status: res.status,@@ -300,7 +315,7 @@ describe('the hooks.json command (POSIX form)', () => {})expect(cmd).toBe("NODETERM_AGY_EVENT='PreToolUse'; export NODETERM_AGY_EVENT; " +- "if [ -r '/h/.nodeterm/agent-hooks/antigravity.sh' ]; then sh '/h/.nodeterm/agent-hooks/antigravity.sh'; " ++ "if [ -r '/h/.nodeterm/agent-hooks/antigravity.sh' ]; then sh '/h/.nodeterm/agent-hooks/antigravity.sh' || :; " +"else printf '%s\\n' '{\"decision\":\"ask\"}'; cat >/dev/null 2>&1 || :; fi")})@@ -336,4 +351,51 @@ describe('the hooks.json command (POSIX form)', () => {},T)++ it.skipIf(!shAvailable)(+ 'exits 0 even when the script fails AFTER answering (a broken endpoint file is sourced late)',+ () => {+ // The script answers FIRST, then sources the endpoint file. A syntax error there used to leak+ // out as `sh`'s exit status 2 — the right answer on stdout with a non-zero exit, a pair agy+ // was never measured on (silence + exit 1 is a measured DENY). The command forces 0.+ const dir = join(root, `cmd-${++seq}`)+ mkdirSync(dir, { recursive: true })+ const script = join(dir, 'antigravity.sh').replaceAll('\\', '/')+ writeFileSync(script, buildManagedScript('antigravity', null), { encoding: 'utf8', mode: 0o755 })+ const endpoint = join(dir, 'hook-endpoint.env')+ writeFileSync(endpoint, 'if then\n', 'utf8')+ const answer = antigravityDecisionFor('PreToolUse')!+ const cmd = buildManagedHookCommand(script, {+ env: { [ANTIGRAVITY_EVENT_ENV]: 'PreToolUse' },+ fallbackStdout: answer+ })+ const env: Record<string, string> = {+ PATH: process.env.PATH ?? '',+ HOME: dir,+ NODETERM_NODE_ID: 'term-agy-1',+ NODETERM_HOOK_ENDPOINT: endpoint+ }+ const res = spawnSync('sh', ['-c', cmd], { input: '{"conversationId":"c"}', env, timeout: T })+ expect(res.stdout.toString()).toBe(`${answer}\n`)+ expect(res.status).toBe(0)+ },+ T+ )+})++describe.skipIf(!shAvailable)('the POST never holds up the answer', () => {+ it('a stalled endpoint does not delay the script: the POST runs in the background', () => {+ // agy waits for the hook PROCESS to exit before it acts on the decision, and our handler's+ // timeout is ANTIGRAVITY_HOOK_TIMEOUT (5 s). A foreground POST against an endpoint that accepts+ // and never answers, plus the bounded fallback walk, measured ~6 s — past that timeout, on+ // every tool call. The fake curl here stalls for 6 s; the script must be long gone by then,+ // and the POST must still arrive afterwards.+ const r = runScript({ event: 'PreToolUse', curlDelaySec: 6 })+ expect(r.stdout).toBe(`${antigravityDecisionFor('PreToolUse')}\n`)+ expect(r.status).toBe(0)+ expect(r.elapsedMs).toBeLessThan(3000)+ const posts = r.posts()+ expect(posts).toHaveLength(1)+ expect(posts[0]).toContain('nodeterm_hook_event=PreToolUse')+ }, T)})diff --git a/src/core/agents/hooks/antigravity.test.ts b/src/core/agents/hooks/antigravity.test.tsindex 2d77f1e44..958e3ccb1 100644--- a/src/core/agents/hooks/antigravity.test.ts+++ b/src/core/agents/hooks/antigravity.test.ts@@ -9,7 +9,17 @@ import { createServer, type Server } from 'node:http'import type { AddressInfo } from 'node:net'import osDefault from 'os'import { spawnSync } from 'node:child_process'-import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, statSync } from 'node:fs'+import {+ mkdtempSync,+ mkdirSync,+ writeFileSync,+ readFileSync,+ existsSync,+ rmSync,+ statSync,+ lstatSync,+ symlinkSync+} from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import {@@ -129,9 +139,19 @@ describe('the bundle', () => {})it('recognizes both leaves on every platform, and nothing foreign', () => {- expect(isAntigravityManagedCommand('sh /x/agent-hooks/antigravity.sh')).toBe(true)- expect(isAntigravityManagedCommand('C:\\x\\agent-hooks\\antigravity-hook.cmd Stop')).toBe(true)- expect(isAntigravityManagedCommand('sh /x/agent-hooks/gemini.sh')).toBe(false)+ expect(isAntigravityManagedCommand('sh /x/.nodeterm/agent-hooks/antigravity.sh')).toBe(true)+ expect(isAntigravityManagedCommand('C:\\x\\.nodeterm\\agent-hooks\\antigravity-hook.cmd Stop')).toBe(true)+ // The shape the Windows command really has: relative to hooks.json's directory.+ expect(+ isAntigravityManagedCommand(+ 'if exist ..\\..\\.nodeterm\\agent-hooks\\antigravity-hook.cmd (call ..\\..\\.nodeterm\\agent-hooks\\antigravity-hook.cmd Stop) & exit 0'+ )+ ).toBe(true)+ expect(isAntigravityManagedCommand('sh /x/.nodeterm/agent-hooks/gemini.sh')).toBe(false)+ // A user's OWN gate that merely shares the leaf name is not ours (the suffix match codex and+ // claude use would have swept it, and the withdrawal would have reported removing our bundle).+ expect(isAntigravityManagedCommand('~/work/agent-hooks/antigravity.sh --policy strict')).toBe(false)+ expect(isAntigravityManagedCommand('C:\\tools\\agent-hooks\\antigravity-hook.cmd')).toBe(false)expect(isAntigravityManagedCommand('/opt/other-tool/antigravity.sh')).toBe(false)expect(isAntigravityManagedCommand(undefined)).toBe(false)expect(isAntigravityManagedCommand(7)).toBe(false)@@ -243,10 +263,75 @@ describe('installAntigravityHooks / removeAntigravityHooks', () => {expect(own(removed, ANTIGRAVITY_BUNDLE_KEY)).toBe(false)})+ it('keeps the user\'s "enabled": false on our bundle across a re-install (the opt-out)', () => {+ const f = join(fresh(), 'hooks.json')+ install(f)+ const disabled = read(f)+ ;(disabled[ANTIGRAVITY_BUNDLE_KEY] as Record<string, unknown>).enabled = false+ writeFileSync(f, JSON.stringify(disabled), 'utf8')+ expect(install(f)).toBe('installed')+ const after = read(f)[ANTIGRAVITY_BUNDLE_KEY] as Record<string, unknown>+ expect(after.enabled).toBe(false)+ // …and the handlers are still refreshed, so re-enabling later gets the current commands.+ expect({ ...after, enabled: undefined }).toEqual({+ enabled: undefined,+ ...buildAntigravityBundle((ev) => antigravityCommandFor(POSIX_SCRIPT, ev, 'linux'))+ })+ })++ it('does not invent an "enabled" key, and treats anything but a literal false as enabled', () => {+ const f = join(fresh(), 'hooks.json')+ install(f)+ expect(Object.hasOwn(read(f)[ANTIGRAVITY_BUNDLE_KEY] as object, 'enabled')).toBe(false)+ const withTrue = read(f)+ ;(withTrue[ANTIGRAVITY_BUNDLE_KEY] as Record<string, unknown>).enabled = 'false'+ writeFileSync(f, JSON.stringify(withTrue), 'utf8')+ install(f)+ expect(Object.hasOwn(read(f)[ANTIGRAVITY_BUNDLE_KEY] as object, 'enabled')).toBe(false)+ })++ it("never sweeps a user's own gate that merely shares our script's leaf name", () => {+ const f = join(fresh(), 'hooks.json')+ const mine = {+ PreToolUse: [+ { matcher: 'run_command', hooks: [{ command: '~/work/agent-hooks/antigravity.sh --policy strict' }] }+ ]+ }+ writeFileSync(f, JSON.stringify({ 'my-safety-gate': mine }), 'utf8')+ install(f)+ expect(read(f)['my-safety-gate']).toEqual(mine)+ expect(removeAntigravityHooks({ hooksJson: f })).toBe('withdrawn')+ expect(read(f)).toEqual({ 'my-safety-gate': mine })+ // With only the user's gate left, a second withdrawal finds nothing of ours.+ expect(removeAntigravityHooks({ hooksJson: f })).toBe('absent')+ })++ it.skipIf(process.platform === 'win32')(+ 'a symlinked hooks.json stays a symlink, its target gets the bundle, and its mode is kept',+ () => {+ // A dotfiles setup: ~/.gemini/config/hooks.json -> ~/dotfiles/agy-hooks.json. A plain rename+ // replaced the link with a regular file, so the dotfile never saw the bundle (and 0600+ // became 0644). Symlinks need privileges on Windows, hence the skip.+ const d = fresh()+ const target = join(d, 'dotfiles-hooks.json')+ writeFileSync(target, JSON.stringify({ mine: {} }), { encoding: 'utf8', mode: 0o600 })+ const link = join(d, 'config', 'hooks.json')+ mkdirSync(join(d, 'config'), { recursive: true })+ symlinkSync(target, link)+ expect(install(link)).toBe('installed')+ expect(lstatSync(link).isSymbolicLink()).toBe(true)+ expect(Object.keys(read(target))).toEqual(['mine', ANTIGRAVITY_BUNDLE_KEY])+ expect(statSync(target).mode & 0o777).toBe(0o600)+ expect(removeAntigravityHooks({ hooksJson: link })).toBe('withdrawn')+ expect(lstatSync(link).isSymbolicLink()).toBe(true)+ expect(read(target)).toEqual({ mine: {} })+ }+ )+it('a "__proto__" key inside a foreign bundle survives the sweep of a stray entry of ours', () => {const out = applyAntigravityBundle(JSON.parse(- '{"other":{"__proto__":[{"type":"command","command":"keep"}],"Stop":[{"type":"command","command":"sh /u/agent-hooks/antigravity.sh"}]}}'+ '{"other":{"__proto__":[{"type":"command","command":"keep"}],"Stop":[{"type":"command","command":"sh /u/.nodeterm/agent-hooks/antigravity.sh"}]}}'),null)@@ -268,7 +353,7 @@ describe('installAntigravityHooks / removeAntigravityHooks', () => {it("keeps a foreign event that was already empty when it sweeps another of that bundle's events", () => {const out = applyAntigravityBundle(- { foreign: { PostToolUse: [], Stop: [{ type: 'command', command: 'sh /u/agent-hooks/antigravity.sh' }] } },+ { foreign: { PostToolUse: [], Stop: [{ type: 'command', command: 'sh /u/.nodeterm/agent-hooks/antigravity.sh' }] } },null)expect(out.foreign).toEqual({ PostToolUse: [] })diff --git a/src/core/agents/hooks/antigravity.ts b/src/core/agents/hooks/antigravity.tsindex b51186f4f..4ec319f51 100644--- a/src/core/agents/hooks/antigravity.ts+++ b/src/core/agents/hooks/antigravity.ts@@ -37,6 +37,7 @@ import {writeManagedHookFileAtomic} from './install-helper'import { buildManagedScript } from './managed-script'+import { updateSettingsFile } from './settings-file'import { ANTIGRAVITY_EVENT_ENV, antigravityDecisionFor } from './antigravity-decision'import {ANTIGRAVITY_SCRIPT_FILE,@@ -150,13 +151,21 @@ export function buildAntigravityBundle(return bundle}-/** Does a handler command belong to us? Both leaves, on every platform (codex's #558 rule). */+/**+ * Does a handler command belong to us? Both leaves, on every platform (codex's #558 rule), and+ * ANCHORED on `.nodeterm/agent-hooks/`: our script only ever lives in `~/.nodeterm/agent-hooks/`+ * (`antigravityScriptPath`; the Windows command reaches it as `..\..\.nodeterm\agent-hooks\…`).+ * The bare `agent-hooks/antigravity.sh` suffix codex/claude match on (they need it for old userData+ * script paths; this agent has no such history) would also sweep a user's OWN gate that happens to+ * live at `~/work/agent-hooks/antigravity.sh` — and the withdrawal pass would then log that it+ * removed "the nodeterm-status bundle".+ */export function isAntigravityManagedCommand(command: unknown): boolean {if (typeof command !== 'string') return falseconst c = normalizeHookCommand(command)return (- c.includes(`agent-hooks/${ANTIGRAVITY_SCRIPT_FILE}`) ||- c.includes(`agent-hooks/${ANTIGRAVITY_WINDOWS_WRAPPER_FILE}`)+ c.includes(`.nodeterm/agent-hooks/${ANTIGRAVITY_SCRIPT_FILE}`) ||+ c.includes(`.nodeterm/agent-hooks/${ANTIGRAVITY_WINDOWS_WRAPPER_FILE}`))}@@ -230,7 +239,15 @@ export function applyAntigravityBundle(if (key === ANTIGRAVITY_BUNDLE_KEY) continuesetOwn(next, key, sweepBundle(value))}- if (bundle) setOwn(next, ANTIGRAVITY_BUNDLE_KEY, bundle)+ if (bundle) {+ // agy's own switch is the user's opt-out: `"enabled": false` on our bundle turns the whole+ // gate off, and every launch rewrites the bundle — so a `false` found there is carried over,+ // or nodeterm would silently switch back on a gate in front of every tool call the user had+ // switched off. Only a literal `false` counts; anything else is the default (enabled).+ const prior = file[ANTIGRAVITY_BUNDLE_KEY]+ const disabled = isRecord(prior) && prior.enabled === false+ setOwn(next, ANTIGRAVITY_BUNDLE_KEY, disabled ? { enabled: false, ...bundle } : bundle)+ }return next}@@ -245,9 +262,32 @@ function readHooksFile(file: string): AntigravityHooksFile | null | undefined {}}-function writeHooksFile(file: string, data: AntigravityHooksFile): void {- mkdirSync(path.dirname(file), { recursive: true })- writeManagedHookFileAtomic(file, `${JSON.stringify(data, null, 2)}\n`)+/**+ * Publish hooks.json through the shared settings transaction (#851, `updateSettingsFile`): resolve+ * a symlinked file (a dotfiles setup) and update its TARGET instead of replacing the link, keep the+ * file's mode, serialize our writers behind a lock, and refuse to publish over a file that changed+ * while we computed the update — agy's own `/hooks` editor writes this same file. `transform` is+ * re-applied to the config read INSIDE the lock, so the published file is never built from a+ * snapshot someone else has since replaced.+ *+ * `writeFile` (tests only) receives the transformed snapshot instead, as before.+ */+function publishHooksFile(+ file: string,+ current: AntigravityHooksFile,+ transform: (config: AntigravityHooksFile) => AntigravityHooksFile,+ writeFile?: (file: string, data: AntigravityHooksFile) => void+): void {+ if (writeFile) {+ writeFile(file, transform(current))+ return+ }+ if (updateSettingsFile(file, transform)) return+ // `false` is both "nothing to change" and "could not publish". Re-read to tell them apart: a+ // file that already says what we would write is a success, anything else is a failed write.+ const now = readHooksFile(file)+ if (now && JSON.stringify(transform(now)) === JSON.stringify(now)) return+ throw new Error(`could not update ${file} (locked by another writer, changed during the update, or unreadable)`)}/**@@ -398,7 +438,7 @@ export function installAntigravityHooks(opts: AntigravityInstallOptions = {}): Areturn 'refused'}try {- ;(opts.writeFile ?? writeHooksFile)(hooksJson, applyAntigravityBundle(current ?? {}, bundle))+ publishHooksFile(hooksJson, current ?? {}, (cfg) => applyAntigravityBundle(cfg, bundle), opts.writeFile)return 'installed'} catch (e) {console.warn('[agent-hooks] antigravity install failed', e)@@ -492,7 +532,7 @@ export function removeAntigravityHooks(// `__proto__` key as data, so it compares like any other.if (JSON.stringify(next) === JSON.stringify(current)) return 'absent'try {- ;(opts.writeFile ?? writeHooksFile)(hooksJson, next)+ publishHooksFile(hooksJson, current, (cfg) => applyAntigravityBundle(cfg, null), opts.writeFile)return 'withdrawn'} catch {return 'failed'diff --git a/src/core/agents/hooks/install-helper.ts b/src/core/agents/hooks/install-helper.tsindex 0e76f33c1..d8091940f 100644--- a/src/core/agents/hooks/install-helper.ts+++ b/src/core/agents/hooks/install-helper.ts@@ -131,7 +131,13 @@ export function buildManagedHookCommand(scriptPath: string, opts: ManagedHookCom}).join('')const answer = opts.fallbackStdout !== undefined ? `printf '%s\\n' ${shQuote(opts.fallbackStdout)}; ` : ''- return `${prefix}if [ -r ${q} ]; then sh ${q}; else ${answer}cat >/dev/null 2>&1 || :; fi`+ // An agent that reads our stdout as a DECISION (fallbackStdout set) also reads the exit status:+ // for antigravity a non-zero exit is a measured DENY even when the right answer was already+ // printed (the script answers FIRST, then sources the endpoint file, whose syntax error would+ // otherwise leak out as `sh`'s status). So that branch forces 0, as the Windows wrapper does.+ // Every other agent's command stays byte-identical.+ const exitZero = opts.fallbackStdout !== undefined ? ' || :' : ''+ return `${prefix}if [ -r ${q} ]; then sh ${q}${exitZero}; else ${answer}cat >/dev/null 2>&1 || :; fi`}/**