Skip to content

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.

feat(ssh-p2a): remote-hooks — reverse tunnel + remote endpoint + remote hook install

enesc22b9a5c6727
diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.ts
new file mode 100644
index 000000000..c110fe18d
--- /dev/null
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it, vi } from 'vitest'
+import { RemoteHooks } from './remote-hooks'
+
+const conn = { host: 'h', user: 'u' }
+
+function mk() {
+ const calls: { args: string[]; stdin?: string }[] = []
+ const run = vi.fn(async (args: string[], stdin?: string) => {
+ calls.push({ args, stdin })
+ if (args.join(' ').includes('cat ~/.claude/settings.json')) return { code: 0, stdout: '{}' }
+ return { code: 0, stdout: '' }
+ })
+ return { rh: new RemoteHooks({ run }), calls, run }
+}
+
+describe('RemoteHooks.setup', () => {
+ it('opens a reverse forward, writes the endpoint file, and installs the managed hook for claude', async () => {
+ const { rh, calls } = mk()
+ const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })
+ expect(res?.endpointPath).toMatch(/hook-endpoint\.env$/)
+ const joined = calls.map((c) => c.args.join(' '))
+ expect(joined.some((j) => j.includes('-O forward') && j.includes('127.0.0.1:51234'))).toBe(true)
+ // endpoint file written via stdin redirect
+ expect(calls.some((c) => (c.stdin ?? '').includes('NODETERM_HOOK_TOKEN=tok'))).toBe(true)
+ // managed script written + config merged + written back
+ expect(calls.some((c) => (c.stdin ?? '').includes('--unix-socket'))).toBe(true)
+ expect(calls.some((c) => (c.stdin ?? '').includes('"hooks"'))).toBe(true)
+ })
+})
+
+describe('RemoteHooks.teardown', () => {
+ it('cancels the reverse forward', async () => {
+ const { rh, run } = mk()
+ await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 't', version: '1' })
+ run.mockClear()
+ await rh.teardown('p1', conn, '/s.sock')
+ expect(run.mock.calls.some(([a]) => a.join(' ').includes('-O cancel'))).toBe(true)
+ })
+})
diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.ts
new file mode 100644
index 000000000..3fb493716
--- /dev/null
+++ b/src/main/remote-ssh/remote-hooks.ts
@@ -0,0 +1,95 @@
+// 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.
+import { childArgs, hookForwardArgs, hookForwardCancelArgs, remoteEndpointFileContents } from './control-master'
+import { buildManagedScript } from '../agents/hooks/managed-script'
+import { mergeManagedHook, type HookSettings } from '../agents/hooks/install-helper'
+import type { SshConnection } from '../../shared/ssh'
+
+export interface RemoteRunner {
+ /** Run one ssh child command (over the master); optional stdin written to the child. */
+ run: (args: string[], stdin?: string) => Promise<{ code: number; stdout: string }>
+}
+
+// Per-agent remote install targets (JSON-config agents only in Phase 2a; codex deferred).
+const REMOTE_DIR = '~/.nodeterm'
+const AGENT_TARGETS: { agentId: string; config: string; script: string; events: string[] }[] = [
+ {
+ agentId: 'claude',
+ config: '~/.claude/settings.json',
+ script: `${REMOTE_DIR}/agent-hooks/claude.sh`,
+ events: ['Stop', 'Notification', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'SessionStart', 'SessionEnd', 'SubagentStop']
+ },
+ {
+ agentId: 'gemini',
+ config: '~/.gemini/settings.json',
+ script: `${REMOTE_DIR}/agent-hooks/gemini.sh`,
+ events: ['Stop', 'Notification', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse']
+ }
+]
+
+const REMOTE_SOCK = (projectId: string): string => `${REMOTE_DIR}/hook-${projectId}.sock`
+const REMOTE_ENDPOINT = `${REMOTE_DIR}/hook-endpoint.env`
+
+export class RemoteHooks {
+ // Remember the hook port used at setup per project so teardown cancels the exact `-R` spec.
+ private ports = new Map<string, number>()
+
+ constructor(private r: RemoteRunner) {}
+
+ async setup(
+ projectId: string,
+ conn: SshConnection,
+ controlPath: string,
+ hook: { port: number; token: string; version: string }
+ ): Promise<{ endpointPath: string } | null> {
+ if (!hook.port || !hook.token) return null
+ const sock = REMOTE_SOCK(projectId)
+ try {
+ // 1. reverse unix-socket forward (stale socket → remove first so -R can bind).
+ await this.r.run(childArgs(conn, controlPath, `mkdir -p ${REMOTE_DIR} && rm -f ${sock}`))
+ await this.r.run(hookForwardArgs(conn, controlPath, sock, hook.port))
+ this.ports.set(projectId, hook.port)
+ // 2. remote endpoint file (0600 via umask).
+ await this.r.run(
+ childArgs(conn, controlPath, `umask 077; cat > ${REMOTE_ENDPOINT}`),
+ remoteEndpointFileContents(sock, hook.token, hook.version)
+ )
+ // 3. install the managed hook for each JSON agent (script + merged config).
+ for (const t of AGENT_TARGETS) {
+ await this.r.run(
+ childArgs(conn, controlPath, `mkdir -p ${REMOTE_DIR}/agent-hooks && cat > ${t.script} && chmod 755 ${t.script}`),
+ buildManagedScript(t.agentId)
+ )
+ const { stdout } = await this.r.run(childArgs(conn, controlPath, `cat ${t.config} 2>/dev/null || echo '{}'`))
+ let cfg: HookSettings = {}
+ try {
+ cfg = JSON.parse(stdout || '{}') as HookSettings
+ } catch {
+ cfg = {}
+ }
+ const merged = mergeManagedHook(cfg, `sh "${t.script}"`, t.events)
+ await this.r.run(
+ childArgs(conn, controlPath, `mkdir -p $(dirname ${t.config}) && cat > ${t.config}`),
+ JSON.stringify(merged, null, 2)
+ )
+ }
+ return { endpointPath: REMOTE_ENDPOINT }
+ } catch {
+ return null // fail-open: agent runs without hooks
+ }
+ }
+
+ async teardown(projectId: string, conn: SshConnection, controlPath: string): Promise<void> {
+ const port = this.ports.get(projectId) ?? 0
+ this.ports.delete(projectId)
+ try {
+ await this.r.run(hookForwardCancelArgs(conn, controlPath, REMOTE_SOCK(projectId), port))
+ } catch {
+ /* fail open */
+ }
+ }
+}
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index 6d8685bb3..e479593cc 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -7,11 +7,12 @@ function makeMgr() {
const statuses: string[] = []
// spawnMaster: returns a fake child that "stays up"; run: resolves stdout for one-shot ssh.
const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn() }))
- const run = vi.fn(async (_args: string[]) => ({ code: 0, stdout: 'src/\nbin/\n' }))
+ const run = vi.fn(async (_args: string[], _stdin?: string) => ({ code: 0, stdout: 'src/\nbin/\n' }))
const mgr = new SshProjectManager({
userDataDir: '/ud',
spawnMaster,
run,
+ getHook: () => ({ port: 51234, token: 'tok', version: '1' }),
onStatus: (e) => statuses.push(e.status)
})
return { mgr, statuses, spawnMaster, run }
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 590e16899..a16421dcb 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -13,14 +13,18 @@ import {
checkMasterArgs,
remoteTmuxKillArgs
} from './control-master'
+import { RemoteHooks } from './remote-hooks'
+import { hookServer } from '../agents/hook-server'
import { sessionName } from '../tmux-naming'
interface Runners {
userDataDir: string
/** Spawn the long-lived master; returns a handle we can kill. */
spawnMaster: (args: string[]) => { kill: () => void; on: (ev: string, cb: (...a: unknown[]) => void) => void }
- /** Run a one-shot ssh, resolving its stdout + exit code. */
- run: (args: string[]) => Promise<{ code: number; stdout: string }>
+ /** Run a one-shot ssh, resolving its stdout + exit code; optional stdin written to the child. */
+ run: (args: string[], stdin?: string) => Promise<{ code: number; stdout: string }>
+ /** Live loopback hook-server coordinates (injected so the manager stays testable). */
+ getHook: () => { port: number; token: string; version: string }
onStatus: (e: { projectId: string; status: SshProjectStatus; error?: string }) => void
}
@@ -28,6 +32,7 @@ interface Conn {
conn: SshConnection
controlPath: string
master: ReturnType<Runners['spawnMaster']>
+ hookEndpointPath?: string
}
/**
@@ -62,16 +67,22 @@ function sshBin(): string {
export class SshProjectManager {
private conns = new Map<string, Conn>()
- constructor(private r: Runners) {}
+ private remoteHooks: RemoteHooks
+ constructor(private r: Runners) {
+ this.remoteHooks = new RemoteHooks({ run: r.run })
+ }
- async connect(projectId: string, conn: SshConnection): Promise<{ controlPath: string }> {
+ async connect(
+ projectId: string,
+ conn: SshConnection
+ ): Promise<{ controlPath: string; hookEndpointPath?: string }> {
const existing = this.conns.get(projectId)
if (existing) {
// Verify the cached master is still alive before reusing it — a dropped/timed-out master
// would otherwise leave us reusing a dead socket. If `-O check` fails, surface
// `reconnecting`, drop the stale entry, and fall through to re-establish.
const { code } = await this.r.run(checkMasterArgs(existing.conn, existing.controlPath))
- if (code === 0) return { controlPath: existing.controlPath }
+ if (code === 0) return { controlPath: existing.controlPath, hookEndpointPath: existing.hookEndpointPath }
this.r.onStatus({ projectId, status: 'reconnecting' })
existing.master.kill()
this.conns.delete(projectId)
@@ -91,12 +102,18 @@ export class SshProjectManager {
for (let i = 0; i < 50; i++) {
const { code } = await this.r.run(checkMasterArgs(conn, controlPath))
if (code === 0) {
+ // Master is up. Best-effort remote hook setup (reverse tunnel + endpoint + install);
+ // fail-open — a null result just means the remote agents run without hooks.
+ const res = await this.remoteHooks.setup(projectId, conn, controlPath, this.r.getHook())
+ const hookEndpointPath = res?.endpointPath
+ const entry = this.conns.get(projectId)
+ if (entry) entry.hookEndpointPath = hookEndpointPath
this.r.onStatus({ projectId, status: 'connected' })
- return { controlPath }
+ return { controlPath, hookEndpointPath }
}
await new Promise((res) => setTimeout(res, 100))
}
- this.disconnect(projectId)
+ await this.disconnect(projectId)
this.r.onStatus({ projectId, status: 'error', error: 'Could not establish the SSH connection.' })
throw new Error('Could not establish the SSH connection.')
}
@@ -128,9 +145,11 @@ export class SshProjectManager {
)
}
- disconnect(projectId: string): void {
+ async disconnect(projectId: string): Promise<void> {
const c = this.conns.get(projectId)
if (!c) return
+ // Cancel the reverse hook tunnel (over the still-live master) BEFORE tearing the master down.
+ await this.remoteHooks.teardown(projectId, c.conn, c.controlPath)
void this.r.run(exitMasterArgs(c.conn, c.controlPath))
c.master.kill()
this.conns.delete(projectId)
@@ -139,7 +158,7 @@ export class SshProjectManager {
/** Tear down every live master (on app quit) so no `-N` master ssh child is orphaned. */
disconnectAll(): void {
- for (const projectId of [...this.conns.keys()]) this.disconnect(projectId)
+ for (const projectId of [...this.conns.keys()]) void this.disconnect(projectId)
}
}
@@ -148,12 +167,16 @@ export function initSshProject(win: BrowserWindow): SshProjectManager {
const mgr = new SshProjectManager({
userDataDir: app.getPath('userData'),
spawnMaster: (args) => spawn(ssh, args, { stdio: 'ignore' }),
- run: (args) =>
- new Promise((resolve) =>
- execFile(ssh, args, { timeout: 15000 }, (err, stdout) =>
+ run: (args, stdin) =>
+ new Promise((resolve) => {
+ const child = execFile(ssh, args, { timeout: 15000 }, (err, stdout) =>
resolve({ code: err ? ((err as { code?: number }).code ?? 1) : 0, stdout: stdout ?? '' })
)
- ),
+ if (stdin !== undefined) {
+ child.stdin?.end(stdin)
+ }
+ }),
+ getHook: () => ({ port: hookServer.getPort(), token: hookServer.getToken(), version: hookServer.getVersion() }),
onStatus: (e) => {
if (!win.isDestroyed()) win.webContents.send(IPC.sshProjectStatus, e)
}