The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): kill hung remote SSH probes via a POSIX remote watchdog
Kevin Rajan5724cb300235
diff --git a/apps/desktop/electron/remote-lifecycle.test.ts b/apps/desktop/electron/remote-lifecycle.test.tsindex 583f4edcab8..941d52282aa 100644--- a/apps/desktop/electron/remote-lifecycle.test.ts+++ b/apps/desktop/electron/remote-lifecycle.test.ts@@ -26,6 +26,7 @@ import {openForward,ownershipDirectory,pidIsOurDashboard,+ probeHermesVersion,probeRemotePlatform,PROTOCOL_VERSION,readLockfile,@@ -476,7 +477,7 @@ test('connect() fails closed on lockfile schema/ownership skew: skips reap, touc`${label}: connect must refuse with remote-lockfile-skew`)assert.ok(- !ssh.calls.some(c => /(^|[^-\d])kill -?9? ?\d/.test(c) && !/kill -0/.test(c)),+ !ssh.calls.some(c => /(^|[^-\d])kill -9 \d+/.test(c) && !/kill -0/.test(c)),`${label}: must not kill any pid`)assert.ok(!ssh.calls.some(c => /rm -f/.test(c)), `${label}: must not remove any remote file`)@@ -1810,6 +1811,41 @@ test('remote SSH ownership capability requires both secure bootstrap flags', asyassert.equal(await remoteSupportsSshOwnership(unsupported, '/x/hermes'), false)})+test('probes run under the remote watchdog so a hung CLI cannot orphan (#110478)', async () => {+ let versionProbe = ''++ const versionSsh = fakeSsh([+ [+ /--version/,+ (cmd: string) => {+ versionProbe = cmd++ return 'Hermes Agent v0.18.2 (abc123)\n'+ }+ ]+ ])++ assert.equal(await probeHermesVersion(versionSsh, '/x/hermes'), 'Hermes Agent v0.18.2 (abc123)')+ assert.ok(versionProbe.includes('kill -9'), 'version probe wrapped in the remote watchdog')++ let helpProbe = ''++ const helpSsh = fakeSsh([+ [+ /serve --help/,+ (cmd: string) => {+ helpProbe = cmd++ return 'YES\n'+ }+ ]+ ])++ assert.equal(await remoteSupportsSshOwnership(helpSsh, '/x/hermes'), true)+ assert.ok(helpProbe.includes('kill -9'), 'ownership probe wrapped in the remote watchdog')+ assert.ok(helpProbe.includes('$( ('), 'watchdog nested around the inner serve --help')+})+test('cleanupStale escalates to SIGKILL when the backend survives the graceful wait (#91668 quit-during-active-turn)', async () => {// A serve mid-turn (in-flight LLM call, live MCP children) can ride out// SIGTERM well past the 5s graceful wait. Before-quit races the wholediff --git a/apps/desktop/electron/remote-lifecycle.ts b/apps/desktop/electron/remote-lifecycle.tsindex cf38b4752d8..dc39f064c90 100644--- a/apps/desktop/electron/remote-lifecycle.ts+++ b/apps/desktop/electron/remote-lifecycle.ts@@ -29,7 +29,7 @@ import crypto from 'node:crypto'import { READY_IN_MERGED_OUTPUT_RE } from './backend-ready'import { parseRemoteProfileListing } from './connection-registry'-import { assertBootstrapNotSuperseded } from './ssh-connection'+import { assertBootstrapNotSuperseded, withRemoteTimeout } from './ssh-connection'const LOCKFILE_SCHEMA_VERSION = 2// Bumped when the desktop<->dashboard reuse contract changes in a way that makes@@ -250,7 +250,9 @@ async function locateHermes(ssh, remoteHermesPath) {// connection uses, so a stale/unexpected install is visible.async function probeHermesVersion(ssh, hermesPath) {try {- const out = (await ssh.exec(`${expandRemotePath(hermesPath)} --version 2>&1`)).trim()+ // Watchdogged: a hung remote CLI must die remotely instead of orphaning+ // when the local ssh child is SIGKILLed (#110478).+ const out = (await ssh.exec(withRemoteTimeout(`${expandRemotePath(hermesPath)} --version 2>&1`))).trim()return (out.split('\n')[0] || '').trim()} catch {@@ -1123,8 +1125,11 @@ function buildSpawnCommand(hermesPath, profile, opts: any = {}) {async function remoteSupportsSshOwnership(ssh, hermesPath) {const hermes = expandRemotePath(hermesPath)+ // The watchdog wraps the inner `serve --help` so the hung CLI is its direct+ // child and dies remotely instead of orphaning (#110478). The `$( (` space+ // is load-bearing: without it the shell parses `$((` as arithmetic expansion.const out = await ssh.exec(- `help="$(${hermes} serve --help 2>&1)"; ` ++ `help="$( ${withRemoteTimeout(`${hermes} serve --help 2>&1`)} )"; ` +`printf '%s' "$help" | grep -q ssh-session-token-file && ` +`printf '%s' "$help" | grep -q ssh-owner-nonce && echo YES || echo NO`)diff --git a/apps/desktop/electron/ssh-connection.test.ts b/apps/desktop/electron/ssh-connection.test.tsindex fa954cebbda..49e1fd33b88 100644--- a/apps/desktop/electron/ssh-connection.test.ts+++ b/apps/desktop/electron/ssh-connection.test.ts@@ -1,8 +1,10 @@import assert from 'node:assert/strict'+import { execFile } from 'node:child_process'import { EventEmitter } from 'node:events'import fs from 'node:fs'import os from 'node:os'import path from 'node:path'+import { promisify } from 'node:util'import { test } from 'vitest'@@ -18,15 +20,19 @@ import {forwardSpec,hostArgs,redactSecrets,+ REMOTE_PROBE_TIMEOUT_SECS,runSsh,SSH_ERROR,SshConnection,sshErrorMessage,stopTunnelChild,target,- validateSshTarget+ validateSshTarget,+ withRemoteTimeout} from './ssh-connection'+const execFileAsync = promisify(execFile)+test('redactSecrets scrubs the spawn-time session token env var', () => {const line = 'setsid env HERMES_DASHBOARD_SESSION_TOKEN=abc123deadbeef HERMES_DESKTOP=1 hermes dashboard'const out = redactSecrets(line)@@ -1067,3 +1073,46 @@ test('stopTunnelChild waits for process exit', async () => {await stoppingassert.equal(stopped, true)})++test('withRemoteTimeout kills a hung probe remotely instead of orphaning it (#110478)', async () => {+ // Shape: POSIX watchdog — macOS remotes have no GNU `timeout`.+ const wrapped = withRemoteTimeout('hermes --version 2>&1', 15)++ assert.ok(wrapped.includes('sleep 15'), 'watchdog duration honored')+ assert.ok(wrapped.includes('kill -9'), 'watchdog kills the hung child remotely')+ assert.ok(!/(^|[ ;(])timeout[ ;]/.test(wrapped), 'no GNU timeout dependency')+ assert.ok(wrapped.endsWith('exit $__htrc'), 'inner exit code propagated')+ assert.ok(+ withRemoteTimeout('true').includes(`sleep ${REMOTE_PROBE_TIMEOUT_SECS}`),+ 'defaults to REMOTE_PROBE_TIMEOUT_SECS'+ )+ assert.ok(REMOTE_PROBE_TIMEOUT_SECS * 1000 < 20_000, 'remote watchdog fires before the local exec timeout')++ // Behavior through a real POSIX shell: healthy output passes through …+ const healthyStart = Date.now()+ const { stdout } = await execFileAsync('sh', ['-c', withRemoteTimeout('echo hello', 5)])+ const healthyElapsed = Date.now() - healthyStart++ assert.equal(stdout, 'hello\n')+ // … and returns promptly: the watchdog's orphaned `sleep` must not hold the+ // session pipes open until the full timeout on the healthy path.+ assert.ok(healthyElapsed < 4000, `healthy probe returned fast (took ${healthyElapsed}ms)`)++ // … a hung command is killed promptly with a non-zero exit …+ const start = Date.now()++ const err: any = await execFileAsync('sh', ['-c', withRemoteTimeout('sleep 30', 1)]).then(+ () => null,+ e => e+ )++ const elapsed = Date.now() - start++ assert.ok(err && err.code !== 0, 'hung command must exit non-zero')+ assert.ok(elapsed < 15000, `watchdog fired promptly instead of waiting 30s (took ${elapsed}ms)`)++ // … and no orphan is left behind.+ const { stdout: strays } = await execFileAsync('sh', ['-c', 'ps -eo args | grep "[s]leep 30" || true'])++ assert.equal(strays.trim(), '', 'killed probe left no orphan process')+})diff --git a/apps/desktop/electron/ssh-connection.ts b/apps/desktop/electron/ssh-connection.tsindex 9a11a193789..bfbe0977530 100644--- a/apps/desktop/electron/ssh-connection.ts+++ b/apps/desktop/electron/ssh-connection.ts@@ -39,6 +39,13 @@ import path from 'node:path'const DEFAULT_CONNECT_TIMEOUT_MS = 15_000const DEFAULT_EXEC_TIMEOUT_MS = 20_000const DEFAULT_FORWARD_TIMEOUT_MS = 15_000++// Remote-side watchdog for probe commands, in seconds. runSsh SIGKILLs the+// LOCAL ssh child on timeout, but the remote command keeps running as an+// orphan (ppid=1) — a hung remote CLI (e.g. a wedged `hermes --version`)+// accumulates orphans that busy-loop (#110478). Kept under+// DEFAULT_EXEC_TIMEOUT_MS so the remote kill lands before the local timeout.+const REMOTE_PROBE_TIMEOUT_SECS = 15// No-mux tunnels are one `ssh -N -L` child each; a transient child death// (network blip, sshd restart, laptop resume) used to instantly poison// isAlive() and cascade upstream into a full teardown that SIGTERM'd a@@ -321,6 +328,38 @@ function buildInteractiveSshArgs(conn, remoteCwd, connectTimeoutMs?, remoteCommareturn args}+// Wrap a remote probe command in a POSIX watchdog so a hung remote CLI is+// killed REMOTELY after `timeoutSecs` instead of orphaning when the local ssh+// child is SIGKILLed (#110478). Pure POSIX sh (dash, macOS sh) — deliberately+// not GNU `timeout`, which macOS remotes do not ship.+//+// The wrapped command must be a SINGLE command: the watchdog kills its direct+// child, so the exact invocation that can hang must be the direct child —+// a hung grandchild of a compound wrapper would orphan anyway. (The ownership+// probe nests the watchdog around the inner `serve --help` inside its+// `$( ... )` for this reason; note the load-bearing space in `$( (`.)+// The wrapped command keeps its stdout; the shell exits non-zero when the+// watchdog fires and the probe's existing failure path handles it.+//+// The sleeper's stdio is detached (</dev/null >/dev/null 2>&1): killing the+// sleeper subshell orphans its `sleep` grandchild, and an orphan holding the+// session pipes would keep the ssh channel open until the full timeout even on+// the healthy path. Detached, the orphan is a benign self-reaping `sleep`.+function withRemoteTimeout(remoteCommand, timeoutSecs = REMOTE_PROBE_TIMEOUT_SECS) {+ const secs =+ Number.isFinite(timeoutSecs) && timeoutSecs > 0+ ? Math.floor(timeoutSecs)+ : REMOTE_PROBE_TIMEOUT_SECS++ return (+ `(${remoteCommand}) </dev/null & __htp=$!; ` ++ `(sleep ${secs} </dev/null >/dev/null 2>&1; kill -9 $__htp 2>/dev/null) & __htw=$!; ` ++ `wait $__htp; __htrc=$?; ` ++ `kill $__htw 2>/dev/null; wait $__htw 2>/dev/null; ` ++ `exit $__htrc`+ )+}+// Bind the local end to 127.0.0.1 ONLY — never 0.0.0.0 — so the tunnel does not// re-expose the remote dashboard to the client's LAN.function forwardSpec(localPort, remotePort, remoteHost = '127.0.0.1') {@@ -1137,6 +1176,7 @@ export {hostArgs,pickLocalPort,redactSecrets,+ REMOTE_PROBE_TIMEOUT_SECS,runSsh,SSH_ERROR,SshConnection,@@ -1144,5 +1184,6 @@ export {stopTunnelChild,target,validateKeyPath,- validateSshTarget+ validateSshTarget,+ withRemoteTimeout}