The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-screen): reap the X server a dead launcher leaves behind instead of starting a second one
teknium1809169b7d007
diff --git a/tests/tools/test_bot_desktop_runtime.py b/tests/tools/test_bot_desktop_runtime.pyindex fd89a14d6de..d7f1b0ec9b1 100644--- a/tests/tools/test_bot_desktop_runtime.py+++ b/tests/tools/test_bot_desktop_runtime.py@@ -144,3 +144,80 @@ def test_concurrent_starts_of_one_profile_spawn_one_launcher(tmp_path, start_in_out = _collect([start_in_fresh_process(tmp_path / "a"), start_in_fresh_process(tmp_path / "a")])assert len({o["pid"] for o in out}) == 1, outassert len(list((tmp_path / "xlocks").glob("spawned.*"))) == 1+++_ORPHANING_LAUNCHER = """#!/usr/bin/env bash+# Stands in for launcher.sh whose Xvnc child ("sleep") lives in the launcher's process group and+# outlives a SIGKILL of the launcher itself — the X lock names the child, as the real one does.+: > "$HERMES_BD_XLOCK_DIR/spawned.$$"+sleep 30 &+echo $! > "$HERMES_BD_XLOCK_DIR/.X${HERMES_BD_DISPLAY_NUM}-lock"+: > "$HERMES_BD_SOCKET"+printf 'DISPLAY=:%s\\n' "$HERMES_BD_DISPLAY_NUM" > "$HERMES_BD_ENV_FILE"+wait+"""+++def _gone(pid: int) -> bool:+ import psutil+ try:+ return psutil.Process(pid).status() == psutil.STATUS_ZOMBIE+ except psutil.NoSuchProcess:+ return True+++def _wait_until(pred, timeout=5.0) -> bool:+ import time+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if pred():+ return True+ time.sleep(0.05)+ return pred()+++def in_process_runtime(tmp_path, monkeypatch):+ """runtime.start()/stop() against a scratch state dir and a fake launcher script (set by the test)."""+ import os++ home = tmp_path / "home"+ (tmp_path / "xlocks").mkdir()+ monkeypatch.setattr(runtime, "state_dir", lambda: home / "bot-desktop")+ monkeypatch.setattr(runtime, "_LAUNCHER", tmp_path / "launcher.sh")+ monkeypatch.setattr(runtime, "_X_LOCK_DIR", tmp_path / "xlocks")+ monkeypatch.setattr(runtime, "_ALLOC_LOCK", tmp_path / "alloc.lock")+ monkeypatch.setattr(runtime, "missing_binaries", lambda: [])+ monkeypatch.setattr(runtime, "geometry", lambda: "800x600")+ monkeypatch.setenv("HERMES_BD_XLOCK_DIR", str(tmp_path / "xlocks"))+ yield tmp_path+ with contextlib.suppress(Exception):+ runtime.stop()+ for lock in (tmp_path / "xlocks").glob(".X*-lock"): # anything the code under test failed to reap+ with contextlib.suppress(OSError, ValueError):+ os.kill(int(lock.read_text()), 9)++[email protected]_only[email protected]_system_guard_bypass # the orphan is reparented to init: signalling it is the point+def test_orphaned_x_server_of_a_dead_launcher_is_reaped_on_next_start(in_process_runtime):+ """SIGKILL the launcher and its Xvnc survives, holding the display and rfb.sock. status() keys on the+ launcher pid and says stopped; start() must find that orphan through the recorded display's X lock+ and kill it instead of allocating a second server beside it (two servers, one socket path)."""+ import os+ import signal++ scratch = in_process_runtime+ (scratch / "launcher.sh").write_text(_ORPHANING_LAUNCHER, encoding="utf-8")+ first = runtime.start(wait_seconds=10)+ lock = scratch / "xlocks" / f".X{first.display.lstrip(':')}-lock"+ orphan = int(lock.read_text())+ os.kill(first.pid, signal.SIGKILL)+ assert _wait_until(lambda: _gone(first.pid))+ assert not _gone(orphan), "the X server outlives its launcher (that is the bug's precondition)"+ assert runtime.status().running is False++ second = runtime.start(wait_seconds=10)+ assert second.pid != first.pid and second.running+ assert _wait_until(lambda: _gone(orphan)), "the dead launcher's X server must be reaped, not leaked"+ assert runtime.stop() is Truediff --git a/tools/bot_desktop/runtime.py b/tools/bot_desktop/runtime.pyindex a9ce1923f09..ace34a9ed6f 100644--- a/tools/bot_desktop/runtime.py+++ b/tools/bot_desktop/runtime.py@@ -125,8 +125,13 @@ def _read(path: Path) -> Optional[str]:def _pid_alive(pid: int) -> bool:+ """A zombie is dead for our purposes: a SIGKILLed launcher stays a zombie in the gateway until the next+ Popen reaps it, and reporting it as running would hide its orphaned X server behind a live status."""import psutil- return psutil.pid_exists(pid)+ try:+ return psutil.Process(pid).status() != psutil.STATUS_ZOMBIE+ except psutil.Error:+ return Falsedef _create_time(pid: int) -> Optional[float]:@@ -150,21 +155,78 @@ def _launcher_pid() -> Optional[int]:except ValueError:return Noneactual = _create_time(pid)- return pid if actual is not None and abs(actual - born) < 0.01 else None+ return pid if actual is not None and abs(actual - born) < 0.01 and _pid_alive(pid) else None+++def _recorded_launcher_pid() -> Optional[int]:+ """The pid ``launcher.pid`` names, alive or not (the orphan sweep matches process groups against it)."""+ pid_s, _, born_s = (_read(state_dir() / "launcher.pid") or "").partition(" ")+ return int(pid_s) if pid_s.isdigit() and born_s else None_X_LOCK_DIR = Path("/tmp") # where X servers write .X<n>-lock (tests point it at a scratch dir)+def _x_lock_pid(num: int) -> Optional[int]:+ try:+ return int((_X_LOCK_DIR / f".X{num}-lock").read_text(encoding="utf-8").strip())+ except (OSError, ValueError):+ return None++def _display_in_use(num: int) -> bool:"""A live X server owns ``:num``: its lock file names a running pid. A lock left by a crashedserver (dead pid) does not count, so the number can be reclaimed."""- lock = _X_LOCK_DIR / f".X{num}-lock"+ pid = _x_lock_pid(num)+ return pid is not None and _pid_alive(pid)+++def _reap_orphaned_server(sd: Path) -> bool:+ """Caller holds ``start.lock`` and has established that no live launcher exists. The launcher runs Xvnc in+ its own session, so a SIGKILLed launcher leaves the X server alive, holding the display and ``rfb.sock``;+ ``status()`` keys on the launcher and says stopped, and a naive restart allocates a second server next+ to it and overwrites the socket path both now claim. The X lock of the recorded display names that+ server: it is ours when it sits in the dead launcher's process group or its command line binds OUR+ socket. Kill it (group first), drop the state it left, and report whether anything was signalled."""+ import psutil++ recorded = _read(sd / "display")+ pid = _x_lock_pid(int(recorded)) if recorded and recorded.isdigit() else None+ if pid is None or not _pid_alive(pid):+ return False+ launcher = _recorded_launcher_pid()try:- pid = int(lock.read_text(encoding="utf-8").strip())- except (OSError, ValueError):+ pgid = os.getpgid(pid) # windows-footgun: ok — Linux-only runtime (is_supported_host gates start/stop)+ cmdline = psutil.Process(pid).cmdline()+ except (ProcessLookupError, psutil.Error):return False- return _pid_alive(pid)+ binds_our_socket = "Xvnc" in Path(cmdline[0] if cmdline else "").name and str(sd / "rfb.sock") in cmdline+ if pgid != launcher and not binds_our_socket:+ return False # somebody else's server took the number after we died; never touch it+ logger.warning("Bot Desktop launcher %s is gone but its X server (pid %s) survived on :%s; reaping",+ launcher, pid, recorded)+ _kill_group_then_wait(pgid if pgid == launcher else None, pid)+ (_X_LOCK_DIR / f".X{recorded}-lock").unlink(missing_ok=True)+ for name in ("launcher.pid", "env", "rfb.sock"):+ (sd / name).unlink(missing_ok=True)+ return True+++def _kill_group_then_wait(pgid: Optional[int], pid: int, grace: float = 2.0) -> None:+ """SIGTERM the group (or the lone pid), SIGKILL whatever is still there after ``grace``."""+ def _signal(sig: int) -> None:+ with contextlib.suppress(ProcessLookupError, PermissionError):+ if pgid is not None:+ os.killpg(pgid, sig) # windows-footgun: ok — Linux-only runtime (is_supported_host gates start/stop)+ else:+ os.kill(pid, sig)+ _signal(signal.SIGTERM)+ deadline = time.monotonic() + grace+ while time.monotonic() < deadline:+ if not _pid_alive(pid):+ return+ time.sleep(0.05)+ _signal(signal.SIGKILL) # windows-footgun: ok — Linux-only runtime (is_supported_host gates start/stop)_ALLOC_LOCK = Path("/tmp/.hermes-bot-desktop-alloc.lock") # host-wide: profiles allocate from one band@@ -307,6 +369,8 @@ def start(*, wait_seconds: float = 15.0) -> DesktopStatus:with _flocked(sd / "start.lock"):if _launcher_pid() is not None and published_env().get("DISPLAY"):return status()+ if _launcher_pid() is None:+ _reap_orphaned_server(sd)with _flocked(_ALLOC_LOCK):return _spawn_and_wait(sd, _pick_display(), wait_seconds)@@ -352,7 +416,8 @@ def _spawn_and_wait(sd: Path, num: int, wait_seconds: float) -> DesktopStatus:def stop() -> bool:- """Stop this profile's desktop; True when a running launcher was signalled."""+ """Stop this profile's desktop; True when a running launcher (or the X server a dead one left behind)+ was signalled."""if not is_supported_host():return Falsesd = state_dir()@@ -364,22 +429,11 @@ def stop() -> bool:def _stop_locked(sd: Path) -> bool:pid = _launcher_pid()if pid is None:+ reaped = _reap_orphaned_server(sd)(sd / "env").unlink(missing_ok=True)- return False+ return reaped# The launcher runs in its own session; killing the group takes Xvnc, dbus and Xfce with it.- try:- os.killpg(pid, signal.SIGTERM) # windows-footgun: ok — Linux-only runtime (is_supported_host gates start)- except ProcessLookupError:- pass- for _ in range(50):- if not _pid_alive(pid):- break- time.sleep(0.1)- else:- try:- os.killpg(pid, signal.SIGKILL) # windows-footgun: ok — Linux-only runtime (is_supported_host gates start)- except ProcessLookupError:- pass+ _kill_group_then_wait(pid, pid, grace=5.0)(sd / "launcher.pid").unlink(missing_ok=True)(sd / "env").unlink(missing_ok=True)return True