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): codex installs over SSH — the one agent the remote path skipped
enesb05f084ede85
diff --git a/src/core/agents/hooks/codex.test.ts b/src/core/agents/hooks/codex.test.tsnew file mode 100644index 000000000..f852454ad--- /dev/null+++ b/src/core/agents/hooks/codex.test.ts@@ -0,0 +1,81 @@+import { describe, expect, it } from 'vitest'+import { buildCodexHooksAndTrust, buildManagedCommand, CODEX_EVENTS } from './codex'+import { computeTrustedHash } from './codex-trust'++// The command form a codex hook carries: `if [ -x '<script>' ]; then /bin/sh '<script>'; fi`.+// The trust hash is computed over THIS exact byte string, so the hooks.json command and the+// config.toml trust entry must always come from the same builder.+describe('buildManagedCommand', () => {+ it('wraps the script path in the [ -x ] guard with POSIX single-quoting', () => {+ expect(buildManagedCommand('/a/b/codex.sh')).toBe(+ "if [ -x '/a/b/codex.sh' ]; then /bin/sh '/a/b/codex.sh'; fi"+ )+ })+})++describe('buildCodexHooksAndTrust', () => {+ it('returns null for an unparseable (null) hooks.json so the caller never clobbers it', () => {+ expect(buildCodexHooksAndTrust(null, 'cmd', '/h/hooks.json')).toBeNull()+ })++ it('prepends the managed handler to all six events + emits one trust entry per event', () => {+ const command = buildManagedCommand('/home/u/.nodeterm/agent-hooks/codex.sh')+ const built = buildCodexHooksAndTrust({}, command, '/home/u/.codex/hooks.json')+ expect(built).not.toBeNull()+ const { config, trustEntries } = built!+ // one definition per subscribed event, our managed handler first+ for (const ev of CODEX_EVENTS) {+ const defs = config.hooks?.[ev]+ expect(defs?.[0]?.hooks?.[0]?.command).toBe(command)+ }+ expect(trustEntries).toHaveLength(CODEX_EVENTS.length)+ expect(trustEntries.every((e) => e.command === command)).toBe(true)+ expect(trustEntries.every((e) => e.sourcePath === '/home/u/.codex/hooks.json')).toBe(true)+ })++ it('is idempotent — re-running on its own output does not duplicate the managed handler', () => {+ const command = buildManagedCommand('/x/agent-hooks/codex.sh')+ const first = buildCodexHooksAndTrust({}, command, '/x/hooks.json')!+ const second = buildCodexHooksAndTrust(first.config, command, '/x/hooks.json')!+ for (const ev of CODEX_EVENTS) {+ // exactly one managed handler at the head, none trailing+ const defs = second.config.hooks?.[ev] ?? []+ const managed = defs.filter((d) => d.hooks?.some((h) => h.command === command))+ expect(managed).toHaveLength(1)+ }+ })++ it('preserves a user-authored hook in a subscribed event (kept AFTER the managed handler)', () => {+ const command = buildManagedCommand('/x/agent-hooks/codex.sh')+ const userDef = { hooks: [{ type: 'command' as const, command: 'echo mine' }] }+ const built = buildCodexHooksAndTrust({ hooks: { Stop: [userDef] } }, command, '/x/hooks.json')!+ const stop = built.config.hooks?.Stop ?? []+ expect(stop[0]?.hooks?.[0]?.command).toBe(command)+ expect(stop.some((d) => d.hooks?.some((h) => h.command === 'echo mine'))).toBe(true)+ })++ it('sweeps a stale managed handler out of an event we no longer subscribe to', () => {+ const command = buildManagedCommand('/x/agent-hooks/codex.sh')+ // PreCompact is not in CODEX_EVENTS; a stale managed copy there must be removed.+ const stale = { hooks: [{ type: 'command' as const, command }] }+ const built = buildCodexHooksAndTrust({ hooks: { PreCompact: [stale] } }, command, '/x/hooks.json')!+ expect(built.config.hooks?.PreCompact).toBeUndefined()+ })++ // GOLDEN: these six hashes were read from a LIVE codex config.toml on a host where the status+ // hooks fire correctly (codex-cli 0.114.0). Locking them guards the exact JSON canonicalization+ // codex hashes against — any drift here silently breaks every codex status badge.+ it('matches the byte-exact trust hashes codex accepts in the field', () => {+ const command = buildManagedCommand('/root/.nodeterm-server/agent-hooks/codex.sh')+ const built = buildCodexHooksAndTrust({}, command, '/root/.codex/hooks.json')!+ const byLabel = Object.fromEntries(built.trustEntries.map((e) => [e.eventLabel, computeTrustedHash(e)]))+ expect(byLabel).toMatchObject({+ session_start: 'sha256:9ad2be7ba503a6c29d73fe63da7e6e6b90a3418a9367d27e8b79ad67ce4208e6',+ user_prompt_submit: 'sha256:ce3fcb34da617dc3be97142660e0c2ae30c9000333b0bfa29ffde7a941813840',+ pre_tool_use: 'sha256:4518d886ca33ee61eba15a15e6348df03891a37f496a9a29a7eaae8b05623eed',+ permission_request: 'sha256:c15e31e91f0ad513f1dd37bbbf5e1263cb0ba7a819b16dd60bc85f576d5bcb85',+ post_tool_use: 'sha256:ec6d59bff150ef00c30f7ef63abdf3c5a839a12f98ebe5dc542ecdfcc2da9d2f',+ stop: 'sha256:bd559fa7db307ab42dac8fa42b49c46b3daa50f944adad2f0a97140a70c70081'+ })+ })+})diff --git a/src/core/agents/hooks/codex.ts b/src/core/agents/hooks/codex.tsindex 97917dddd..324e3ca2a 100644--- a/src/core/agents/hooks/codex.ts+++ b/src/core/agents/hooks/codex.ts@@ -40,7 +40,7 @@ import {} from './codex-trust'// Confirmed codex event set.-const CODEX_EVENTS = [+export const CODEX_EVENTS = ['SessionStart','UserPromptSubmit','PreToolUse',@@ -53,7 +53,7 @@ const CODEX_EVENTS = [// codex-rs/hooks/src/lib.rs::hook_event_key_label), while hooks.json uses the// PascalCase serde-rename. Map between them in one place so the trust-write// path can't drift from the hooks.json install path.-const CODEX_EVENT_LABEL: Record<(typeof CODEX_EVENTS)[number], CodexEventLabel> = {+export const CODEX_EVENT_LABEL: Record<(typeof CODEX_EVENTS)[number], CodexEventLabel> = {SessionStart: 'session_start',UserPromptSubmit: 'user_prompt_submit',PreToolUse: 'pre_tool_use',@@ -68,7 +68,7 @@ const SCRIPT_FILE_NAME = 'codex.sh'// where each HookDefinition has a `hooks` array of command handlers.type HookCommandConfig = { type: 'command'; command: string; [k: string]: unknown }type HookDefinition = { hooks?: HookCommandConfig[]; [k: string]: unknown }-type HooksConfig = { hooks?: Record<string, HookDefinition[]>; [k: string]: unknown }+export type HooksConfig = { hooks?: Record<string, HookDefinition[]>; [k: string]: unknown }function codexHome(): string {// Default CODEX_HOME. We intentionally write into the user's REAL ~/.codex.@@ -121,12 +121,67 @@ function removeManagedFromDefinitions(defs: HookDefinition[]): HookDefinition[]// makes Codex reject the hook. The POSIX wrapper's// `[ -x ... ]` guard makes a missing/non-executable script a silent no-op so a// broken install never poisons the session with exit-127 noise.-function buildManagedCommand(script: string): string {+export function buildManagedCommand(script: string): string {// POSIX single-quote escape so $, `, ", \ in the path are taken literally.const quoted = `'${script.replaceAll("'", "'\\''")}'`return `if [ -x ${quoted} ]; then /bin/sh ${quoted}; fi`}+// Pure core of the codex install: given the CURRENT parsed hooks.json (or {} for+// a missing file), the managed hook `command`, and the `sourcePath` used to key+// the trust entries (the hooks.json path — canonical/realpath'd form on the host+// that will RUN codex), return the merged hooks.json config plus the trust+// entries whose `trusted_hash` must land in config.toml. Shared by the LOCAL+// installer (fs writes) and the SSH RemoteHooks installer (writes over the+// ControlMaster) so the hooks.json shape and the trust hash can never drift+// between the two paths. Returns null when `existing` is null (unparseable+// hooks.json) — the caller must then leave the file untouched.+export function buildCodexHooksAndTrust(+ existing: HooksConfig | null,+ command: string,+ sourcePath: string+): { config: HooksConfig; trustEntries: CodexTrustEntry[] } | null {+ if (!existing) return null+ const config: HooksConfig = { ...existing }+ const nextHooks: Record<string, HookDefinition[]> = { ...(config.hooks ?? {}) }+ const managedEvents = new Set<string>(CODEX_EVENTS)++ // Sweep managed entries out of events we no longer subscribe to (e.g. left+ // over from an older install) so we don't keep firing stale hooks.+ for (const [eventName, defs] of Object.entries(nextHooks)) {+ if (managedEvents.has(eventName) || !Array.isArray(defs)) {+ continue+ }+ const cleaned = removeManagedFromDefinitions(defs)+ if (cleaned.length === 0) {+ delete nextHooks[eventName]+ } else {+ nextHooks[eventName] = cleaned+ }+ }++ // Prepend our managed handler to each subscribed event (idempotent — strip any+ // prior managed copy first) and record the matching trust entry at+ // groupIndex 0 / handlerIndex 0.+ const trustEntries: CodexTrustEntry[] = []+ for (const eventName of CODEX_EVENTS) {+ const current = Array.isArray(nextHooks[eventName]) ? nextHooks[eventName] : []+ const cleaned = removeManagedFromDefinitions(current)+ const definition: HookDefinition = { hooks: [{ type: 'command', command }] }+ nextHooks[eventName] = [definition, ...cleaned]+ trustEntries.push({+ sourcePath,+ eventLabel: CODEX_EVENT_LABEL[eventName],+ groupIndex: 0,+ handlerIndex: 0,+ command+ })+ }++ config.hooks = nextHooks+ return { config, trustEntries }+}+function readHooksJson(file: string): HooksConfig | null {if (!existsSync(file)) {return {}@@ -208,49 +263,17 @@ export function installCodexHooks(): void {}try {- const nextHooks: Record<string, HookDefinition[]> = { ...(config.hooks ?? {}) }- const managedEvents = new Set<string>(CODEX_EVENTS)-- // Why: sweep managed entries out of events we no longer subscribe to (e.g.- // left over from an older install) so we don't keep firing stale hooks.- for (const [eventName, defs] of Object.entries(nextHooks)) {- if (managedEvents.has(eventName) || !Array.isArray(defs)) {- continue- }- const cleaned = removeManagedFromDefinitions(defs)- if (cleaned.length === 0) {- delete nextHooks[eventName]- } else {- nextHooks[eventName] = cleaned- }- }-- // Why: prepend our managed handler to each subscribed event (idempotent —- // strip any prior managed copy first) and record the matching trust entry- // at groupIndex 0 / handlerIndex 0. Prepending keeps the status hook ahead- // of any user hooks so a slow user hook can't leave the badge stale.- const trustEntries: CodexTrustEntry[] = []- for (const eventName of CODEX_EVENTS) {- const current = Array.isArray(nextHooks[eventName]) ? nextHooks[eventName] : []- const cleaned = removeManagedFromDefinitions(current)- const definition: HookDefinition = { hooks: [{ type: 'command', command }] }- nextHooks[eventName] = [definition, ...cleaned]- trustEntries.push({- sourcePath: hooksFile,- eventLabel: CODEX_EVENT_LABEL[eventName],- groupIndex: 0,- handlerIndex: 0,- command- })- }-- config.hooks = nextHooks- writeHooksJson(hooksFile, config)+ // Prepending keeps the status hook ahead of any user hooks so a slow user+ // hook can't leave the badge stale. The trust entry is keyed by the local+ // hooks.json path (computeTrustKey realpath's it to match how codex keys it).+ const built = buildCodexHooksAndTrust(config, command, hooksFile)+ if (!built) return+ writeHooksJson(hooksFile, built.config)// Why: write trust LAST so a half-write can't leave a hash pointing at a// hook that doesn't exist. upsert does a line-level merge that preserves// all other config.toml content.- upsertHookTrustEntries(configTomlPath(), trustEntries)+ upsertHookTrustEntries(configTomlPath(), built.trustEntries)} catch (e) {console.warn('[agent-hooks] codex install failed', e)}diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.tsindex 89156d332..7804442e4 100644--- a/src/main/remote-ssh/remote-hooks.test.ts+++ b/src/main/remote-ssh/remote-hooks.test.ts@@ -52,6 +52,53 @@ describe('RemoteHooks.setup', () => {expect(joined.some((j) => j.includes('~/'))).toBe(false)})+ it('installs codex too — hooks.json merge PLUS the config.toml trust write', async () => {+ const { rh, calls } = mk()+ const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })+ expect(res).not.toBeNull()+ const joined = calls.map((c) => c.args.join(' '))+ // codex managed script written to the absolute agent-hooks path (paths are posix-quoted).+ expect(joined.some((j) => j.includes("cat > '/home/u/.nodeterm/agent-hooks/codex.sh'"))).toBe(true)+ // hooks.json merged with the [ -x ] guarded command (embedded as JSON in stdin).+ expect(+ calls.some(+ (c) =>+ c.args.join(' ').includes("cat > '/home/u/.codex/hooks.json'") &&+ (c.stdin ?? '').includes("if [ -x '/home/u/.nodeterm/agent-hooks/codex.sh' ]")+ )+ ).toBe(true)+ // the part claude/gemini don't need: a config.toml trust block with a trusted_hash.+ expect(+ calls.some(+ (c) =>+ c.args.join(' ').includes("cat > '/home/u/.codex/config.toml'") &&+ (c.stdin ?? '').includes('[hooks.state.') &&+ (c.stdin ?? '').includes('trusted_hash = "sha256:')+ )+ ).toBe(true)+ // no unexpanded tilde anywhere in the codex path work either.+ expect(joined.some((j) => j.includes('~/'))).toBe(false)+ })++ it('leaves a malformed remote codex hooks.json untouched (never clobbers it)', async () => {+ const calls: { args: string[]; stdin?: string }[] = []+ const run = vi.fn(async (args: string[], stdin?: string) => {+ calls.push({ args, stdin })+ const joined = args.join(' ')+ if (joined.includes('$HOME')) return { code: 0, stdout: '/home/u' }+ if (joined.includes('%{http_code}')) return { code: 0, stdout: '204' }+ // present-but-broken hooks.json (the `|| echo '{}'` only fires when the file is MISSING).+ if (joined.includes("cat '/home/u/.codex/hooks.json'")) return { code: 0, stdout: '{ not json' }+ return { code: 0, stdout: '' }+ })+ await new RemoteHooks({ run }).setup('p1', conn, '/s.sock', { port: 1, token: 't', version: '1' })+ const joined = calls.map((c) => c.args.join(' '))+ // the script is still (idempotently) written, but neither hooks.json nor config.toml is rewritten.+ expect(joined.some((j) => j.includes("cat > '/home/u/.nodeterm/agent-hooks/codex.sh'"))).toBe(true)+ expect(joined.some((j) => j.includes("cat > '/home/u/.codex/hooks.json'"))).toBe(false)+ expect(joined.some((j) => j.includes("cat > '/home/u/.codex/config.toml'"))).toBe(false)+ })+it('verifies the tunnel end-to-end and heals a stale forward with one rebind', async () => {// First verify sees a dead target (a reused live-orphan master serving a previous run's// forward — the field case that killed remote statuses for hours); the rebind fixes it.diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.tsindex f2b45fa80..ee85ab99e 100644--- a/src/main/remote-ssh/remote-hooks.ts+++ b/src/main/remote-ssh/remote-hooks.ts@@ -1,12 +1,18 @@// Connection-time remote hook setup for SSH projects: opens the reverse unix-socket tunnel// (local loopback hook server → remote socket), writes the owner-only remote endpoint file,-// and installs the managed hook into the remote agent configs (claude + gemini in Phase 2a;-// codex deferred). Every step fails open: any remote failure → setup returns null and the-// agent simply runs without hooks. Takes an INJECTED runner so the flow is unit-testable-// without real ssh/electron.+// and installs the managed hook into the remote agent configs (claude + gemini JSON settings,+// plus codex's hooks.json + config.toml trust). Every step fails open: any remote failure →+// 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 { buildManagedScript } from '../../core/agents/hooks/managed-script'import { mergeManagedHook, type HookSettings } from '../../core/agents/hooks/install-helper'+import {+ buildCodexHooksAndTrust,+ buildManagedCommand as buildCodexManagedCommand,+ type HooksConfig as CodexHooksConfig+} from '../../core/agents/hooks/codex'+import { upsertHookTrustEntriesInContent } from '../../core/agents/hooks/codex-trust'import { ensureFullscreenTui, type TuiSettings } from '../../core/agents/hooks/claude-tui'import {CONTROL_SHIM_SCRIPT,@@ -34,7 +40,9 @@ export interface RemoteRunner {run: (args: string[], stdin?: string) => Promise<{ code: number; stdout: string }>}-// Per-agent remote install targets (JSON-config agents only in Phase 2a; codex deferred).+// Per-agent remote install targets (JSON-settings agents merged via mergeManagedHook). Codex+// is installed separately (installCodexRemote) because it needs a hooks.json merge PLUS a+// config.toml trust write — see that method.// 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).@@ -138,12 +146,103 @@ export class RemoteHooks {JSON.stringify(merged, null, 2))}+ // 4. codex: hooks.json merge + config.toml trust (its own shape — not a JSON-settings agent).+ await this.installCodexRemote(conn, controlPath, home, remoteDir)return { endpointPath: endpoint }} catch {return null // fail-open: agent runs without hooks}}+ /**+ * Install the managed codex status hook on the REMOTE host: write `codex.sh`, merge our handler+ * into `~/.codex/hooks.json`, and — the part that makes codex different from claude/gemini — write+ * the matching TRUST entries into `~/.codex/config.toml`. Codex will NOT run a hook whose+ * `[hooks.state."<key>"].trusted_hash` doesn't equal its own hash of the hook definition, so the+ * hooks.json merge alone (the desktop's local `codex.ts` learned this) leaves a remote codex+ * session dark. This mirrors that local flow over the ControlMaster.+ *+ * The trust hash is computed over the EXACT `command` string (which embeds the remote script+ * path), so the command written into hooks.json and the command hashed into config.toml MUST be+ * the same bytes — both come from `buildCodexManagedCommand(script)`. The trust KEY is keyed by+ * the hooks.json path as codex canonicalizes it (`key_source` → realpath), so we resolve the+ * remote path with `readlink -f` ON THE HOST rather than realpath'ing it against the desktop fs+ * (which would resolve the wrong machine's symlinks, or fall back to a path codex never uses).+ *+ * Fail-open at every step; an unparseable remote hooks.json is left untouched (never clobbered).+ */+ private async installCodexRemote(+ conn: SshConnection,+ controlPath: string,+ home: string,+ remoteDir: string+ ): Promise<void> {+ try {+ const script = `${remoteDir}/agent-hooks/codex.sh`+ await this.r.run(+ childArgs(+ conn,+ controlPath,+ `mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`+ ),+ buildManagedScript('codex')+ )+ const command = buildCodexManagedCommand(script)+ const codexHome = `${home}/.codex`+ const hooksFile = `${codexHome}/hooks.json`+ const configToml = `${codexHome}/config.toml`++ // Resolve the canonical remote hooks.json path (codex realpath's key_source before keying the+ // trust entry). Falls back to the plain path when readlink can't resolve it yet.+ const { stdout: canonRaw } = await this.r.run(+ childArgs(+ conn,+ controlPath,+ `mkdir -p ${posixQuote(codexHome)}; readlink -f ${posixQuote(hooksFile)} 2>/dev/null || printf %s ${posixQuote(hooksFile)}`+ )+ )+ const sourcePath = canonRaw.trim() || hooksFile++ // Read the current hooks.json. `|| echo '{}'` only fires when the file is MISSING, so a+ // present-but-malformed file reaches JSON.parse and throws → we skip (never clobber it).+ const { stdout: hooksRaw } = await this.r.run(+ childArgs(conn, controlPath, `cat ${posixQuote(hooksFile)} 2>/dev/null || echo '{}'`)+ )+ let existing: CodexHooksConfig | null+ try {+ const parsed = JSON.parse(hooksRaw || '{}') as unknown+ existing =+ parsed && typeof parsed === 'object' && !Array.isArray(parsed)+ ? (parsed as CodexHooksConfig)+ : null+ } catch {+ existing = null+ }+ const built = buildCodexHooksAndTrust(existing, command, sourcePath)+ if (!built) return // missing is fine ({}); unparseable/odd shape → leave the host's file alone++ await this.r.run(+ childArgs(conn, controlPath, `mkdir -p ${posixQuote(codexHome)} && cat > ${posixQuote(hooksFile)}`),+ `${JSON.stringify(built.config, null, 2)}\n`+ )++ // Trust LAST: read config.toml, line-merge our trust blocks (preserving all other content),+ // write back only if it changed. `|| true` so a missing config.toml reads as empty.+ const { stdout: tomlRaw } = await this.r.run(+ childArgs(conn, controlPath, `cat ${posixQuote(configToml)} 2>/dev/null || true`)+ )+ const nextToml = upsertHookTrustEntriesInContent(tomlRaw, built.trustEntries)+ if (nextToml !== tomlRaw) {+ await this.r.run(+ childArgs(conn, controlPath, `mkdir -p ${posixQuote(codexHome)} && cat > ${posixQuote(configToml)}`),+ nextToml+ )+ }+ } catch {+ /* fail-open: the remote codex session simply runs without status hooks */+ }+ }+/*** Merge the managed claude hook into a REMOTE managed-account config dir's `settings.json`, so an* agent that runs under `CLAUDE_CONFIG_DIR=<accountDir>` reports status like the default