The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): reap orphaned serve backends via parent-death watchdog + group-kill
XiaoZAZAa9a0648f495f
diff --git a/apps/desktop/electron/backend-child.ts b/apps/desktop/electron/backend-child.tsindex 874419b14dd..df720be5916 100644--- a/apps/desktop/electron/backend-child.ts+++ b/apps/desktop/electron/backend-child.ts@@ -6,15 +6,18 @@* Node's `child.kill()` only signals the direct child. On Windows a backend* that spawned its own grandchildren (a `hermes` REPL, a pty terminal* session, the gateway) survives a plain SIGTERM and keeps files (e.g. the- * venv shim) locked. So on Windows we tree-kill via `forceKillProcessTree`;- * everywhere else a plain SIGTERM is correct and sufficient (POSIX has no- * mandatory locks, and the backend is not spawned detached so there's no- * process-group to negative-pid-kill).+ * venv shim) locked. So on Windows we tree-kill via `forceKillProcessTree`.+ *+ * On POSIX the backend IS spawned into its own session/process-group+ * (start_new_session=True), so `child.kill('SIGTERM')` would only reach the+ * backend and orphan its MCP grandchildren (the leak in #serve-orphans). We+ * signal the whole group via `process.kill(-pid, ...)` instead, falling back+ * to the direct child if the group send fails.** Extracted into its own dependency-free module (no electron import) so the- * SIGTERM-vs-tree-kill branching can be asserted directly with a fake child- * object and a spy `forceKillProcessTree`, instead of grepping main.ts source- * text for the function body.+ * tree-kill / group-kill branching can be asserted directly with a fake child+ * object and spy kill functions, instead of grepping main.ts source text for+ * the function body.*/export interface StopBackendChildDeps {@@ -22,6 +25,12 @@ export interface StopBackendChildDeps {isWindows?: boolean/** Windows tree-kill implementation (real: taskkill /T /F via execFileSync). */forceKillProcessTree: (pid: number) => void+ /**+ * POSIX group-signal implementation. Real: process.kill(-pgid, signal).+ * Injectable so the negative-pid group send is asserted in tests without a+ * live process group. Defaults to process.kill.+ */+ killGroup?: (pgid: number, signal: string) => void}export interface StopBackendTreesForUpdateDeps {@@ -52,10 +61,19 @@ export function stopBackendChild(child: KillableChild | null | undefined, deps:}const isWindows = deps.isWindows ?? process.platform === 'win32'+ const killGroup = deps.killGroup ?? ((pgid: number, signal: string) => process.kill(pgid, signal))try {if (isWindows && Number.isInteger(child.pid)) {deps.forceKillProcessTree(child.pid as number)+ } else if (Number.isInteger(child.pid)) {+ // POSIX: pgid == pid (start_new_session). Signal the whole group so MCP+ // grandchildren die too; fall back to the direct child on failure.+ try {+ killGroup(-(child.pid as number), 'SIGTERM')+ } catch {+ child.kill('SIGTERM')+ }} else {child.kill('SIGTERM')}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 643766c737c..d1f3dd1b49b 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -8071,6 +8071,14 @@ async function waitForBackendExit(child, timeoutMs = 5000) {try {if (IS_WINDOWS && Number.isInteger(child.pid)) {forceKillProcessTree(child.pid)+ } else if (Number.isInteger(child.pid)) {+ // POSIX: SIGKILL the whole group (pgid==pid, start_new_session) so+ // MCP grandchildren die with the backend. Fall back to the child.+ try {+ process.kill(-child.pid, 'SIGKILL')+ } catch {+ child.kill('SIGKILL')+ }} else {child.kill('SIGKILL')}@@ -8298,6 +8306,11 @@ async function spawnPoolBackend(profile, entry) {// Marks this dashboard backend as desktop-spawned so it runs the cron// scheduler tick loop (the gateway isn't running under the app).HERMES_DESKTOP: '1',+ // Our PID so the backend's parent-death watchdog self-exits if we die+ // uncleanly (crash / SIGKILL / update handoff) instead of leaking a+ // serving backend + its MCP child subtree. See web_server.py+ // _start_parent_death_watchdog.+ HERMES_PARENT_PID: String(process.pid),HERMES_WEB_DIST: webDist,...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})},@@ -8591,6 +8604,11 @@ async function startHermes() {// Marks this dashboard backend as desktop-spawned so it runs the cron// scheduler tick loop (the gateway isn't running under the app).HERMES_DESKTOP: '1',+ // Our PID so the backend's parent-death watchdog self-exits if we die+ // uncleanly (crash / SIGKILL / update handoff) instead of leaking a+ // serving backend + its MCP child subtree. See web_server.py+ // _start_parent_death_watchdog.+ HERMES_PARENT_PID: String(process.pid),HERMES_WEB_DIST: webDist,...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})},diff --git a/apps/desktop/electron/windows-child-options.test.ts b/apps/desktop/electron/windows-child-options.test.tsindex 3e6d7daccdc..a68b9dfc5e7 100644--- a/apps/desktop/electron/windows-child-options.test.ts+++ b/apps/desktop/electron/windows-child-options.test.ts@@ -65,19 +65,36 @@ test('stopBackendChild tree-kills on Windows when the child has a pid', () => {assert.deepEqual(calls, [], 'SIGTERM must not be sent when the Windows tree-kill path is taken')})-test('stopBackendChild sends SIGTERM on non-Windows platforms', () => {+test('stopBackendChild group-SIGTERMs on POSIX (negative pgid) when the child has a pid', () => {const { child, calls } = makeChild({ pid: 4242 })const treeKillCalls: number[] = []+ const groupKills: Array<[number, string]> = []stopBackendChild(child, {forceKillProcessTree: (pid: number) => treeKillCalls.push(pid),- isWindows: false+ isWindows: false,+ killGroup: (pgid, signal) => groupKills.push([pgid, signal])})- assert.deepEqual(calls, ['SIGTERM'])+ assert.deepEqual(groupKills, [[-4242, 'SIGTERM']], 'must signal the whole process group')+ assert.deepEqual(calls, [], 'direct child.kill must not run when the group send succeeds')assert.deepEqual(treeKillCalls, [], 'tree-kill must not run off Windows')})+test('stopBackendChild falls back to direct SIGTERM on POSIX when the group send throws', () => {+ const { child, calls } = makeChild({ pid: 4242 })++ stopBackendChild(child, {+ forceKillProcessTree: () => {},+ isWindows: false,+ killGroup: () => {+ throw new Error('ESRCH: no such process group')+ }+ })++ assert.deepEqual(calls, ['SIGTERM'], 'must fall back to signalling the direct child')+})+test('stopBackendChild falls back to SIGTERM on Windows when the pid is not an integer', () => {const { child, calls } = makeChild({ pid: null })const treeKillCalls: number[] = []diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 197c7c193bc..5bc2d6472ad 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -17639,6 +17639,49 @@ def _maybe_open_browser(threading.Thread(target=_open, daemon=True).start()+def _is_serve_orphaned(original_ppid: int, getppid=os.getppid) -> bool:+ """True when this process lost its original spawning parent (ppid changed)."""+ return getppid() != original_ppid+++def _start_parent_death_watchdog() -> None:+ """Exit when the desktop parent that spawned this backend dies.++ The desktop passes its own PID via HERMES_PARENT_PID. When that process+ vanishes (crash, SIGKILL, update handoff exiting before it reaps us) this+ orphaned backend would otherwise keep serving forever and leak its MCP+ child subtree. os._exit propagates to the MCP watchdogs parented here.++ No-op for standalone `hermes serve` (env unset). Poll interval tunable via+ HERMES_SERVE_WATCHDOG_POLL_S.+ """+ raw = os.environ.get("HERMES_PARENT_PID")+ if not raw:+ return+ try:+ original_ppid = int(raw)+ except (TypeError, ValueError):+ return+ try:+ poll = max(0.5, float(os.environ.get("HERMES_SERVE_WATCHDOG_POLL_S", "2.0")))+ except (TypeError, ValueError):+ poll = 2.0++ def _loop() -> None:+ while not _is_serve_orphaned(original_ppid):+ time.sleep(poll)+ os._exit(0)++ threading.Thread(target=_loop, daemon=True, name="serve-parent-watchdog").start()+++def _demo() -> None:+ # orphan iff current ppid differs from the recorded spawning parent+ assert _is_serve_orphaned(999999999, getppid=lambda: 1) is True+ assert _is_serve_orphaned(42, getppid=lambda: 42) is False+ print("web_server parent-death watchdog self-check: OK")++def start_server(host: str = "127.0.0.1",port: int = 9119,@@ -17844,6 +17887,16 @@ def start_server(if server.should_exit:return+ # Parent-death watchdog. The desktop spawns us and is supposed to+ # SIGTERM us on quit, but a crash / SIGKILL / update handoff that+ # exits before reaping leaves us orphaned (ppid→1) yet still+ # serving — leaking the whole backend + its MCP child subtree+ # (each MCP watchdog is parented to THIS process, so os._exit here+ # cascades their teardown). Same pattern as+ # tui_gateway/slash_worker.py::_start_parent_death_watchdog. No-op+ # for standalone `hermes serve` (no HERMES_PARENT_PID env).+ _start_parent_death_watchdog()+actual_port = _read_bound_port(server, fallback=port)app.state.bound_port = actual_port