The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): a launchd-supervised backend restarts through launchd, never as a detached respawn
John Paul Soliva99b727bd96ae
diff --git a/hermes_cli/dashboard_procs.py b/hermes_cli/dashboard_procs.pyindex dd58c7c756f..88c7ba46517 100644--- a/hermes_cli/dashboard_procs.py+++ b/hermes_cli/dashboard_procs.py@@ -345,13 +345,24 @@ def _kill_stale_dashboard_processes(# Snapshot systemd unit/cgroup and argv BEFORE killing (the cgroup dies with the process).pid_cgroup: dict[int, str | None] = {}pid_service: dict[int, str | None] = {}+ pid_launchd: dict[int, tuple[str, str]] = {}pid_cmdline: dict[int, list[str]] = {}pid_home: dict[int, str | None] = {}if restart_managed and sys.platform != "win32":+ # macOS: a backend supervised by a launchd job (LaunchAgent / LaunchDaemon) must come back+ # through launchd, never as a detached argv respawn — the respawn holds the job's port, the+ # job then fails every KeepAlive restart with "port already in use", and the running+ # backend is left unsupervised. Snapshot the loaded jobs once, before the kill.+ launchd_jobs = _dash._loaded_launchd_backend_jobs()for pid in pids:pid_cgroup[pid] = _dash._get_pid_cgroup_path(pid)pid_service[pid] = _dash._get_systemd_service_for_pid(pid)- if not pid_service[pid] and (cmdline := _dash._dashboard_cmdline_for_pid(pid)):+ if pid_service[pid]:+ continue+ cmdline = _dash._dashboard_cmdline_for_pid(pid)+ if launchd_jobs and (job := _dash._launchd_job_owning_backend(pid, cmdline, launchd_jobs)):+ pid_launchd[pid] = job+ elif cmdline:# Manual process: exact argv + HERMES_HOME for the respawn and its profile cap.# Manually-started process: preserve its exact argv so we can respawn it after the update# (#40449, #68934). Snapshot HERMES_HOME before the kill so per-profile caps still work@@ -372,7 +383,8 @@ def _kill_stale_dashboard_processes(for pid, err_msg in failed:print(f" ✗ failed to stop PID {pid}: {err_msg}")if killed and restart_managed:- unrecovered = _restart_killed_backends(killed, pid_service, pid_cgroup, pid_cmdline, pid_home)+ unrecovered = _restart_killed_backends(+ killed, pid_service, pid_cgroup, pid_cmdline, pid_home, pid_launchd=pid_launchd)else:unrecovered = list(killed)if killed:@@ -383,9 +395,11 @@ def _kill_stale_dashboard_processes(def _restart_killed_backends(killed: list[int], pid_service: dict[int, str | None], pid_cgroup: dict[int, str | None],- pid_cmdline: dict[int, list[str]], pid_home: dict[int, str | None]) -> list[int]:- """Update path: restart systemd units, respawn manual argv (detached, headless, logged to- logs/dashboard-restart.log; one per profile, no ``--port 0``). Returns PIDs not brought back."""+ pid_cmdline: dict[int, list[str]], pid_home: dict[int, str | None], *,+ pid_launchd: dict[int, tuple[str, str]] | None = None) -> list[int]:+ """Update path: restart systemd units, kickstart launchd jobs (macOS), respawn manual argv+ (detached, headless, logged to logs/dashboard-restart.log; one per profile, no ``--port 0``).+ Returns PIDs not brought back."""# Two categories: Without this, a remote backend (hermes serve) under Restart=on-failure never comes# back after our clean SIGTERM, and the Desktop can't reconnect (#68934). Filtered so Desktop# ``serve|dashboard --port 0`` backends are not resurrected and duplicates collapse to one per profile@@ -397,6 +411,7 @@ def _restart_killed_backends(respawn_candidates: list[tuple[int, list[str], str | None]] = []for pid in killed:svc_name = pid_service.get(pid)+ launchd_job = (pid_launchd or {}).get(pid)if svc_name:if svc_name in seen_services:continue@@ -406,6 +421,19 @@ def _restart_killed_backends(else:failed_restarts.append((svc_name, "systemctl restart returned non-zero"))unrecovered.append(pid)+ elif launchd_job:+ # launchd owns the backend: the job brings it back (KeepAlive, or the kickstart below);+ # an argv respawn would sit on the job's port and leave it failing forever.+ domain, label = launchd_job+ target = f"{domain}/{label}"+ if target in seen_services:+ continue+ seen_services.add(target)+ if _dash._try_kickstart_launchd_job(domain, label):+ print(f" ✓ restarted launchd job {target}")+ else:+ failed_restarts.append((target, f"launchctl kickstart failed; run: launchctl kickstart -k {target}"))+ unrecovered.append(pid)elif pid in pid_cmdline:respawn_candidates.append((pid, pid_cmdline[pid], pid_home.get(pid)))else:diff --git a/hermes_cli/main_dashboard.py b/hermes_cli/main_dashboard.pyindex c82d62099b9..7c152ad78ff 100644--- a/hermes_cli/main_dashboard.py+++ b/hermes_cli/main_dashboard.py@@ -210,6 +210,87 @@ def _try_restart_systemd_service(svc_name: str, cgroup_path: str | None = None)return False+# launchd plist directories that can supervise a ``hermes dashboard`` / ``hermes serve`` backend on+# macOS, with the launchctl domain their jobs load into (LaunchAgents: ``gui/<uid>`` or ``user/<uid>``,+# probed per label like the gateway helpers; LaunchDaemons: ``system``). Both LaunchAgents dirs are+# per-user domains, so they share the ``agent`` kind.+def _launchd_plist_dirs() -> list[tuple[str, Path]]:+ return [+ ("agent", Path.home() / "Library" / "LaunchAgents"),+ ("agent", Path("/Library/LaunchAgents")),+ ("daemon", Path("/Library/LaunchDaemons")),+ ]+++def _loaded_launchd_backend_jobs(+ plist_dirs: list[tuple[str, Path]] | None = None,+) -> list[tuple[str, str, list[str], int | None]]:+ """``(domain, label, program_arguments, live_pid)`` for every LOADED launchd job whose+ ``ProgramArguments`` is a ``hermes dashboard`` / ``hermes serve`` backend. macOS only (empty+ elsewhere). Reads the plists (unreadable/malformed ones are skipped) and asks ``launchctl print``+ per candidate label — a job that is not loaded in any domain is not returned, so an operator's+ stale plist never claims a process."""+ if sys.platform != "darwin":+ return []+ import plistlib+ from hermes_cli.gateway import _launchd_print_service_pid+ uid = os.getuid() # windows-footgun: ok — darwin-only branch+ jobs: list[tuple[str, str, list[str], int | None]] = []+ for kind, plist_dir in (plist_dirs if plist_dirs is not None else _launchd_plist_dirs()):+ try:+ plists = sorted(plist_dir.glob("*.plist"))+ except OSError:+ continue+ for plist_path in plists:+ try:+ with open(plist_path, "rb") as f:+ data = plistlib.load(f)+ except (OSError, ValueError, plistlib.InvalidFileException):+ continue+ if not isinstance(data, dict):+ continue+ label = str(data.get("Label") or "").strip()+ args = data.get("ProgramArguments")+ if not label or not isinstance(args, list) or not args:+ continue+ argv = [str(a) for a in args]+ if _parse_dashboard_runtime(shlex.join(argv)) is None:+ continue+ domains = ("system",) if kind == "daemon" else (f"gui/{uid}", f"user/{uid}")+ for domain in domains:+ try:+ loaded, live_pid = _launchd_print_service_pid(domain, label)+ except _SYSTEMCTL_ERRORS:+ loaded, live_pid = False, None+ if loaded:+ jobs.append((domain, label, argv, live_pid))+ break+ return jobs+++def _launchd_job_owning_backend(+ pid: int, cmdline: list[str] | None, jobs: list[tuple[str, str, list[str], int | None]],+) -> tuple[str, str] | None:+ """``(domain, label)`` of the loaded launchd job that owns *pid*: launchd reports *pid* as the+ job's live process, OR the process runs the job's exact ``ProgramArguments`` — a detached copy of+ a supervised backend (an earlier respawn) holds the port the job needs, and respawning it again+ would only re-create that conflict. None when no loaded job claims the process."""+ for domain, label, argv, live_pid in jobs:+ if live_pid == pid or (cmdline is not None and list(cmdline) == argv):+ return (domain, label)+ return None+++def _try_kickstart_launchd_job(domain: str, label: str) -> bool:+ """``launchctl kickstart <domain>/<label>`` (no ``-k``: the process was already stopped, and a+ KeepAlive job may have respawned it — a kill would take that fresh process down). True on+ success; False on a non-zero exit or when launchctl is unavailable / wedged."""+ try:+ return _run_probe(["launchctl", "kickstart", f"{domain}/{label}"], timeout=30).returncode == 0+ except _SYSTEMCTL_ERRORS:+ return False++def _dashboard_cmdline_for_pid(pid: int) -> list[str] | None:"""Exact argv of a running process: ``/proc/<pid>/cmdline`` (Linux), ``ps -o command=`` + shlex(macOS), None on Windows (no graceful taskkill window; Desktop manages its backend)."""diff --git a/tests/hermes_cli/test_update_stale_dashboard.py b/tests/hermes_cli/test_update_stale_dashboard.pyindex a4da3d0ea19..32220c69fad 100644--- a/tests/hermes_cli/test_update_stale_dashboard.py+++ b/tests/hermes_cli/test_update_stale_dashboard.py@@ -929,3 +929,150 @@ class TestPostUpdateStaleModuleReload:assert "hermes_cli._subprocess_compat" in reloadedassert "hermes_cli.dashboard_procs" in reloaded+++class TestLaunchdSupervisedBackends:+ """macOS: a backend supervised by a launchd job must come back through launchd. Respawning+ its argv detached leaves a copy holding the job's port, so every KeepAlive restart of the job+ fails with "port already in use" and the backend that IS running is no longer supervised."""++ ARGV = [+ "/opt/hermes/venv/bin/python", "-m", "hermes_cli.main",+ "dashboard", "--host", "0.0.0.0", "--port", "9119", "--no-open", "--skip-build",+ ]++ def _live(self):+ return main_dashboard++ @staticmethod+ def _fake_kill(pid, sig):+ if sig == 0:+ raise ProcessLookupError++ def _run(self, pid, jobs, *, kickstart_ok=True):+ live = self._live()+ with patch.object(main_dashboard, "_restart_managed_dashboard_service", return_value=False), \+ patch.object(live, "_find_stale_dashboard_pids", return_value=[pid]), \+ patch.object(main_dashboard, "_get_pid_cgroup_path", return_value=None), \+ patch.object(main_dashboard, "_get_systemd_service_for_pid", return_value=None), \+ patch.object(main_dashboard, "_dashboard_cmdline_for_pid", return_value=list(self.ARGV)), \+ patch.object(main_dashboard, "_loaded_launchd_backend_jobs", return_value=jobs), \+ patch.object(main_dashboard, "_try_kickstart_launchd_job", return_value=kickstart_ok) as kickstart, \+ patch("hermes_cli.dashboard_procs._hermes_home_for_pid", return_value=None), \+ patch.object(live, "_respawn_dashboard_processes", return_value=[]) as respawn, \+ patch("os.kill", side_effect=self._fake_kill), \+ patch("time.sleep"):+ result = _kill_stale_dashboard_processes(restart_managed=True)+ return result, kickstart, respawn++ @pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn")+ def test_launchd_owned_pid_is_kickstarted_not_respawned(self, capsys):+ """launchd reports the PID as the job's live process → kickstart the job, never respawn."""+ result, kickstart, respawn = self._run(9101, [("system", "ai.hermes.dashboard", list(self.ARGV), 9101)])++ respawn.assert_not_called()+ kickstart.assert_called_once_with("system", "ai.hermes.dashboard")+ assert result["killed"] == [9101]+ assert result["unrecovered"] == []+ out = capsys.readouterr().out+ assert "✓ restarted launchd job system/ai.hermes.dashboard" in out+ assert "when you're ready" not in out++ @pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn")+ def test_detached_copy_of_a_launchd_job_is_not_respawned(self, capsys):+ """The state an earlier respawn leaves behind: the job is loaded but has no live process+ (it fails on the port), and a detached copy runs its exact ProgramArguments. Killing the+ copy hands the port back to the job; respawning it would recreate the conflict."""+ result, kickstart, respawn = self._run(9102, [("system", "ai.hermes.dashboard", list(self.ARGV), None)])++ respawn.assert_not_called()+ kickstart.assert_called_once_with("system", "ai.hermes.dashboard")+ assert result["unrecovered"] == []+ assert "✓ restarted launchd job system/ai.hermes.dashboard" in capsys.readouterr().out++ @pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn")+ def test_launchd_kickstart_failure_reports_the_manual_command(self, capsys):+ result, kickstart, respawn = self._run(+ 9103, [("gui/501", "ai.hermes.dashboard", list(self.ARGV), 9103)], kickstart_ok=False)++ respawn.assert_not_called()+ kickstart.assert_called_once_with("gui/501", "ai.hermes.dashboard")+ assert result["unrecovered"] == [9103]+ out = capsys.readouterr().out+ assert "launchctl kickstart -k gui/501/ai.hermes.dashboard" in out+ assert "Restart anything not auto-restarted" in out++ @pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn")+ def test_unrelated_launchd_job_does_not_claim_a_manual_backend(self, capsys):+ """A loaded job with a different PID and different argv leaves the manual respawn intact."""+ other_argv = ["hermes", "dashboard", "--port", "8300"]+ result, kickstart, respawn = self._run(9104, [("gui/501", "ai.hermes.dashboard", other_argv, 777)])++ kickstart.assert_not_called()+ respawn.assert_called_once_with([list(self.ARGV)])+ assert result["unrecovered"] == []++ def test_owning_job_matches_by_live_pid_or_exact_argv(self):+ jobs = [+ ("gui/501", "ai.hermes.dashboard", ["hermes", "dashboard", "--port", "8300"], 4242),+ ("system", "ai.hermes.serve", ["hermes", "serve", "--port", "8301"], None),+ ]+ owning = main_dashboard._launchd_job_owning_backend+ assert owning(4242, ["something", "else"], jobs) == ("gui/501", "ai.hermes.dashboard")+ assert owning(9999, ["hermes", "serve", "--port", "8301"], jobs) == ("system", "ai.hermes.serve")+ assert owning(9999, ["hermes", "serve", "--port", "8302"], jobs) is None+ assert owning(9999, None, jobs) is None+ assert owning(4242, None, []) is None++ @pytest.mark.macos_only+ def test_loaded_backend_jobs_scans_plists_and_probes_only_backend_labels(self, tmp_path):+ """Only LOADED jobs whose ProgramArguments are a dashboard/serve backend are returned:+ gateway jobs are never probed, unloaded backends are dropped, unreadable plists skipped,+ and LaunchDaemons resolve to the system domain."""+ import plistlib++ agents = tmp_path / "LaunchAgents"+ daemons = tmp_path / "LaunchDaemons"+ agents.mkdir()+ daemons.mkdir()+ backend_argv = ["/opt/hermes/venv/bin/python", "-m", "hermes_cli.main", "dashboard", "--port", "9119"]+ serve_argv = ["/opt/hermes/venv/bin/python", "-m", "hermes_cli.main", "serve", "--port", "8642"]+ gateway_argv = ["/opt/hermes/venv/bin/python", "-m", "hermes_cli.main", "gateway", "run"]+ for path, label, argv in (+ (agents / "ai.hermes.dashboard.plist", "ai.hermes.dashboard", backend_argv),+ (agents / "ai.hermes.gateway.plist", "ai.hermes.gateway", gateway_argv),+ (agents / "ai.hermes.serve-old.plist", "ai.hermes.serve-old", serve_argv),+ (daemons / "ai.hermes.serve.plist", "ai.hermes.serve", serve_argv),+ ):+ with open(path, "wb") as f:+ plistlib.dump({"Label": label, "ProgramArguments": argv}, f)+ (agents / "broken.plist").write_bytes(b"not a plist")++ uid = os.getuid()+ probed: list[tuple[str, str]] = []++ def fake_print(domain, label):+ probed.append((domain, label))+ if (domain, label) == (f"user/{uid}", "ai.hermes.dashboard"):+ return (True, 4242)+ if (domain, label) == ("system", "ai.hermes.serve"):+ return (True, None)+ return (False, None)++ with patch("hermes_cli.gateway._launchd_print_service_pid", side_effect=fake_print):+ jobs = main_dashboard._loaded_launchd_backend_jobs([("agent", agents), ("daemon", daemons)])++ assert jobs == [+ (f"user/{uid}", "ai.hermes.dashboard", backend_argv, 4242),+ ("system", "ai.hermes.serve", serve_argv, None),+ ]+ assert ("gui/501", "ai.hermes.gateway") not in probed+ assert not any(label == "ai.hermes.gateway" for _domain, label in probed)+ # An agent label is probed gui first, then user; a daemon only in system.+ assert probed[:2] == [(f"gui/{uid}", "ai.hermes.dashboard"), (f"user/{uid}", "ai.hermes.dashboard")]+ assert ("system", "ai.hermes.serve") in probed+ assert not any(domain == "system" and label != "ai.hermes.serve" for domain, label in probed)++ @pytest.mark.linux_only+ def test_loaded_backend_jobs_is_empty_off_macos(self, tmp_path):+ assert main_dashboard._loaded_launchd_backend_jobs([("agent", tmp_path)]) == []