The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-desktop): a waiting idle check never stops the replacement screen
kshitijk4poor1f140147104b
diff --git a/tests/tools/test_bot_desktop_idle.py b/tests/tools/test_bot_desktop_idle.pyindex 4be68f537b9..19caed83c66 100644--- a/tests/tools/test_bot_desktop_idle.py+++ b/tests/tools/test_bot_desktop_idle.py@@ -4,8 +4,12 @@ one a human holds or that saw recent use is not."""from __future__ import annotationsimport os+import subprocess+import threadingimport time+import pytest+from tools.bot_desktop import lease, runtime@@ -17,7 +21,7 @@ def _running(monkeypatch, tmp_path):monkeypatch.setattr(runtime, "_launcher_pid", lambda: 4242)monkeypatch.setattr(runtime, "idle_stop_seconds", lambda: 600.0)stops = []- monkeypatch.setattr(runtime, "stop", lambda: stops.append(True) or True)+ monkeypatch.setattr(runtime, "stop", lambda still_due=None: stops.append(True) or True)return sd, stops@@ -59,3 +63,55 @@ def test_the_launchers_idle_check_sleeps_until_the_screen_could_be_due():assert next_check_in(1800, 7200) == 1800, "a human holding it past the window: recheck a window later"assert next_check_in(1.2, None) == 2 # a window shorter than the floor is checked at its own lengthassert next_check_in(0, None) == runtime.DEFAULT_IDLE_STOP_MINUTES * 60 # off: re-read the setting later++[email protected]("judged", ["the old screen", "any screen"])+def test_an_idle_check_that_waited_on_the_lock_never_stops_the_replacement_screen(tmp_path, monkeypatch, judged):+ """The idle decision is taken before ``start.lock``; a stop + start that holds the lock meanwhile replaces+ the screen. The waiting check must re-decide under the lock: the launcher's own check (it names the screen+ it judged) keeps a replacement however idle, the gateway watcher keeps one that is in use."""+ from tools.bot_desktop import placement, sandbox_host++ sd = tmp_path / "bd"+ sd.mkdir()+ (sd / "env").write_text("DISPLAY=:20\n", encoding="utf-8")+ (sd / "activity").touch()+ _age(sd / "activity", 3600)+ monkeypatch.setattr(runtime, "state_dir", lambda: sd)+ monkeypatch.setattr(runtime, "idle_stop_seconds", lambda: 600.0)+ monkeypatch.setattr(runtime, "is_supported_host", lambda: True)+ monkeypatch.setattr(sandbox_host, "_read_marker", dict)+ monkeypatch.setattr(placement, "resolve", lambda: placement.Placement(placement.GATEWAY, "local"))+ monkeypatch.setattr(lease, "get", lambda profile_key=None: lease.Lease(holder=lease.AGENT))++ def launch() -> subprocess.Popen:+ proc = subprocess.Popen(["sleep", "60"], start_new_session=True)+ (sd / "launcher.pid").write_text(f"{proc.pid} {runtime._create_time(proc.pid)}", encoding="utf-8")+ return proc++ old, new = launch(), None+ lock, waiting, result = runtime._flocked, threading.Event(), []++ def flocked_after_signalling(path):+ waiting.set()+ return lock(path)+ monkeypatch.setattr(runtime, "_flocked", flocked_after_signalling)+ identity = (old.pid, runtime._create_time(old.pid)) if judged == "the old screen" else None+ check = threading.Thread(target=lambda: result.append(runtime.stop_if_idle(launcher=identity)))+ try:+ with lock(sd / "start.lock"): # a concurrent stop + start holds it+ check.start()+ assert waiting.wait(5) # past its first decision; it gets the lock only after the swap below+ old.kill()+ old.wait()+ new = launch()+ if judged == "any screen":+ runtime.touch_activity() # the replacement is in use+ check.join(15)+ assert result == [False], "the waiting check stopped the screen it found under the lock"+ assert new.poll() is None and runtime._launcher_pid() == new.pid+ finally:+ for proc in (old, new):+ if proc is not None and proc.poll() is None:+ proc.kill()+ proc.wait()diff --git a/tools/bot_desktop/idle_watch.py b/tools/bot_desktop/idle_watch.pyindex 6b839de03bf..534e4082d70 100644--- a/tools/bot_desktop/idle_watch.py+++ b/tools/bot_desktop/idle_watch.py@@ -14,6 +14,7 @@ from __future__ import annotationsimport loggingimport mathimport os+import sysfrom typing import Optionalfrom tools.bot_desktop import runtime@@ -33,9 +34,20 @@ def next_check_in(limit: float, idle: Optional[float]) -> int:return math.ceil(max(min(_MIN_DELAY_S, limit), limit - idle if idle < limit else limit))+def _own_launcher(argv: list[str]) -> Optional[tuple[int, float]]:+ """``(pid, create_time)`` of the launcher that ran this check (its pid is the one argument), so the+ check stops only that screen and never a replacement started while it waited on ``start.lock``. A+ launcher already gone gets an identity nothing matches."""+ pid_s = argv[0] if argv else ""+ if not pid_s.isdigit():+ return None+ born = runtime._create_time(int(pid_s))+ return int(pid_s), born if born is not None else -1.0++def main() -> None:logging.basicConfig(level=logging.INFO, format="%(asctime)s idle-watch %(message)s") # stderr = launcher.log- if runtime.stop_if_idle():+ if runtime.stop_if_idle(launcher=_own_launcher(sys.argv[1:])):returndelay = next_check_in(runtime.idle_stop_seconds(), runtime.idle_seconds())logger.info("screen kept; next idle check in %ds", delay)diff --git a/tools/bot_desktop/launcher.sh b/tools/bot_desktop/launcher.shindex a25cb56506b..94203ae7bba 100755--- a/tools/bot_desktop/launcher.sh+++ b/tools/bot_desktop/launcher.sh@@ -291,7 +291,7 @@ if [[ -n "${HERMES_BD_PYTHON:-}" ]]; thentrap 'kill "$!" 2>/dev/null; exit 0' TERMwhile kill -0 "$$" 2>/dev/null; dodelay=$(HERMES_HOME="$HERMES_BD_HOME" PYTHONPATH="$HERMES_BD_SRC_ROOT${PYTHONPATH:+:$PYTHONPATH}" \- "$HERMES_BD_PYTHON" -m tools.bot_desktop.idle_watch) || delay=300 # broken check: retry slowly+ "$HERMES_BD_PYTHON" -m tools.bot_desktop.idle_watch "$$") || delay=300 # broken check: retry slowly[[ -n "$delay" ]] || exit 0 # it stopped the screen[[ "$delay" =~ ^[0-9]+$ ]] || delay=300sleep "$delay" & wait "$!"diff --git a/tools/bot_desktop/runtime.py b/tools/bot_desktop/runtime.pyindex 6e8bae93f74..410ffcd06cd 100644--- a/tools/bot_desktop/runtime.py+++ b/tools/bot_desktop/runtime.py@@ -24,7 +24,7 @@ import sysimport timefrom dataclasses import dataclassfrom pathlib import Path-from typing import Dict, Optional+from typing import Callable, Dict, Optionalfrom agent.deadline import poll_untilfrom hermes_constants import get_hermes_home@@ -178,10 +178,10 @@ def _create_time(pid: int) -> Optional[float]:return None-def _launcher_pid() -> Optional[int]:- """The live launcher's pid, or None. ``launcher.pid`` holds ``"<pid> <create_time>"``: a recycled pid- with a different start time is somebody else's process and must never be reported as ours nor- killed by :func:`stop`. The pre-identity single-number format is treated as not running."""+def _launcher_identity() -> Optional[tuple[int, float]]:+ """``(pid, create_time)`` of the live launcher, or None. ``launcher.pid`` holds ``"<pid> <create_time>"``:+ a recycled pid with a different start time is somebody else's process and must never be reported as+ ours nor killed by :func:`stop`. The pre-identity single-number format is treated as not running."""raw = _read(state_dir() / "launcher.pid")pid_s, _, born_s = (raw or "").partition(" ")if not pid_s.isdigit() or not born_s:@@ -191,7 +191,13 @@ 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 and _pid_alive(pid) else None+ return (pid, born) if actual is not None and abs(actual - born) < 0.01 and _pid_alive(pid) else None+++def _launcher_pid() -> Optional[int]:+ """The live launcher's pid, or None (see :func:`_launcher_identity`)."""+ identity = _launcher_identity()+ return identity[0] if identity is not None else Nonedef _recorded_launcher_pid() -> Optional[int]:@@ -449,20 +455,36 @@ def idle_stop_seconds() -> float:return max(0.0, minutes) * 60-def stop_if_idle() -> bool:- """Stop this profile's screen when it has been idle past the limit and no human holds it. True when- it was stopped."""+def _idle_due(launcher: Optional[tuple[int, float]]) -> Optional[float]:+ """Idle seconds when the screen is due for the idle stop now, else None. ``launcher`` (``(pid,+ create_time)``) limits it to that one screen: a replacement started since is never due."""limit = idle_stop_seconds()if limit <= 0 or not is_running():- return False+ return None+ if launcher is not None:+ current = _launcher_identity()+ if current is None or current[0] != launcher[0] or abs(current[1] - launcher[1]) >= 0.01:+ return Noneidle = idle_seconds()if idle is None or idle < limit:- return False+ return Nonefrom tools.bot_desktop import lease as _bd_leaseif _bd_lease.get().holder == _bd_lease.HUMAN:+ return None+ return idle+++def stop_if_idle(launcher: Optional[tuple[int, float]] = None) -> bool:+ """Stop this profile's screen when it has been idle past the limit and no human holds it. True when+ it was stopped. ``launcher`` names the screen the caller judges (the launcher's own check passes it).++ The decision is taken again under ``start.lock`` before anything is killed: a check that waited on the+ lock while the screen was stopped and started again (or used) must not kill the screen it finds then."""+ idle = _idle_due(launcher)+ if idle is None:return Falselogger.info("Bot Desktop for profile %s idle for %.0f min; stopping", _profile_name(), idle / 60)- return stop()+ return stop(still_due=lambda: _idle_due(launcher) is not None)def published_env() -> dict[str, str]:@@ -816,11 +838,13 @@ def _sandbox_published_env() -> dict[str, str]:return sandbox_host.published_env(env, _profile_name())-def stop() -> bool:+def stop(still_due: Optional[Callable[[], bool]] = None) -> bool:"""Stop this profile's desktop; True when a running launcher (or the X server a dead one left behind)- was signalled."""+ was signalled. ``still_due`` is re-asked under ``start.lock``; False there leaves the screen running."""from tools.bot_desktop import sandbox_hostif sandbox_host._read_marker() or placement.resolve().where == placement.TERMINAL:+ if still_due is not None and not still_due():+ return False# The marker names the sandbox that owns the screen; stop THAT one (re-attaching after a restart),# whatever the placement setting says now. A marker whose sandbox is gone is simply dropped.env = _owned_sandbox_env()@@ -834,6 +858,9 @@ def stop() -> bool:sd = state_dir()sd.mkdir(parents=True, exist_ok=True)with _flocked(sd / "start.lock"):+ if still_due is not None and not still_due():+ logger.info("Bot Desktop for profile %s changed while the idle stop waited; kept", _profile_name())+ return Falsereturn _stop_locked(sd)