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): pure hook-forward/env builders + unix-socket script branch + pure merge + getters

enescc00b9bed6c4
diff --git a/src/main/agents/hook-server.ts b/src/main/agents/hook-server.ts
index ab942ea2d..cfcbdb344 100644
--- a/src/main/agents/hook-server.ts
+++ b/src/main/agents/hook-server.ts
@@ -45,6 +45,16 @@ class HookServer {
return this.endpointPath
}
+ getPort(): number {
+ return this.port
+ }
+ getToken(): string {
+ return this.token
+ }
+ getVersion(): string {
+ return NODETERM_HOOK_PROTOCOL_VERSION
+ }
+
setListener(cb: (e: NormalizedAgentEvent) => void): void {
this.listener = cb
}
diff --git a/src/main/agents/hooks/install-helper.test.ts b/src/main/agents/hooks/install-helper.test.ts
new file mode 100644
index 000000000..af3a7f7bc
--- /dev/null
+++ b/src/main/agents/hooks/install-helper.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest'
+import { mergeManagedHook } from './install-helper'
+
+const cmd = 'sh "/remote/.nodeterm/agent-hooks/claude.sh"'
+
+describe('mergeManagedHook', () => {
+ it('adds the managed command to each event, preserving other tools hooks', () => {
+ const out = mergeManagedHook({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'other' }] }] } }, cmd, ['Stop'])
+ expect(out.hooks!.Stop).toEqual([
+ { hooks: [{ type: 'command', command: 'other' }] },
+ { hooks: [{ type: 'command', command: cmd }] }
+ ])
+ })
+ it('is idempotent — re-merging drops the prior managed entry (agent-hooks marker)', () => {
+ const once = mergeManagedHook({}, cmd, ['Stop'])
+ const twice = mergeManagedHook(once, cmd, ['Stop'])
+ expect(twice.hooks!.Stop).toEqual([{ hooks: [{ type: 'command', command: cmd }] }])
+ })
+ it('drops a legacy claude-signals managed entry too', () => {
+ const out = mergeManagedHook(
+ { hooks: { Stop: [{ hooks: [{ type: 'command', command: 'sh /x/claude-signals.sh' }] }] } },
+ cmd,
+ ['Stop']
+ )
+ expect(out.hooks!.Stop).toEqual([{ hooks: [{ type: 'command', command: cmd }] }])
+ })
+})
diff --git a/src/main/agents/hooks/install-helper.ts b/src/main/agents/hooks/install-helper.ts
index a3d031577..8630a28ae 100644
--- a/src/main/agents/hooks/install-helper.ts
+++ b/src/main/agents/hooks/install-helper.ts
@@ -17,6 +17,9 @@ import { buildManagedScript } from './managed-script'
type HookDef = { hooks?: { type: string; command: string }[] }
type Settings = { hooks?: Record<string, HookDef[]>; [k: string]: unknown }
+/** Public alias for the hook settings shape, shared by local + remote merge callers. */
+export type HookSettings = Settings
+
function scriptPathFor(scriptFileName: string): string {
return path.join(app.getPath('userData'), 'agent-hooks', scriptFileName)
}
@@ -28,6 +31,17 @@ function isManaged(d: HookDef): boolean {
)
}
+/** Pure: merge the managed `command` into each event, dropping any prior managed entry. */
+export function mergeManagedHook(config: HookSettings, command: string, events: readonly string[]): HookSettings {
+ const next: HookSettings = { ...config, hooks: { ...(config.hooks ?? {}) } }
+ for (const ev of events) {
+ const existing = (next.hooks![ev] ?? []).filter((d) => !isManaged(d))
+ existing.push({ hooks: [{ type: 'command', command }] })
+ next.hooks![ev] = existing
+ }
+ return next
+}
+
export interface InstallHooksOptions {
agentId: string
scriptFileName: string
@@ -59,12 +73,7 @@ export function installHooksInto(opts: InstallHooksOptions): void {
} catch {
config = {}
}
- config.hooks = config.hooks ?? {}
- for (const ev of events) {
- const existing = (config.hooks[ev] ?? []).filter((d) => !isManaged(d))
- existing.push({ hooks: [{ type: 'command', command }] })
- config.hooks[ev] = existing
- }
+ config = mergeManagedHook(config, command, events)
try {
mkdirSync(path.dirname(configPath), { recursive: true })
writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8')
diff --git a/src/main/agents/hooks/managed-script.test.ts b/src/main/agents/hooks/managed-script.test.ts
new file mode 100644
index 000000000..ffd07467b
--- /dev/null
+++ b/src/main/agents/hooks/managed-script.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest'
+import { buildManagedScript } from './managed-script'
+
+describe('buildManagedScript', () => {
+ const s = buildManagedScript('claude')
+ it('keeps the local TCP POST path', () => {
+ expect(s).toContain('http://127.0.0.1:${NODETERM_HOOK_PORT}/hook/claude')
+ })
+ it('adds a unix-socket POST branch gated on NODETERM_HOOK_SOCK', () => {
+ expect(s).toContain('NODETERM_HOOK_SOCK')
+ expect(s).toContain('--unix-socket')
+ expect(s).toContain('/hook/claude')
+ })
+ it('still no-ops without node id / endpoint', () => {
+ expect(s).toContain('NODETERM_NODE_ID')
+ })
+})
diff --git a/src/main/agents/hooks/managed-script.ts b/src/main/agents/hooks/managed-script.ts
index 4236c66e9..858265996 100644
--- a/src/main/agents/hooks/managed-script.ts
+++ b/src/main/agents/hooks/managed-script.ts
@@ -8,20 +8,30 @@ export function buildManagedScript(agentId: string): string {
'if [ -n "$NODETERM_HOOK_ENDPOINT" ] && [ -r "$NODETERM_HOOK_ENDPOINT" ]; then',
' . "$NODETERM_HOOK_ENDPOINT" 2>/dev/null || :',
'fi',
- 'if [ -z "$NODETERM_HOOK_PORT" ] || [ -z "$NODETERM_HOOK_TOKEN" ] || [ -z "$NODETERM_NODE_ID" ]; then',
+ 'if [ -z "$NODETERM_HOOK_TOKEN" ] || [ -z "$NODETERM_NODE_ID" ]; then',
' exit 0',
'fi',
'payload=$(cat)',
'if [ -z "$payload" ]; then',
' exit 0',
'fi',
- `curl -sS -X POST "http://127.0.0.1:\${NODETERM_HOOK_PORT}/hook/${agentId}" \\`,
- ' --connect-timeout 0.5 --max-time 1.5 \\',
- ' -H "Content-Type: application/x-www-form-urlencoded" \\',
- ' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',
- ' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
- ' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
- ' --data-urlencode "payload=${payload}" >/dev/null 2>&1 || true',
+ 'if [ -n "$NODETERM_HOOK_SOCK" ]; then',
+ ` curl -sS -X POST --unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/hook/${agentId}" \\`,
+ ' --connect-timeout 0.5 --max-time 1.5 \\',
+ ' -H "Content-Type: application/x-www-form-urlencoded" \\',
+ ' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',
+ ' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
+ ' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
+ ' --data-urlencode "payload=${payload}" >/dev/null 2>&1 || true',
+ 'elif [ -n "$NODETERM_HOOK_PORT" ]; then',
+ ` curl -sS -X POST "http://127.0.0.1:\${NODETERM_HOOK_PORT}/hook/${agentId}" \\`,
+ ' --connect-timeout 0.5 --max-time 1.5 \\',
+ ' -H "Content-Type: application/x-www-form-urlencoded" \\',
+ ' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',
+ ' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
+ ' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
+ ' --data-urlencode "payload=${payload}" >/dev/null 2>&1 || true',
+ 'fi',
'exit 0',
''
].join('\n')
diff --git a/src/main/remote-ssh/control-master.test.ts b/src/main/remote-ssh/control-master.test.ts
index 70cc52ef9..911051f2e 100644
--- a/src/main/remote-ssh/control-master.test.ts
+++ b/src/main/remote-ssh/control-master.test.ts
@@ -7,7 +7,11 @@ import {
remoteCapturePaneArgs,
remoteTmuxPtyArgs,
listDirArgs,
- RMT_TMUX_SOCKET
+ RMT_TMUX_SOCKET,
+ hookForwardArgs,
+ hookForwardCancelArgs,
+ remoteHookEnvArgs,
+ remoteEndpointFileContents
} from './control-master'
const conn = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }
@@ -73,6 +77,38 @@ describe('remoteTmuxPtyArgs', () => {
const cmd = args[args.length - 1]
expect(args.slice(1)).toEqual(childArgs(conn, '/s.sock', cmd))
})
+ it('splices extraEnv -e pairs right after new-session -A (before -s)', () => {
+ const args = remoteTmuxPtyArgs(conn, '/s.sock', 'nt-x', '/srv/app', undefined, undefined, [
+ '-e', 'NODETERM_HOOK_ENDPOINT=/r/ep.env',
+ '-e', 'NODETERM_NODE_ID=nt-x'
+ ])
+ const cmd = args[args.length - 1]
+ expect(cmd).toContain('new-session -A -e NODETERM_HOOK_ENDPOINT=/r/ep.env -e NODETERM_NODE_ID=nt-x -s')
+ })
+})
+
+describe('hook forwarding', () => {
+ it('hookForwardArgs builds a reverse unix-socket forward over the master', () => {
+ expect(hookForwardArgs(conn, '/s.sock', '/home/u/.nodeterm/h.sock', 51234)).toEqual([
+ '-O', 'forward', '-R', '/home/u/.nodeterm/h.sock:127.0.0.1:51234',
+ '-o', 'ControlPath=/s.sock', '-p', '2222', '[email protected]'
+ ])
+ })
+ it('hookForwardCancelArgs mirrors it with -O cancel', () => {
+ expect(hookForwardCancelArgs(conn, '/s.sock', '/r.sock', 51234)[1]).toBe('cancel')
+ })
+ it('remoteHookEnvArgs builds tmux -e pairs (endpoint + node id + version)', () => {
+ expect(remoteHookEnvArgs('/r/.nodeterm/ep.env', 'nt-x', '1')).toEqual([
+ '-e', 'NODETERM_HOOK_ENDPOINT=/r/.nodeterm/ep.env',
+ '-e', 'NODETERM_NODE_ID=nt-x',
+ '-e', 'NODETERM_HOOK_VERSION=1'
+ ])
+ })
+ it('remoteEndpointFileContents writes SOCK/TOKEN/VERSION', () => {
+ expect(remoteEndpointFileContents('/r.sock', 'tok', '1')).toBe(
+ 'NODETERM_HOOK_SOCK=/r.sock\nNODETERM_HOOK_TOKEN=tok\nNODETERM_HOOK_VERSION=1\n'
+ )
+ })
})
describe('listDirArgs', () => {
diff --git a/src/main/remote-ssh/control-master.ts b/src/main/remote-ssh/control-master.ts
index 7e9143cb7..31780d577 100644
--- a/src/main/remote-ssh/control-master.ts
+++ b/src/main/remote-ssh/control-master.ts
@@ -71,15 +71,44 @@ export function listDirArgs(conn: SshConnection, controlPath: string, path: stri
return childArgs(conn, controlPath, `ls -1Ap ${quoteRemotePath(path)}`)
}
-/** The remote PTY program is `ssh <childArgs> host -t '<remoteTmuxCommand>'`. */
+/**
+ * Reverse-forward the local hook server's loopback TCP port to a remote unix socket over the
+ * existing master (`ssh -O forward -R <remoteSock>:127.0.0.1:<hookPort>`), so remote hook scripts
+ * can POST to it via `curl --unix-socket`.
+ */
+function fwdSpec(remoteSock: string, hookPort: number): string {
+ return `${remoteSock}:127.0.0.1:${hookPort}`
+}
+export function hookForwardArgs(conn: SshConnection, controlPath: string, remoteSock: string, hookPort: number): string[] {
+ return ['-O', 'forward', '-R', fwdSpec(remoteSock, hookPort), '-o', `ControlPath=${controlPath}`, ...portArgs(conn), target(conn)]
+}
+export function hookForwardCancelArgs(conn: SshConnection, controlPath: string, remoteSock: string, hookPort: number): string[] {
+ return ['-O', 'cancel', '-R', fwdSpec(remoteSock, hookPort), '-o', `ControlPath=${controlPath}`, ...portArgs(conn), target(conn)]
+}
+/** tmux `-e KEY=VALUE` pairs injecting the remote hook endpoint file + node id + protocol version. */
+export function remoteHookEnvArgs(endpointPath: string, nodeId: string, version: string): string[] {
+ return ['-e', `NODETERM_HOOK_ENDPOINT=${endpointPath}`, '-e', `NODETERM_NODE_ID=${nodeId}`, '-e', `NODETERM_HOOK_VERSION=${version}`]
+}
+/** Contents of the remote endpoint env file the managed hook script sources (unix-socket transport). */
+export function remoteEndpointFileContents(sock: string, token: string, version: string): string {
+ return `NODETERM_HOOK_SOCK=${sock}\nNODETERM_HOOK_TOKEN=${token}\nNODETERM_HOOK_VERSION=${version}\n`
+}
+
+/**
+ * The remote PTY program is `ssh <childArgs> host -t '<remoteTmuxCommand>'`. `extraEnv` is an
+ * already-built list of tmux `-e KEY=VALUE` pairs (e.g. from `remoteHookEnvArgs`) spliced into
+ * the `new-session` command right after `-A`, mirroring the local tmux `-e` placement.
+ */
export function remoteTmuxPtyArgs(
conn: SshConnection,
controlPath: string,
sessionId: string,
remoteCwd: string,
program?: string,
- programArgs?: string[]
+ programArgs?: string[],
+ extraEnv: string[] = []
): string[] {
- const cmd = remoteTmuxCommand({ sessionId, remoteCwd, program, programArgs, socket: RMT_TMUX_SOCKET })
+ let cmd = remoteTmuxCommand({ sessionId, remoteCwd, program, programArgs, socket: RMT_TMUX_SOCKET })
+ if (extraEnv.length) cmd = cmd.replace('new-session -A ', `new-session -A ${extraEnv.join(' ')} `)
return ['-t', ...childArgs(conn, controlPath, cmd)]
}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index eae6982ae..226e461b6 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -23,7 +23,7 @@ export interface PtyCreateOptions {
*/
agentId?: AgentId
/** When set, this PTY runs on a remote host over the project's ssh ControlMaster, in remote tmux. */
- sshRemote?: { controlPath: string; conn: import('./ssh').SshConnection; remoteCwd: string }
+ sshRemote?: { controlPath: string; conn: import('./ssh').SshConnection; remoteCwd: string; hookEndpointPath?: string }
}
/**