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
perf(ssh): run the per-agent remote hook installs concurrently
enes978ffe550acd
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8e2e3feee..aa2aa7d41 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1669,6 +1669,30 @@ else, and its context links must keep classifying across restarts).the validator refuses) settles at one attempt per 15 minutes instead of rewriting every agent'shook config every 45 s. A missing spec answers "not alive" rather than "unknown": nothing of oursis bound, which is a tunnel that cannot deliver.+- **The per-agent hook installs run CONCURRENTLY, and the order that still matters is the one above+ them.** `RemoteHooks.setup()` is the chain `connectOnce` awaits before a project reports+ `connected`, so every terminal of a switched-to project waits through it. Its shape was: resolve+ `$HOME`, open + VERIFY the reverse tunnel, write the endpoint file — and then install five agents'+ hooks strictly one after another, ~16 more remote round trips in a row. MEASURED against a real+ sshd through a 25 ms one-way delay proxy (50 ms RTT), 5 runs each: **3281 ms serial → 1471 ms+ concurrent** over the same 22–24 ssh children. The installers are independent by construction —+ each writes its own script under `<remoteDir>/agent-hooks/` and merges its own agent's config; no+ two touch the same remote path, and the only shared statement is an idempotent `mkdir -p` — and+ the `SshChildGate` (cap 6 per ControlMaster) is what makes the fan-out safe against a stock host's+ `MaxSessions`, which is the whole reason it exists.+ - **The tunnel and the endpoint file stay strictly BEFORE the fan-out**: that file is what every+ hook this installs POSTs through, and it is written only once the tunnel has verified end to+ end. `remote-hooks.test.ts` pins that ordering AND the overlap (a gated fake runner, so+ concurrency is observed rather than inferred from wall-clock; the overlap test fails on the+ serial version, checked by mutation).+ - **`allSettled`, not `all`.** By the fan-out the tunnel is verified and the endpoint written, so+ one installer failing must cost that agent its hooks and nothing else — not discard a working+ setup for every other agent, which is what a rejection propagating to `setup`'s outer catch+ would do (`return null` ⇒ no hooks at all, and post-#735 a repair retried on backoff forever).+ Every installer catches its own errors today; this is the guard for the next one that forgets.+ - The claude/gemini loop body became `installJsonAgentRemote`, with the same fail-open try/catch+ its three siblings already had. Its three steps stay strictly ordered inside: the merge reads+ the file the write then replaces.- **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/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.tsindex 53bcb253c..802183d7b 100644--- a/src/main/remote-ssh/remote-hooks.test.ts+++ b/src/main/remote-ssh/remote-hooks.test.ts@@ -890,3 +890,94 @@ describe('RemoteHooks.setup — the host $HOME is data, not truth', () => {expect(joined.some((j) => j.includes(`cat > '/home/gökhan/.claude/settings.json'`))).toBe(true)})})++// ── The per-agent installs run CONCURRENTLY, and the order that still matters ────────────────+//+// Serially these were ~16 remote round trips in a row — 3.54 s on a 50 ms-RTT link, measured+// against a real sshd — and every terminal of a switched-to project waits through them, because+// `connectOnce` does not publish the master until this returns. What must NOT be parallelized with+// them is the tunnel and the endpoint file: that file is what every installed hook POSTs through.+describe('RemoteHooks.setup — install concurrency', () => {+ /** A harness whose `run` blocks each matching command until the test releases it, so overlap is+ * observable rather than inferred from wall-clock. */+ function gatedHarness(gateOn: string) {+ const calls: string[] = []+ const inFlight = new Set<string>()+ let peak = 0+ const gates: (() => void)[] = []+ const run = vi.fn(async (args: string[]) => {+ const joined = args.join(' ')+ calls.push(joined)+ if (joined.includes(gateOn)) {+ inFlight.add(joined)+ peak = Math.max(peak, inFlight.size)+ await new Promise<void>((resolve) => gates.push(resolve))+ inFlight.delete(joined)+ }+ if (joined.includes('$HOME')) return { code: 0, stdout: '/home/u' }+ if (joined.includes('%{http_code}')) return { code: 0, stdout: '204' }+ return { code: 0, stdout: '' }+ })+ return {+ rh: new RemoteHooks({ run }),+ calls,+ releaseAll: () => {+ for (const g of gates.splice(0)) g()+ },+ gateCount: () => gates.length,+ peak: () => peak+ }+ }++ it('starts every agent script write together instead of one at a time', async () => {+ // The script write is the FIRST round trip of each per-agent installer, so several of them in+ // flight at once is exactly "the installers overlap". Serially this number is 1.+ const h = gatedHarness('agent-hooks')+ const done = h.rh.setup('p1', conn, '/s.sock', { port: 1, token: 't', version: '1' })+ // Let the pre-install steps (HOME, tunnel, endpoint) settle and the fan-out start.+ for (let i = 0; i < 50 && h.gateCount() < 2; i++) await Promise.resolve()+ expect(h.peak()).toBeGreaterThan(1)+ h.releaseAll()+ // The installers each take a few more gated round trips; release until the setup lands.+ for (let i = 0; i < 40; i++) {+ await Promise.resolve()+ h.releaseAll()+ }+ await expect(done).resolves.toEqual({ endpointPath: '/home/u/.nodeterm/hook-endpoint-p1.env' })+ })++ it('the TUNNEL and the ENDPOINT FILE are both complete before any agent install starts', async () => {+ // The ordering rule the fan-out must not swallow: every hook this installs POSTs through the+ // endpoint file, and the endpoint is only written once the tunnel has verified end to end.+ const { rh, calls } = harness()+ await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })+ const joined = calls.map((c) => c.args.join(' '))+ const firstInstall = joined.findIndex((j) => j.includes('agent-hooks'))+ const forward = joined.findIndex((j) => j.includes('-O forward'))+ const verify = joined.findIndex((j) => j.includes('%{http_code}'))+ const endpoint = calls.findIndex((c) => (c.stdin ?? '').includes("NODETERM_HOOK_TOKEN='tok'"))+ expect(firstInstall).toBeGreaterThan(-1)+ expect(forward).toBeGreaterThan(-1)+ expect(verify).toBeGreaterThan(forward)+ expect(endpoint).toBeGreaterThan(verify)+ expect(firstInstall).toBeGreaterThan(endpoint)+ })++ it('one agent failing does not discard the endpoint the others are installed against', async () => {+ // `allSettled`, not `all`: by this point the tunnel is verified and the endpoint written, so a+ // single installer's failure must cost that agent its hooks and nothing else. (Every installer+ // catches its own errors today — this is the guard for the next one that forgets.)+ const { rh } = harness({ failOn: '.grok' })+ const res = await rh.setup('p1', conn, '/s.sock', { port: 1, token: 't', version: '1' })+ expect(res?.endpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')+ })++ it('still installs every agent — claude, gemini, codex, grok and copilot', async () => {+ const { rh, calls } = harness()+ await rh.setup('p1', conn, '/s.sock', { port: 1, token: 't', version: '1' })+ const joined = calls.map((c) => c.args.join(' '))+ for (const agent of ['claude', 'gemini', 'codex', 'grok', 'copilot']) {+ expect(joined.some((j) => j.includes(`agent-hooks/${agent}.sh`))).toBe(true)+ }+ })+})diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.tsindex 1163794ff..bd064d53c 100644--- a/src/main/remote-ssh/remote-hooks.ts+++ b/src/main/remote-ssh/remote-hooks.ts@@ -216,42 +216,37 @@ export class RemoteHooks {remoteEndpointFileContents(sock, hook.token, hook.version, `${remoteDir}/node-tokens`))if (endpointResult.code !== 0) return null- // 3. install the managed hook for each JSON agent (script + merged config).- for (const t of AGENT_TARGETS) {- const script = `${remoteDir}/agent-hooks/${t.agentId}.sh`- const config = `${home}/${t.config}`- await this.r.run(- childArgs(- conn,- controlPath,- `mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`- ),- buildManagedScript(t.agentId, REMOTE_IDENTITY_ROOT)- )- const { stdout: cfgRaw } = await this.r.run(- childArgs(conn, controlPath, `cat ${posixQuote(config)} 2>/dev/null || echo '{}'`)- )- let cfg: HookSettings = {}- try {- cfg = JSON.parse(cfgRaw || '{}') as HookSettings- } catch {- cfg = {}+ // 3-6. Per-agent hook installs — CONCURRENT, because they are independent of each other.+ //+ // Each one writes its own script under `<remoteDir>/agent-hooks/` and merges its own agent's+ // config file; no two touch the same remote path, and the only shared statement is an+ // idempotent `mkdir -p` of that one directory. Run serially they were ~16 remote round trips+ // in a row — MEASURED at 3.54 s on a 50 ms-RTT link, which is wall-clock every terminal of a+ // switched-to project used to wait through (the master is not published until `connected`;+ // see `connectOnce`). The `SshChildGate` (cap 6 per ControlMaster) is what makes the fan-out+ // safe against a stock host's `MaxSessions`, and is the whole reason it exists.+ //+ // ORDER IS STILL LOAD-BEARING ABOVE THIS LINE: the tunnel must be verified and the endpoint+ // file written first, because that file is what every one of these hooks POSTs through.+ //+ // `allSettled`, not `all`: the endpoint is already written and the tunnel already verified by+ // the time we get here, so ONE agent's installer failing must not discard a working setup for+ // every other agent. Each installer already catches its own errors, so today nothing rejects —+ // this is the guard for the next one that forgets to.+ const installs = await Promise.allSettled([+ ...AGENT_TARGETS.map((t) => this.installJsonAgentRemote(conn, controlPath, home, remoteDir, t)),+ // codex: hooks.json merge + config.toml trust (its own shape — not a JSON-settings agent).+ this.installCodexRemote(conn, controlPath, home, remoteDir),+ // grok: our own file in its hooks DIRECTORY, under the HOST's $GROK_HOME.+ this.installGrokRemote(conn, controlPath, home, remoteDir),+ // copilot: its own file/grammar under the HOST's $COPILOT_HOME hooks directory.+ this.installCopilotRemote(conn, controlPath, home, remoteDir)+ ])+ for (const r of installs) {+ if (r.status === 'rejected') {+ console.warn('[remote-hooks] one agent hook install failed; the others are installed', r.reason)}- const merged = mergeManagedHook(cfg, buildManagedHookCommand(script), t.events)- await this.r.run(- // `$(dirname …)` is itself QUOTED (same reason as installGrokRemote): a home with a- // space would otherwise word-split into two mkdir args, the directory would never be- // created, and the correctly-quoted `cat >` would then fail — silently, fail-open.- childArgs(conn, controlPath, `mkdir -p "$(dirname ${posixQuote(config)})" && cat > ${posixQuote(config)}`),- 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)- // 5. grok: our own file in its hooks DIRECTORY, under the HOST's $GROK_HOME.- await this.installGrokRemote(conn, controlPath, home, remoteDir)- // 6. copilot: its own file/grammar under the HOST's $COPILOT_HOME hooks directory.- await this.installCopilotRemote(conn, controlPath, home, remoteDir)return { endpointPath: endpoint }} catch {return null // fail-open: agent runs without hooks@@ -387,6 +382,55 @@ export class RemoteHooks {** Fail-open at every step; an unparseable remote hooks.json is left untouched (never clobbered).*/+ /**+ * Install the managed hook for ONE json-settings agent (claude, gemini): write its script, read+ * its settings file, merge our handler in, write it back.+ *+ * Extracted from `setup`'s loop so the four per-agent installs can run concurrently, and given+ * the same fail-open try/catch its three siblings already have — a per-agent failure must cost+ * that agent its status hooks and nothing else. The three steps INSIDE stay strictly ordered:+ * the merge reads the file the write then replaces.+ */+ private async installJsonAgentRemote(+ conn: SshConnection,+ controlPath: string,+ home: string,+ remoteDir: string,+ target: { agentId: string; config: string; events: readonly string[] }+ ): Promise<void> {+ try {+ const script = `${remoteDir}/agent-hooks/${target.agentId}.sh`+ const config = `${home}/${target.config}`+ await this.r.run(+ childArgs(+ conn,+ controlPath,+ `mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`+ ),+ buildManagedScript(target.agentId, REMOTE_IDENTITY_ROOT)+ )+ const { stdout: cfgRaw } = await this.r.run(+ childArgs(conn, controlPath, `cat ${posixQuote(config)} 2>/dev/null || echo '{}'`)+ )+ let cfg: HookSettings = {}+ try {+ cfg = JSON.parse(cfgRaw || '{}') as HookSettings+ } catch {+ cfg = {}+ }+ const merged = mergeManagedHook(cfg, buildManagedHookCommand(script), target.events)+ await this.r.run(+ // `$(dirname …)` is itself QUOTED (same reason as installGrokRemote): a home with a+ // space would otherwise word-split into two mkdir args, the directory would never be+ // created, and the correctly-quoted `cat >` would then fail — silently, fail-open.+ childArgs(conn, controlPath, `mkdir -p "$(dirname ${posixQuote(config)})" && cat > ${posixQuote(config)}`),+ JSON.stringify(merged, null, 2)+ )+ } catch {+ /* fail-open: this agent's remote sessions run without status hooks */+ }+ }+private async installCodexRemote(conn: SshConnection,controlPath: string,