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.

fix(hooks): preserve app boot and migrate proven legacy endpoints

reviewb97278dda1c9
diff --git a/CLAUDE.md b/CLAUDE.md
index cb92c3213..3308626dd 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2072,12 +2072,21 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
- **Hook endpoint ownership (#826):** startup first probes every transport in an existing
endpoint advertisement and preserves a live or uncertain owner. The local Unix listener probes its socket before
cleanup. Only `ECONNREFUSED` plus the same device/inode permits removal; a live listener,
- non-socket, symlink or uncertain probe refuses startup without replacing its endpoint.
+ non-socket, symlink or uncertain probe disables hooks without replacing its endpoint.
+ Both shells use `startForApp`: Desktop creates its window and then shows an actionable warning;
+ Server Edition logs the same warning and continues boot. An authenticated owner must answer
+ `/verify` with 204 for the advertised bearer AND reject a random bearer (403/421); unrelated
+ HTTP responses are uncertain listeners, not authenticated nodeterm. Probes have a hard deadline.
Endpoint writes are atomic and stop removes only the run's own advertised contents. SSH setup
never removes a socket before binding: every forward gets a fresh random path, while discovery
is stable per project + installation identity hash. Only a verified replacement is advertised;
- then this run cancels its previous forward. Existing legacy endpoint files are left intact and
- upgraded clients can discover the new file. A reused tunnel that loses bearer verification
+ then this run cancels its previous forward. A legacy project endpoint is migrated only when its
+ bearer matches the current run, the previous installation-qualified advertisement, or a stale
+ conventional local advertisement retained at boot. Publication rechecks the snapshot digest,
+ refuses symlinks, uses a migration lock and a private temp, and never places credentials in argv.
+ Without ownership proof (including a first upgrade after the old local advertisement was deleted),
+ it preserves the file and logs instructions to restart affected agent sessions; discovery still
+ works but may incur the old dead-tunnel delay until then. No real-host upgrade is claimed by unit tests. A reused tunnel that loses bearer verification
emits hook-only health updates: the desktop shows a warning and clears it after repair, without
reconnecting terminals. These changes share the core listener in Desktop and Server Edition;
the mobile wire protocol and node-identity rules are unchanged.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 67d4db2a6..e57060620 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -769,3 +769,9 @@ who never saw it.
Managed Codex login terminals are agent-less: core identifies their provider from the saved
account list. Before opening one, await `useSettings.getState().flush()` after adding the account.
The normal 300 ms coalesced save is too late: an unknown id can launch against the system home.
+
+Optional hook ownership failures must never stop Desktop window creation or Server boot. Use the
+shared nonfatal startup path and surface its actionable diagnostic. A responding HTTP port is not
+nodeterm identity: verify bearer acceptance and rejection. Legacy SSH endpoint migration requires
+ownership proof, an unchanged-file check, and stdin-only credential transfer; a project name alone
+is not permission to replace another installation's advertisement.
diff --git a/src/core/agents/hook-server.boot.test.ts b/src/core/agents/hook-server.boot.test.ts
new file mode 100644
index 000000000..acbeb513a
--- /dev/null
+++ b/src/core/agents/hook-server.boot.test.ts
@@ -0,0 +1,66 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { createServer } from 'http'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { HookServer } from './hook-server'
+import { initPlatform, resetPlatformForTests } from '../platform'
+import { fakePlatform } from '../platform-fake'
+
+let dir: string
+const servers: HookServer[] = []
+function hook(): HookServer { const h = new HookServer(); servers.push(h); return h }
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-boot-'))
+ resetPlatformForTests()
+ initPlatform(fakePlatform({ userDataDir: dir }))
+})
+afterEach(() => {
+ for (const h of servers.splice(0)) h.stop()
+ fs.rmSync(dir, { recursive: true, force: true })
+})
+describe('nonfatal hook startup used by both application shells', () => {
+ it('continues boot with an actionable warning and preserves a malformed file', async () => {
+ const h = hook()
+ fs.writeFileSync(h.endpointFilePath(), 'NODETERM_HOOK_PO')
+ const warning = await h.startForApp()
+ expect(warning).toContain('Agent hooks are disabled')
+ expect(warning).toContain(h.endpointFilePath())
+ expect(warning).toContain('restart nodeterm')
+ expect(h.getPort()).toBe(0)
+ expect(h.getToken()).toBe('')
+ expect(fs.readFileSync(h.endpointFilePath(), 'utf8')).toBe('NODETERM_HOOK_PO')
+ })
+ it('continues boot without replacing an unrelated HTTP listener advertisement', async () => {
+ const foreign = createServer((_req, res) => { res.writeHead(404); res.end() })
+ await new Promise<void>((resolve) => foreign.listen(0, '127.0.0.1', resolve))
+ const h = hook()
+ const content = `NODETERM_HOOK_PORT='${(foreign.address() as { port: number }).port}'\n`
+ fs.writeFileSync(h.endpointFilePath(), content)
+ try {
+ expect(await h.startForApp()).toContain('Agent hooks are disabled')
+ expect(h.getPort()).toBe(0)
+ expect(fs.readFileSync(h.endpointFilePath(), 'utf8')).toBe(content)
+ } finally { await new Promise<void>((resolve) => foreign.close(() => resolve())) }
+ })
+ it('continues boot with hooks disabled while a real owner keeps serving', async () => {
+ const owner = hook()
+ expect(await owner.startForApp()).toBeNull()
+ const contents = fs.readFileSync(owner.endpointFilePath(), 'utf8')
+ const other = hook()
+ expect(await other.startForApp()).toContain('Close any other nodeterm instance')
+ expect(other.getPort()).toBe(0)
+ expect(fs.readFileSync(owner.endpointFilePath(), 'utf8')).toBe(contents)
+ const response = await fetch(`http://127.0.0.1:${owner.getPort()}/verify`, {
+ method: 'POST', headers: { 'x-nodeterm-hook-token': owner.getToken() }
+ })
+ expect(response.status).toBe(204)
+ })
+ it('reclaims a stale advertisement and retains its local bearer for SSH upgrade proof', async () => {
+ const h = hook()
+ fs.writeFileSync(h.endpointFilePath(), `NODETERM_HOOK_SOCK='${path.join(dir, 'sock', 'hook.sock')}'\nNODETERM_HOOK_TOKEN='previous-run'\n`)
+ expect(await h.startForApp()).toBeNull()
+ expect(h.getPreviousEndpointToken()).toBe('previous-run')
+ expect(h.getPort()).toBeGreaterThan(0)
+ })
+})
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.ts
index dac3d2d93..e8df3643d 100644
--- a/src/core/agents/hook-server.ts
+++ b/src/core/agents/hook-server.ts
@@ -7,6 +7,7 @@ import { homedir } from 'os'
import path from 'path'
import { platform } from '../platform'
import { writeFileAtomic } from '../fs-atomic'
+import { parseEndpointEnv } from './hook-endpoint-parse'
import { hookSockPath } from './hook-sock-path'
import { canControlCanvas, type AgentId } from '../../shared/agents/config'
import { normalizeFor, type NormalizedAgentEvent } from '../../shared/agents/normalize'
@@ -356,6 +357,10 @@ export class HookServer {
}) => Promise<void>)
| null = null
private codexIdentityListener: ((e: CodexIdentityEvent) => void) | null = null
+ private previousEndpointToken = ''
+
+ getPreviousEndpointToken(): string { return this.previousEndpointToken }
+
private endpointPath = ''
private publishedEndpoint = ''
private nodeAuthSecret: Buffer | null = null
@@ -554,6 +559,22 @@ export class HookServer {
this.identityNow = now
}
+ /** Shell boot must continue even when optional hooks cannot safely take ownership. */
+ async startForApp(): Promise<string | null> {
+ try {
+ await this.start()
+ return null
+ } catch {
+ this.stop()
+ // Do not include raw errors: an invalid HTTP header may contain the bearer.
+ return `Agent hooks are disabled because their endpoint is occupied, malformed, or unavailable. ` +
+ `The application can still run, but agent status and canvas commands may be unavailable. ` +
+ `Close any other nodeterm instance using this data directory. If none is running, inspect ` +
+ `${this.endpointFilePath()} and its advertised listener; back up and remove a stale file, ` +
+ `then restart nodeterm. No other owner's endpoint was replaced.`
+ }
+ }
+
async start(): Promise<void> {
if (this.starting) return this.starting
if (this.server) return
@@ -567,6 +588,14 @@ export class HookServer {
private async startOwnedEndpoint(): Promise<void> {
await assertHookEndpointAvailable(this.endpointFilePath())
+ this.previousEndpointToken = ''
+ try {
+ const previous = parseEndpointEnv(readFileSync(this.endpointFilePath(), 'utf8'))
+ // Only our conventional local endpoint supplies upgrade proof, never a tunnel record.
+ if (previous.NODETERM_HOOK_SOCK === hookSockPath(platform().userDataDir)) {
+ this.previousEndpointToken = previous.NODETERM_HOOK_TOKEN ?? ''
+ }
+ } catch { /* a first run has no prior bearer */ }
this.token = randomUUID()
// ONE handler, shared verbatim by the TCP and the unix-socket listeners: every gate (bearer,
// per-node verdict, verified-only verbs) runs identically on both transports.
diff --git a/src/core/agents/hook-socket-owner.test.ts b/src/core/agents/hook-socket-owner.test.ts
index 5e853e6e4..8f057414a 100644
--- a/src/core/agents/hook-socket-owner.test.ts
+++ b/src/core/agents/hook-socket-owner.test.ts
@@ -16,19 +16,29 @@ function fixture(): string {
afterEach(() => { for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true }) })
describe('hook endpoint advertisement ownership', () => {
- it.each([204, 421])('preserves a live advertised owner answering %s, independently of the new bind path', async (status) => {
+ it.each([403, 421])('authenticates a live owner whose wrong-token reply is %s', async (status) => {
const file = fixture()
- const server = createHttpServer((_req, res) => { res.writeHead(status); res.end() })
+ const server = createHttpServer((req, res) => { res.writeHead(req.headers['x-nodeterm-hook-token'] === 'old-owner' ? 204 : status); res.end() })
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
const address = server.address() as { port: number }
const contents = `NODETERM_HOOK_PORT='${address.port}'\nNODETERM_HOOK_TOKEN='old-owner'\n`
fs.writeFileSync(file, contents)
try {
- await expect(assertHookEndpointAvailable(file)).rejects.toThrow('hook-endpoint-owned')
+ await expect(assertHookEndpointAvailable(file)).rejects.toThrow('live nodeterm owner authenticated')
expect(fs.readFileSync(file, 'utf8')).toBe(contents)
} finally { await new Promise<void>((resolve) => server.close(() => resolve())) }
})
+ it.each([200, 204, 404, 421])('does not authenticate a foreign HTTP listener returning %s', async (status) => {
+ const file = fixture()
+ const server = createHttpServer((_req, res) => { res.writeHead(status); res.end() })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ fs.writeFileSync(file, `NODETERM_HOOK_PORT='${(server.address() as { port: number }).port}'\nNODETERM_HOOK_TOKEN='old-owner'\n`)
+ try {
+ await expect(assertHookEndpointAvailable(file)).rejects.toThrow('could not be authenticated')
+ } finally { await new Promise<void>((resolve) => server.close(() => resolve())) }
+ })
+
it('allows an absent file but preserves an unreadable ownership record', async () => {
const file = fixture()
await expect(assertHookEndpointAvailable(file)).resolves.toBeUndefined()
diff --git a/src/core/agents/hook-socket-owner.ts b/src/core/agents/hook-socket-owner.ts
index ca3866c9e..d87b3bac2 100644
--- a/src/core/agents/hook-socket-owner.ts
+++ b/src/core/agents/hook-socket-owner.ts
@@ -1,12 +1,13 @@
import { lstatSync, readFileSync, unlinkSync } from 'fs'
import { createConnection } from 'net'
import { request } from 'http'
+import { randomUUID } from 'crypto'
import { parseEndpointEnv } from './hook-endpoint-parse'
export class HookSocketOwnedError extends Error {
- constructor() {
+ constructor(reason = 'Another listener may own this hook endpoint') {
super(
- 'hook-endpoint-owned: Another listener may own this hook endpoint; its advertisement was left unchanged.'
+ `hook-endpoint-owned: ${reason}; its advertisement was left unchanged.`
)
}
}
@@ -26,26 +27,37 @@ export async function assertHookEndpointAvailable(file: string): Promise<void> {
...(env.NODETERM_HOOK_SOCK ? [{ socketPath: env.NODETERM_HOOK_SOCK }] : []),
...(Number.isInteger(port) && port > 0 && port <= 65535 ? [{ host: '127.0.0.1', port }] : [])
]
- if (!targets.length) throw new HookSocketOwnedError()
+ if (!targets.length) throw new HookSocketOwnedError('The endpoint file is malformed')
for (const target of targets) {
- const stale = await new Promise<boolean>((resolve) => {
- const req = request({
- ...target,
- path: '/verify',
- method: 'POST',
- timeout: 500,
- headers: { 'X-Nodeterm-Hook-Token': env.NODETERM_HOOK_TOKEN ?? '' }
- })
- const finish = (value: boolean): void => {
- req.destroy()
+ const probe = (token: string): Promise<number | 'stale' | 'unknown'> => new Promise((resolve) => {
+ let req: ReturnType<typeof request>
+ const deadline = setTimeout(() => finish('unknown'), 500)
+ const finish = (value: number | 'stale' | 'unknown'): void => {
+ clearTimeout(deadline)
+ req?.destroy()
resolve(value)
}
- req.once('response', () => finish(false))
- req.once('timeout', () => finish(false))
- req.once('error', (e: NodeJS.ErrnoException) => finish(e.code === 'ECONNREFUSED' || e.code === 'ENOENT'))
- req.end()
+ try {
+ req = request({
+ ...target, path: '/verify', method: 'POST', timeout: 500,
+ headers: { 'X-Nodeterm-Hook-Token': token }
+ })
+ req.once('response', (res) => finish(res.statusCode ?? 'unknown'))
+ req.once('timeout', () => finish('unknown'))
+ req.once('error', (e: NodeJS.ErrnoException) =>
+ finish(e.code === 'ECONNREFUSED' || e.code === 'ENOENT' ? 'stale' : 'unknown'))
+ req.end()
+ } catch { finish('unknown') }
})
- if (!stale) throw new HookSocketOwnedError()
+ const answer = await probe(env.NODETERM_HOOK_TOKEN ?? '')
+ if (answer === 'stale') continue
+ // A generic 204 listener is not nodeterm. Prove that /verify accepts the advertised
+ // bearer AND rejects an unrelated one, including pre-421 nodeterm releases.
+ const negative = answer === 204 && env.NODETERM_HOOK_TOKEN ? await probe(randomUUID()) : null
+ if (answer === 204 && (negative === 403 || negative === 421)) {
+ throw new HookSocketOwnedError('A live nodeterm owner authenticated the advertised bearer')
+ }
+ throw new HookSocketOwnedError('The advertised listener could not be authenticated as nodeterm')
}
}
diff --git a/src/main/index.ts b/src/main/index.ts
index d8f8d94cb..425335618 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1866,7 +1866,7 @@ app.whenReady().then(async () => {
// hook POST dies against a dead port with zero symptoms beyond "statuses stay idle". The
// listeners (setListener/setRawListener/setControlHandler) attach later, which the server
// tolerates — early hook POSTs are simply dropped, never mis-routed.
- await hookServer.start()
+ const hookStartupWarning = await hookServer.startForApp()
// ---- Node identity (src/core/agents/node-auth-secret.ts) ------------------------------------
// One secret does two jobs: it arms the hook server's per-node capability (closing the "shared
// bearer can name any sibling node" hole) and it signs the codex thread → node records the hook
@@ -1943,6 +1943,10 @@ app.whenReady().then(async () => {
return undefined
})
const win = createWindow()
+ if (hookStartupWarning) {
+ console.error('[agent-hooks]', hookStartupWarning)
+ void dialog.showMessageBox(win, { type: 'warning', title: 'Agent hooks unavailable', message: hookStartupWarning })
+ }
// NT_MULTI instances are throwaway dev sandboxes. The dock badge is the one marker that is
// always visible on macOS (the window title is hidden by titleBarStyle: 'hiddenInset', and the
// dev dock icon/name are Electron's own), so a test instance can never be mistaken for the
diff --git a/src/main/remote-ssh/legacy-hook-endpoint.test.ts b/src/main/remote-ssh/legacy-hook-endpoint.test.ts
new file mode 100644
index 000000000..e9fb15c95
--- /dev/null
+++ b/src/main/remote-ssh/legacy-hook-endpoint.test.ts
@@ -0,0 +1,45 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { execFileSync, spawnSync } from 'child_process'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { legacyEndpointMigration } from './legacy-hook-endpoint'
+
+const dirs: string[] = []
+function fixture(): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nt-legacy-' space-"))
+ dirs.push(dir)
+ return path.join(dir, 'legacy.env')
+}
+afterEach(() => { for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true }) })
+const old = "NODETERM_HOOK_TOKEN='old-secret'\nNODETERM_HOOK_SOCK='/dead'\n"
+const fresh = "NODETERM_HOOK_TOKEN='new-secret'\nNODETERM_HOOK_SOCK='/verified'\n"
+describe.skipIf(process.platform === 'win32')('legacy SSH endpoint migration (real shell)', () => {
+ it('updates an owned legacy path atomically with private permissions and no argv secrets', () => {
+ const file = fixture()
+ fs.writeFileSync(file, old)
+ const migration = legacyEndpointMigration(file, old, fresh, ['old-secret'])!
+ expect(migration.command).not.toContain('old-secret')
+ expect(migration.command).not.toContain('new-secret')
+ execFileSync('/bin/sh', ['-c', migration.command], { input: migration.stdin })
+ expect(fs.readFileSync(file, 'utf8')).toBe(fresh)
+ expect(fs.statSync(file).mode & 0o777).toBe(0o600)
+ expect(fs.readdirSync(path.dirname(file))).toEqual(['legacy.env'])
+ })
+ it('refuses an unknown owner and malformed credentials', () => {
+ expect(legacyEndpointMigration(fixture(), old, fresh, ['other'])).toBeNull()
+ expect(legacyEndpointMigration(fixture(), 'partial', fresh, [''])).toBeNull()
+ })
+ it.each(['changed', 'symlink', 'locked'])('preserves a %s target after the ownership read', (kind) => {
+ const file = fixture()
+ fs.writeFileSync(file, old)
+ const migration = legacyEndpointMigration(file, old, fresh, ['old-secret'])!
+ if (kind === 'changed') fs.writeFileSync(file, 'another owner')
+ if (kind === 'symlink') { fs.renameSync(file, `${file}.target`); fs.symlinkSync(`${file}.target`, file) }
+ if (kind === 'locked') fs.mkdirSync(`${file}.migration-lock`)
+ const result = spawnSync('/bin/sh', ['-c', migration.command], { input: migration.stdin })
+ expect(result.status).not.toBe(0)
+ expect(fs.readFileSync(file, 'utf8')).toBe(kind === 'changed' ? 'another owner' : old)
+ if (kind === 'symlink') expect(fs.lstatSync(file).isSymbolicLink()).toBe(true)
+ })
+})
diff --git a/src/main/remote-ssh/legacy-hook-endpoint.ts b/src/main/remote-ssh/legacy-hook-endpoint.ts
new file mode 100644
index 000000000..cbeb9bc37
--- /dev/null
+++ b/src/main/remote-ssh/legacy-hook-endpoint.ts
@@ -0,0 +1,23 @@
+import { createHash, randomUUID } from 'crypto'
+import { parseEndpointEnv } from '../../core/agents/hook-endpoint-parse'
+import { posixQuote } from '../../shared/ssh'
+
+/** A project name alone is not ownership. Only a bearer already held by this installation
+ * permits migration. Unknown legacy files stay untouched; sessions can use bounded discovery. */
+export function legacyEndpointMigration(
+ file: string, snapshot: string, contents: string, ownedTokens: readonly string[]
+): { command: string; stdin: string } | null {
+ const token = parseEndpointEnv(snapshot).NODETERM_HOOK_TOKEN
+ if (!token || !ownedTokens.some((owned) => owned && owned === token)) return null
+ const q = posixQuote(file)
+ const stage = posixQuote(`${file}.migration-${randomUUID()}`)
+ const digest = createHash('sha256').update(snapshot).digest('hex')
+ // A digest is public comparison data, never the old or new bearer. Both credentials stay
+ // off argv. Refuse symlinks, concurrent changes and overlapping migration writers.
+ const cleanup = posixQuote(`rm -f -- ${stage}; rmdir ${q}.migration-lock`)
+ const command = `umask 077; mkdir ${q}.migration-lock 2>/dev/null || exit 1; ` +
+ `trap ${cleanup} EXIT; ` +
+ `cat > ${stage} && chmod 600 ${stage} && test ! -L ${q} && test -f ${q} && ` +
+ `test "$( (sha256sum < ${q} 2>/dev/null || shasum -a 256 < ${q}) | cut -d ' ' -f 1)" = '${digest}' && mv -f -- ${stage} ${q}`
+ return { command, stdin: contents }
+}
diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.ts
index 27e3358ea..f2784bf0e 100644
--- a/src/main/remote-ssh/remote-hooks.test.ts
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@ -48,6 +48,32 @@ function harness(
}
describe('RemoteHooks.setup', () => {
+ it('migrates a legacy file using this installation’s previous qualified bearer', async () => {
+ const legacy = "NODETERM_HOOK_TOKEN='previous-secret'\nNODETERM_HOOK_SOCK='/stale'\n"
+ const { rh, calls } = harness({ responses: {
+ [`cat '/home/u/.nodeterm/hook-endpoint-p1-${owner}.env'`]: legacy,
+ ["cat '/home/u/.nodeterm/hook-endpoint-p1.env'"]: legacy
+ } })
+ expect(await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })).not.toBeNull()
+ const migration = calls.find((c) => c.cmd.includes('.migration-lock'))
+ expect(migration).toBeDefined()
+ expect(migration!.stdin).toContain("NODETERM_HOOK_TOKEN='tok'")
+ expect(migration!.cmd).not.toContain('previous-secret')
+ expect(migration!.cmd).not.toContain("'tok'")
+ })
+
+ it('preserves a legacy file owned by another installation and still connects', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ const { rh, calls } = harness({ responses: {
+ ["cat '/home/u/.nodeterm/hook-endpoint-p1.env'"]: "NODETERM_HOOK_TOKEN='foreign-secret'\n"
+ } })
+ expect(await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })).not.toBeNull()
+ expect(calls.some((c) => c.cmd.includes('.migration-lock'))).toBe(false)
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('restart affected agent sessions'))
+ } finally { warn.mockRestore() }
+ })
+
it('opens a reverse forward, writes the endpoint file, and installs the managed hook for claude', async () => {
const { rh, calls } = harness()
const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })
diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.ts
index 820ceb5f5..cb5f0d335 100644
--- a/src/main/remote-ssh/remote-hooks.ts
+++ b/src/main/remote-ssh/remote-hooks.ts
@@ -1,4 +1,6 @@
import { createHash, randomUUID } from 'crypto'
+import { parseEndpointEnv } from '../../core/agents/hook-endpoint-parse'
+import { legacyEndpointMigration } from './legacy-hook-endpoint'
// 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 JSON settings,
@@ -208,6 +210,11 @@ export class RemoteHooks {
return null
}
const previous = this.specs.get(projectId)
+ // Read the installation-qualified file BEFORE replacing it: its prior bearer can prove
+ // ownership after a normal app quit removed the local endpoint advertisement.
+ const prior = await this.r.run(childArgs(conn, controlPath,
+ `test ! -L ${posixQuote(endpoint)} && cat ${posixQuote(endpoint)} 2>/dev/null`)).catch(() => null)
+ const previousToken = prior?.code === 0 ? parseEndpointEnv(prior.stdout).NODETERM_HOOK_TOKEN : ''
// 2. Remote endpoint file — written only after the tunnel proved live, so sessions are
// never pointed at a socket that answers nothing. The file carries the hook bearer. A
// direct `cat > endpoint` both exposed partial bytes and preserved an old permissive mode;
@@ -225,6 +232,23 @@ export class RemoteHooks {
await this.r.run(hookForwardCancelArgs(conn, controlPath, sock, hook.port)).catch(() => {})
return null
}
+ const legacy = `${remoteDir}/hook-endpoint-${projectId}.env`
+ try {
+ const old = await this.r.run(childArgs(conn, controlPath,
+ `test ! -L ${posixQuote(legacy)} && cat ${posixQuote(legacy)} 2>/dev/null`))
+ if (old.code === 0 && old.stdout) {
+ const migration = legacyEndpointMigration(legacy, old.stdout,
+ remoteEndpointFileContents(sock, hook.token, hook.version, `${remoteDir}/node-tokens`),
+ [hook.token, previousToken ?? '', hookServer.getPreviousEndpointToken()])
+ const migrated = migration && await this.r.run(childArgs(conn, controlPath, migration.command), migration.stdin)
+ if (!migrated || migrated.code !== 0) {
+ console.warn('[remote-hooks] Legacy hook endpoint was preserved because ownership or unchanged contents could not be proven. ' +
+ 'Existing sessions use endpoint discovery; restart affected agent sessions to adopt the new endpoint directly.')
+ }
+ }
+ } catch {
+ console.warn('[remote-hooks] Legacy hook endpoint migration unavailable; restart affected agent sessions to adopt the new endpoint directly.')
+ }
this.specs.set(projectId, { sock, port: hook.port })
if (previous) {
await this.r.run(hookForwardCancelArgs(conn, controlPath, previous.sock, previous.port)).catch(() => {})
diff --git a/src/server/index.ts b/src/server/index.ts
index 15ead1c4b..e398afe90 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -616,7 +616,8 @@ export async function startServer(
// this baseline hook pass stays unchanged when the feature flag is off.
installHooksIntoLocalAccounts(settingsStore.get().claudeAccounts ?? [])
}
- await hookServer.start()
+ const hookStartupWarning = await hookServer.startForApp()
+ if (hookStartupWarning) console.error('[nodeterm-server]', hookStartupWarning)
// Safe default and rollback path. The opt-in runtime replaces this handler only after its
// workspace-backed services are ready; a failed initialization therefore degrades to the same
// named permanent refusal rather than a half-wired execution surface.