Skip to content

The agent that grows with you

fix(update): respawn a manual dashboard through the current install's entry

liuhao1024e317693749f9
diff --git a/hermes_cli/main_dashboard.py b/hermes_cli/main_dashboard.py
index 150bb117f33..d06e0dc7437 100644
--- a/hermes_cli/main_dashboard.py
+++ b/hermes_cli/main_dashboard.py
@@ -10,6 +10,7 @@ import re
import shlex
import subprocess
import sys
+import time
from pathlib import Path
from typing import NoReturn
@@ -376,6 +377,32 @@ def _dashboard_cmdline_for_pid(pid: int) -> list[str] | None:
return None
+_RESPAWN_LIVENESS_GRACE_SECONDS = 1.0
+
+
+def _respawnable_command_for_current_install(argv: list[str]) -> list[str]:
+ """Collapse a captured ``[interpreter, launcher, ...]`` argv onto the running install.
+
+ A pre-PM-takeover install left ``~/.local/bin/hermes`` as a symlink to a Python console
+ script, so the kernel recorded a manual backend as
+ ``[<old venv python>, <launcher path>, dashboard, ...]``. The takeover then rewrote that
+ launcher into a POSIX shell shim, and replaying the captured argv verbatim asks the old
+ interpreter to parse a shell script — the child dies at parse time while the updater
+ prints ``✓ restarted`` (#124778). Any ``python <entry>`` pair is rebuilt against the
+ ``hermes`` entry of the code that is running now; other shapes replay unchanged.
+ """
+ interpreter_name = os.path.basename(argv[0]) if argv else ""
+ if len(argv) <= 2 or not interpreter_name.startswith("python") or argv[1].startswith("-"):
+ return list(argv)
+ entry = Path(__file__).resolve().parents[1] / "hermes"
+ if not entry.is_file():
+ return list(argv)
+ current_interpreter = sys.executable or argv[0]
+ rebuilt = [current_interpreter, str(entry)]
+ rebuilt.extend(argv[2:])
+ return rebuilt
+
+
def _respawn_dashboard_processes(commands: list[list[str]]) -> list[list[str]]:
"""Respawn manually-started dashboards after ``hermes update``, detached, logging to
``logs/dashboard-restart.log``; returns the argvs that failed to spawn. Callers pre-filter via
@@ -385,6 +412,7 @@ def _respawn_dashboard_processes(commands: list[list[str]]) -> list[list[str]]:
"""
from hermes_constants import get_hermes_home
respawned: list[list[str]] = []
+ spawned: list[tuple[list[str], "subprocess.Popen"]] = []
failed: list[tuple[list[str], str]] = []
log_path = get_hermes_home() / "logs" / "dashboard-restart.log"
with contextlib.suppress(OSError):
@@ -392,18 +420,30 @@ def _respawn_dashboard_processes(commands: list[list[str]]) -> list[list[str]]:
for command in commands:
try:
+ command = _respawnable_command_for_current_install(command)
# Keep restarted dashboards headless; reopening a browser after a
# background update is noisy and fails in SSH/headless sessions.
if "dashboard" in command and "--no-open" not in command:
command = [*command, "--no-open"]
with open(log_path, "ab") as log_f:
- subprocess.Popen(
+ proc = subprocess.Popen(
command, stdin=subprocess.DEVNULL, stdout=log_f, stderr=subprocess.STDOUT,
start_new_session=True, close_fds=True)
- respawned.append(command)
+ spawned.append((command, proc))
except (OSError, ValueError) as exc:
failed.append((command, str(exc)))
+ # A respawned backend is a resident server: one that exits within the grace
+ # window died at startup (SyntaxError on a stale argv, port already bound,
+ # ...) and must surface as a failure, not as ``✓ restarted`` (#124778).
+ time.sleep(_RESPAWN_LIVENESS_GRACE_SECONDS)
+ for command, proc in spawned:
+ if proc.poll() is None:
+ respawned.append(command)
+ else:
+ failed.append((command, f"child exited during the first "
+ f"{_RESPAWN_LIVENESS_GRACE_SECONDS:.0f}s (code {proc.returncode})"))
+
for command in respawned:
print(f" ✓ restarted: {shlex.join(command)}")
for command, err_msg in failed:
diff --git a/tests/hermes_cli/test_old_updater_takeover.py b/tests/hermes_cli/test_old_updater_takeover.py
index 405a41bd3d6..465e5ec5c14 100644
--- a/tests/hermes_cli/test_old_updater_takeover.py
+++ b/tests/hermes_cli/test_old_updater_takeover.py
@@ -317,14 +317,17 @@ def test_serve_resume_child_reuses_respawn_without_updater_or_supervisors(tmp_pa
"stopped_serves": {"pending": True, "entries": entries}}))
program = tmp_path / "probe.py"
program.write_text(
- "import json, os, runpy, subprocess, sys\nfrom pathlib import Path\n"
+ "import json, os, runpy, subprocess, sys, time\nfrom pathlib import Path\n"
"calls = []\n"
+ "time.sleep = lambda *_: None\n"
"def forbidden(*args, **kwargs):\n raise AssertionError('updater/process control ran')\n"
+ "class _Proc:\n def poll(self):\n return None\n"
"def spawn(command, **kwargs):\n"
" assert kwargs['start_new_session'] is True\n"
" assert kwargs['stdin'] == subprocess.DEVNULL\n"
" calls.append(command)\n"
f" if {spawn_fails!r}:\n raise OSError('probe spawn failed')\n"
+ " return _Proc()\n"
"subprocess.Popen = spawn\nsubprocess.run = os.system = os.kill = forbidden\n"
f"sys.argv = [{str(root / 'hermes_cli/update_serve_resume.py')!r}, {str(context)!r}, {str(result_path)!r}]\n"
"try:\n runpy.run_path(sys.argv[0], run_name='__main__')\n"
diff --git a/tests/hermes_cli/test_update_stale_dashboard.py b/tests/hermes_cli/test_update_stale_dashboard.py
index 92ec16e3b78..d7175824b46 100644
--- a/tests/hermes_cli/test_update_stale_dashboard.py
+++ b/tests/hermes_cli/test_update_stale_dashboard.py
@@ -16,6 +16,7 @@ from __future__ import annotations
import json
import os
import sys
+from pathlib import Path
from unittest.mock import patch, MagicMock
import pytest
@@ -496,7 +497,11 @@ class TestManualBackendRespawn:
def __init__(self, cmd, **kwargs):
spawned.append(list(cmd))
- with patch.object(live.subprocess, "Popen", _FakePopen):
+ def poll(self):
+ return None
+
+ with patch.object(live.subprocess, "Popen", _FakePopen), \
+ patch.object(live.time, "sleep"):
failed = live._respawn_dashboard_processes([
["hermes", "dashboard", "--port", "8300"],
["hermes", "serve", "--host", "0.0.0.0"],
@@ -510,11 +515,86 @@ class TestManualBackendRespawn:
live = self._live()
monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
- with patch.object(live.subprocess, "Popen", side_effect=OSError("no such file")):
+ with patch.object(live.subprocess, "Popen", side_effect=OSError("no such file")), \
+ patch.object(live.time, "sleep"):
failed = live._respawn_dashboard_processes([["hermes", "serve"]])
assert failed == [["hermes", "serve"]]
+ def test_pre_takeover_interpreter_launcher_argv_is_rebuilt(self, tmp_path, monkeypatch):
+ """A kernel-captured ``[old venv python, launcher, ...]`` argv is respawned through
+ the running install's interpreter + ``hermes`` entry instead of being replayed
+ verbatim after the PM takeover rewrote the launcher into a shell shim (#124778)."""
+ live = self._live()
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ spawned: list[list[str]] = []
+
+ class _FakePopen:
+ def __init__(self, cmd, **kwargs):
+ spawned.append(list(cmd))
+
+ def poll(self):
+ return None
+
+ captured = [
+ "/old/venv/bin/python", "/home/u/.local/bin/hermes",
+ "dashboard", "--no-open", "--host", "127.0.0.1", "--port", "34553",
+ ]
+ with patch.object(live.subprocess, "Popen", _FakePopen), \
+ patch.object(live.time, "sleep"):
+ failed = live._respawn_dashboard_processes([captured])
+
+ assert failed == []
+ entry = Path(live.__file__).resolve().parents[1] / "hermes"
+ assert spawned == [[sys.executable, str(entry),
+ "dashboard", "--no-open", "--host", "127.0.0.1", "--port", "34553"]]
+
+ def test_child_exiting_within_the_grace_window_is_a_reported_failure(
+ self, tmp_path, monkeypatch, capsys):
+ """A respawn that dies at once (parse error on a stale argv, port already bound)
+ must surface as a failure, never as ``✓ restarted`` (#124778)."""
+ live = self._live()
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+
+ class _DyingPopen:
+ returncode = 1
+
+ def __init__(self, cmd, **kwargs):
+ pass
+
+ def poll(self):
+ return 1
+
+ with patch.object(live.subprocess, "Popen", _DyingPopen), \
+ patch.object(live.time, "sleep"):
+ failed = live._respawn_dashboard_processes([["hermes", "dashboard", "--port", "8300"]])
+
+ out = capsys.readouterr().out
+ assert failed == [["hermes", "dashboard", "--port", "8300", "--no-open"]]
+ assert "✓ restarted" not in out
+ assert "✗ failed to restart" in out
+
+ def test_python_dash_m_argv_shape_replays_unchanged(self, tmp_path, monkeypatch):
+ """``[python, -m, hermes_cli.main, ...]`` is not an interpreter+launcher pair;
+ only that pair is rebuilt, so module-shaped argvs keep replaying verbatim."""
+ live = self._live()
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ spawned: list[list[str]] = []
+
+ class _FakePopen:
+ def __init__(self, cmd, **kwargs):
+ spawned.append(list(cmd))
+
+ def poll(self):
+ return None
+
+ captured = ["python", "-m", "hermes_cli.main", "serve", "--port", "8400"]
+ with patch.object(live.subprocess, "Popen", _FakePopen), \
+ patch.object(live.time, "sleep"):
+ live._respawn_dashboard_processes([captured])
+
+ assert spawned == [captured]
+
class TestFilterDashboardRespawnCandidates:
"""Unit tests for respawn filtering / dedupe / orphan skip (#78821)."""