Skip to content

The agent that grows with you

fix(dashboard): stop sweep spares the caller's wrapper shell

Konstantin Khlopkovab55bbc389ad
diff --git a/hermes_cli/dashboard_procs.py b/hermes_cli/dashboard_procs.py
index 7d2670b78d0..51366807a4a 100644
--- a/hermes_cli/dashboard_procs.py
+++ b/hermes_cli/dashboard_procs.py
@@ -252,6 +252,79 @@ def _exclude_pids_from_env() -> set[int]:
return out
+#: Executables that only *carry* a hermes command line. A process headed by one of these
+#: never serves traffic itself; when its argv matches the dashboard patterns it is a
+#: wrapper around the command (``bash -c 'hermes dashboard --stop'``), not a backend.
+_WRAPPER_HEAD_COMMANDS = frozenset({
+ "ash", "bash", "csh", "dash", "fish", "ksh", "sh", "tcsh", "zsh",
+ "env", "nohup", "nice", "stdbuf", "timeout", "watch", "xargs",
+ "screen", "tmux", "sudo",
+})
+
+
+def _caller_ancestor_pids() -> set[int]:
+ """PIDs of THIS process's ancestors (self excluded), best-effort; empty on any failure.
+
+ ``--stop`` and the update sweep must never kill the process tree they were invoked
+ from. psutil is primary; the ``/proc`` walk keeps the answer when psutil is unusable.
+ """
+ try:
+ import psutil
+
+ return {p.pid for p in psutil.Process().parents()}
+ except Exception:
+ pass
+ ancestors: set[int] = set()
+ cur = os.getpid()
+ for _ in range(2048): # cycle / corrupt-PPid guard
+ try:
+ status_text = Path(f"/proc/{cur}/status").read_text(
+ encoding="utf-8", errors="replace")
+ for line in status_text.splitlines():
+ if line.startswith("PPid:"):
+ cur = int(line.split()[1])
+ break
+ else:
+ return ancestors
+ except (OSError, ValueError, IndexError):
+ return ancestors
+ if cur <= 1:
+ return ancestors
+ ancestors.add(cur)
+ return ancestors
+
+
+def _argv_head_command(pid: int) -> str | None:
+ """Basename of *pid*'s first argv token, best-effort; ``None`` when unreadable."""
+ try:
+ import psutil
+
+ argv = psutil.Process(pid).cmdline()
+ if argv:
+ return os.path.basename(str(argv[0]))
+ except Exception:
+ pass
+ try:
+ raw = Path(f"/proc/{pid}/cmdline").read_bytes()
+ except OSError:
+ return None
+ head = raw.split(b"\x00", 1)[0].decode("utf-8", "replace")
+ return head.rsplit("/", 1)[-1] or None
+
+
+def _is_caller_wrapper_shell(pid: int, ancestors: set[int]) -> bool:
+ """True when *pid* is a caller ancestor headed by a wrapper executable.
+
+ Root selection is a substring match, so the shell a ``--stop`` was typed into (or a
+ ``bash -c 'hermes dashboard --stop'`` wrapper) matches on its own argv. Ancestor alone
+ is not a spare: the backend hosting a shell-escaped TUI is also the caller's ancestor
+ and must stay stoppable — only a wrapper-headed ancestor is spared.
+ """
+ if pid not in ancestors:
+ return False
+ return (_argv_head_command(pid) or "") in _WRAPPER_HEAD_COMMANDS
+
+
def _kill_pids_windows(pids: list[int], killed: list[int], failed: list[tuple[int, str]]) -> None:
"""``taskkill /F`` each PID after re-verifying its identity."""
from gateway.status import get_process_start_time
diff --git a/hermes_cli/main_dashboard.py b/hermes_cli/main_dashboard.py
index fd3187ddab1..8a74aea53b4 100644
--- a/hermes_cli/main_dashboard.py
+++ b/hermes_cli/main_dashboard.py
@@ -20,8 +20,16 @@ _PRE_BUILD_HINT = " Pre-build first: npm install --workspace web && npm run bu
def _find_stale_dashboard_pids(*, exclude_pids: set[int] | None = None) -> list[int]:
"""Return PIDs of stale ``dashboard``/``serve`` processes for update cleanup."""
- from hermes_cli.dashboard_procs import _scan_dashboard_processes
- return [pid for pid, _cmd in _scan_dashboard_processes(exclude_pids=exclude_pids)]
+ from hermes_cli.dashboard_procs import (
+ _caller_ancestor_pids,
+ _is_caller_wrapper_shell,
+ _scan_dashboard_processes,
+ )
+ pids = [pid for pid, _cmd in _scan_dashboard_processes(exclude_pids=exclude_pids)]
+ # The argv substring scan also selects the caller's own wrapper shell (``bash -c
+ # 'hermes dashboard --stop'``); killing it takes down the invoking terminal.
+ ancestors = _caller_ancestor_pids()
+ return [pid for pid in pids if not _is_caller_wrapper_shell(pid, ancestors)]
def _parse_dashboard_runtime(command: str) -> tuple[str, str, int] | None:
diff --git a/tests/hermes_cli/test_dashboard_stop_spare_caller.py b/tests/hermes_cli/test_dashboard_stop_spare_caller.py
new file mode 100644
index 00000000000..08114bf17f2
--- /dev/null
+++ b/tests/hermes_cli/test_dashboard_stop_spare_caller.py
@@ -0,0 +1,125 @@
+"""Root selection for ``dashboard --stop`` / update cleanup must spare the caller.
+
+The argv substring scan (``_DASHBOARD_PATTERNS``) matches any process whose command
+line merely mentions ``hermes dashboard`` / ``hermes serve`` — including the shell the
+``--stop`` was typed into (``bash -c 'hermes dashboard --stop'``). Killing it takes down
+the invoking terminal; the historical fix for the hosted-TUI case is descendant hygiene
+(#113819), which is orthogonal to root selection.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import patch
+
+from hermes_cli.dashboard_procs import (
+ _caller_ancestor_pids,
+ _is_caller_wrapper_shell,
+)
+from hermes_cli.main_dashboard import _find_stale_dashboard_pids
+
+
+class TestCallerAncestorPids:
+ def test_returns_parents_without_self(self):
+ # Can't assert exact pids portably; the invariant that matters is that the
+ # caller itself is never in the spare set (chain roots 0/1 are harmless —
+ # they never match the dashboard argv patterns).
+ import os
+
+ ancestors = _caller_ancestor_pids()
+ assert isinstance(ancestors, set)
+ assert all(isinstance(p, int) for p in ancestors)
+ assert os.getpid() not in ancestors
+
+ def test_psutil_failure_falls_back_to_proc(self):
+ import sys
+
+ real_import = (
+ __builtins__["__import__"]
+ if isinstance(__builtins__, dict)
+ else __builtins__.__import__
+ )
+
+ def fake_import(name, *args, **kwargs):
+ if name == "psutil":
+ raise ImportError("no psutil")
+ return real_import(name, *args, **kwargs)
+
+ if sys.platform == "win32":
+ # /proc walk unavailable: empty set is the documented best-effort answer.
+ with patch("builtins.__import__", side_effect=fake_import):
+ assert _caller_ancestor_pids() == set()
+ else:
+ with patch("builtins.__import__", side_effect=fake_import):
+ assert isinstance(_caller_ancestor_pids(), set)
+
+
+class TestIsCallerWrapperShell:
+ def test_wrapper_ancestor_is_spared(self):
+ # bash-headed ancestor carrying the dashboard argv in its own cmdline.
+ with patch(
+ "hermes_cli.dashboard_procs._argv_head_command", return_value="bash"
+ ):
+ assert _is_caller_wrapper_shell(4242, {4242}) is True
+
+ def test_backend_ancestor_stays_killed(self):
+ # A python-headed ancestor is a real backend (hosted TUI case): must stay
+ # stoppable, otherwise `--stop` from inside the dashboard's own TUI breaks.
+ with patch(
+ "hermes_cli.dashboard_procs._argv_head_command", return_value="python3.12"
+ ):
+ assert _is_caller_wrapper_shell(4242, {4242}) is False
+
+ def test_wrapper_non_ancestor_stays_killed(self):
+ # Same argv shape, but NOT the caller's ancestor: a genuinely unrelated
+ # wrapper (e.g. another user's `bash -c 'hermes serve'`) is still a target.
+ with patch(
+ "hermes_cli.dashboard_procs._argv_head_command", return_value="bash"
+ ):
+ assert _is_caller_wrapper_shell(9999, {4242}) is False
+
+ def test_unreadable_argv_head_is_not_spared(self):
+ # None (unreadable /proc) must not compare equal to anything in the set.
+ with patch("hermes_cli.dashboard_procs._argv_head_command", return_value=None):
+ assert _is_caller_wrapper_shell(4242, {4242}) is False
+
+
+class TestFindStaleDashboardPidsSparesCaller:
+ def test_scan_results_are_filtered(self, capsys):
+ processes = [
+ (111, "/opt/hermes/bin/python hermes dashboard --port 9119"),
+ (222, "bash -c hermes dashboard --stop"),
+ ]
+ with (
+ patch(
+ "hermes_cli.dashboard_procs._scan_dashboard_processes",
+ return_value=processes,
+ ) as scan,
+ patch(
+ "hermes_cli.dashboard_procs._caller_ancestor_pids", return_value={222}
+ ),
+ patch("hermes_cli.dashboard_procs._argv_head_command", return_value="bash"),
+ ):
+ result = _find_stale_dashboard_pids()
+ scan.assert_called_once()
+ assert result == [111]
+
+
+class TestWrapperHeadCommands:
+ def test_set_covers_common_shells_and_carriers(self):
+ from hermes_cli.dashboard_procs import _WRAPPER_HEAD_COMMANDS
+
+ for head in (
+ "bash",
+ "sh",
+ "zsh",
+ "fish",
+ "nohup",
+ "env",
+ "timeout",
+ "sudo",
+ "tmux",
+ ):
+ assert head in _WRAPPER_HEAD_COMMANDS
+ # A backend head must never be in the set.
+ for head in ("python", "python3", "python3.12", "hermes", "uv", "uvx"):
+ assert head not in _WRAPPER_HEAD_COMMANDS