Skip to content

The agent that grows with you

fix(bot-desktop): an abandoned screen stops itself after the idle window

kshitijk4poorb5e47a022583
diff --git a/tests/tools/test_bot_desktop_idle.py b/tests/tools/test_bot_desktop_idle.py
index f8d4b757529..4be68f537b9 100644
--- a/tests/tools/test_bot_desktop_idle.py
+++ b/tests/tools/test_bot_desktop_idle.py
@@ -50,3 +50,12 @@ def test_idle_stop_disabled_by_zero(tmp_path, monkeypatch):
monkeypatch.setattr(runtime, "idle_stop_seconds", lambda: 0.0)
_age(sd / "env", 10 ** 6)
assert runtime.stop_if_idle() is False and stops == []
+
+
+def test_the_launchers_idle_check_sleeps_until_the_screen_could_be_due():
+ from tools.bot_desktop.idle_watch import next_check_in
+ assert next_check_in(1800, 600) == 1200 # wakes when the window runs out at the current age
+ assert next_check_in(1800, 1795) == 30 # never a tight loop near the edge
+ 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 length
+ assert next_check_in(0, None) == runtime.DEFAULT_IDLE_STOP_MINUTES * 60 # off: re-read the setting later
diff --git a/tests/tools/test_bot_desktop_idle_self_stop.py b/tests/tools/test_bot_desktop_idle_self_stop.py
new file mode 100644
index 00000000000..fe30ee030e3
--- /dev/null
+++ b/tests/tools/test_bot_desktop_idle_self_stop.py
@@ -0,0 +1,129 @@
+"""A Bot Desktop screen whose gateway never comes back stops itself after ``bot_desktop.idle_stop_minutes``.
+
+The real ``launcher.sh`` runs against stub X/Xfce binaries. ``runtime.start()`` runs in a separate
+"gateway" process that is SIGKILLed, so nothing in the test process holds the screen.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import signal
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+import pytest
+
+from tests.waiting import wait_until
+
+pytestmark = [pytest.mark.platforms("linux"), pytest.mark.live_system_guard_bypass]
+
+_REPO = Path(__file__).resolve().parents[2]
+
+_STUBS = {
+ # Binds nothing: creates the socket path it was given, then lives like a server.
+ "Xvnc": '#!/bin/sh\nwhile [ $# -gt 0 ]; do [ "$1" = -rfbunixpath ] && : > "$2"; shift; done\nexec sleep 600\n',
+ "dbus-run-session": '#!/bin/sh\nshift\nDBUS_SESSION_BUS_ADDRESS=unix:path=/nonexistent; export DBUS_SESSION_BUS_ADDRESS\nexec "$@"\n',
+ "xfce4-panel": "#!/bin/sh\nexec sleep 600\n",
+ **{name: "#!/bin/sh\nexit 0\n" for name in ("xdpyinfo", "setxkbmap", "xsetroot", "xset", "xauth", "xprop",
+ "xfsettingsd", "xfwm4", "xfdesktop")},
+}
+
+# The gateway: starts the profile's screen through the real runtime path, reports the launcher pid, idles.
+_GATEWAY = """
+import sys, time
+from pathlib import Path
+sys.path.insert(0, {repo!r})
+from tools.bot_desktop import runtime
+runtime._X_LOCK_DIR = Path({scratch!r})
+runtime._ALLOC_LOCK = runtime._X_LOCK_DIR / "alloc.lock"
+runtime.missing_binaries = list
+print(runtime.start(wait_seconds=15).pid, flush=True)
+time.sleep(600)
+"""
+
+
+def _alive(pgid: int) -> bool:
+ try:
+ os.killpg(pgid, 0) # windows-footgun: ok — Linux-only test
+ except ProcessLookupError:
+ return False
+ return True
+
+
+def abandoned_screen(tmp_path):
+ """``launch(idle_stop_minutes)`` -> (state dir, launcher pid): a running screen whose gateway is dead."""
+ stubs = tmp_path / "bin"
+ stubs.mkdir()
+ for name, body in _STUBS.items():
+ (stubs / name).write_text(body, encoding="utf-8")
+ (stubs / name).chmod(0o755)
+ home = tmp_path / "home"
+ home.mkdir()
+ env = {**os.environ, "HERMES_HOME": str(home), "PATH": f"{stubs}{os.pathsep}{os.environ['PATH']}"}
+ env.pop("PYTHONPATH", None)
+ groups: list[int] = []
+
+ def launch(idle_stop_minutes: float) -> tuple[Path, int]:
+ (home / "config.yaml").write_text(f"bot_desktop:\n idle_stop_minutes: {idle_stop_minutes}\n", encoding="utf-8")
+ gateway = subprocess.Popen([sys.executable, "-c", _GATEWAY.format(repo=str(_REPO), scratch=str(tmp_path))],
+ env=env, stdout=subprocess.PIPE, text=True)
+ launcher = int(gateway.stdout.readline())
+ groups.append(launcher)
+ gateway.kill() # SIGKILL: no cleanup runs, no gateway comes back
+ gateway.wait()
+ gateway.stdout.close()
+ return home / "bot-desktop", launcher
+
+ yield launch
+ for pgid in groups:
+ with contextlib.suppress(ProcessLookupError):
+ os.killpg(pgid, signal.SIGKILL) # windows-footgun: ok — Linux-only test
+
+
+def test_an_abandoned_screen_stops_itself_after_the_idle_window(abandoned_screen):
+ sd, launcher = abandoned_screen(idle_stop_minutes=0.02) # 1.2 s
+ # stop() deletes launcher.pid/env after the group is gone, so both are part of "stopped".
+ wait_until(lambda: not _alive(launcher) and not (sd / "launcher.pid").exists() and not (sd / "env").exists(),
+ timeout=30, what="the abandoned screen to be stopped the way stop() does")
+
+
+def test_a_screen_in_use_is_kept_and_a_returning_gateway_reattaches(abandoned_screen, monkeypatch):
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ from tools.bot_desktop import runtime
+
+ sd, launcher = abandoned_screen(idle_stop_minutes=0.02)
+ log = sd / "launcher.log"
+
+ def checks_kept() -> int:
+ return log.read_text(encoding="utf-8", errors="replace").count("screen kept")
+
+ def kept_while_used(n: int) -> bool:
+ (sd / "activity").touch() # the agent / a viewer using the screen
+ return checks_kept() >= n
+
+ wait_until(lambda: kept_while_used(2), timeout=30, what="idle checks that keep a screen in use")
+ assert _alive(launcher)
+
+ # A human holding the screen long past the window is never timed out.
+ (sd / "lease.json").write_text(json.dumps({"holder": "human", "viewer_id": "v", "epoch": 1}), encoding="utf-8")
+ old = time.time() - 3600
+ os.utime(sd / "activity", (old, old))
+ seen = checks_kept()
+ wait_until(lambda: checks_kept() > seen, timeout=30, what="an idle check while a human holds the screen")
+ assert _alive(launcher)
+
+ # A gateway that comes back inside the window re-attaches to the same screen instead of starting another.
+ monkeypatch.setattr(runtime, "missing_binaries", list) # the stub X binaries are only on the launcher's PATH
+ token = set_hermes_home_override(sd.parent)
+ try:
+ assert runtime.start(wait_seconds=1).pid == launcher
+ finally:
+ reset_hermes_home_override(token)
+
+ (sd / "lease.json").unlink() # handed back; nobody uses it any more
+ wait_until(lambda: not _alive(launcher), timeout=30, what="the screen to stop once nobody holds it")
diff --git a/tools/bot_desktop/idle_watch.py b/tools/bot_desktop/idle_watch.py
new file mode 100644
index 00000000000..6b839de03bf
--- /dev/null
+++ b/tools/bot_desktop/idle_watch.py
@@ -0,0 +1,51 @@
+"""One idle check for a Bot Desktop screen, run by the screen's own launcher.
+
+The screen outlives the gateway that started it on purpose (a restarted gateway re-attaches to it), so the
+gateway's display watcher cannot be the only thing that ever stops it: when no gateway comes back, Xvnc +
+Xfce and any browser left open run until reboot. ``launcher.sh`` therefore runs
+``python -m tools.bot_desktop.idle_watch`` in a loop of its own. Each run applies
+:func:`runtime.stop_if_idle` (the same ``bot_desktop.idle_stop_minutes`` window and the same rule that a
+human holding the screen is never timed out) and prints how long the launcher should sleep before the next
+run, so no interpreter stays resident between checks.
+"""
+
+from __future__ import annotations
+
+import logging
+import math
+import os
+from typing import Optional
+
+from tools.bot_desktop import runtime
+
+logger = logging.getLogger(__name__)
+
+_MIN_DELAY_S = 30.0 # the gateway watcher's cadence; a window shorter than that is checked at its own length
+
+
+def next_check_in(limit: float, idle: Optional[float]) -> int:
+ """Whole seconds until the screen could next be due: when the window runs out at the current idle age,
+ or a full window later while something (a human holding it) keeps it past that. With the auto-stop off
+ (``limit <= 0``) the setting is re-read every default window."""
+ if limit <= 0:
+ return runtime.DEFAULT_IDLE_STOP_MINUTES * 60
+ idle = idle or 0.0
+ return math.ceil(max(min(_MIN_DELAY_S, limit), limit - idle if idle < limit else limit))
+
+
+def main() -> None:
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s idle-watch %(message)s") # stderr = launcher.log
+ if runtime.stop_if_idle():
+ return
+ delay = next_check_in(runtime.idle_stop_seconds(), runtime.idle_seconds())
+ logger.info("screen kept; next idle check in %ds", delay)
+ print(delay)
+
+
+if __name__ == "__main__":
+ # stop() kills the launcher's process group, which this check was started in; in a session of its own it
+ # survives that kill to finish the stop (SIGKILL stragglers, drop the runtime files), then exits. A process
+ # that already leads its group (run by hand from a shell) cannot setsid and is not in the launcher's group.
+ if os.getpgrp() != os.getpid(): # windows-footgun: ok — Linux-only (launcher.sh)
+ os.setsid() # windows-footgun: ok — Linux-only (launcher.sh) detached-spawn: ok — short-lived, outlives the group kill it performs
+ main()
diff --git a/tools/bot_desktop/launcher.sh b/tools/bot_desktop/launcher.sh
index 67b8a039d69..a25cb56506b 100755
--- a/tools/bot_desktop/launcher.sh
+++ b/tools/bot_desktop/launcher.sh
@@ -275,6 +275,32 @@ setxkbmap -display "$DISPLAY" us 2>/dev/null || true # RFB keysyms + xdotool a
xsetroot -display "$DISPLAY" -solid '#1c1f29' 2>/dev/null || true
xset -display "$DISPLAY" s off -dpms s noblank 2>/dev/null || true
+# ---- idle self-stop: the screen outlives the gateway that started it (a restarted gateway re-attaches),
+# so it must also stop itself when no gateway ever comes back. tools/bot_desktop/idle_watch.py applies the
+# gateway watcher's own rule (bot_desktop.idle_stop_minutes; never while a human holds the screen) once per
+# run and prints the seconds until the next check; nothing stays resident in between. Skipped when runtime.py
+# passed no interpreter (the sandbox-hosted screen, whose sandbox lifetime bounds it).
+WATCH_PID=
+if [[ -n "${HERMES_BD_PYTHON:-}" ]]; then
+ # A start is use: stamp it now, or an activity file left by an earlier screen could make the first check
+ # stop this one before runtime.py stamps it.
+ touch "$(dirname "$HERMES_BD_ENV_FILE")/activity"
+ # The TERM trap ends the sleep at once when the screen goes down (stop()'s group signal or the EXIT trap
+ # below); during the ~0.4 s check itself bash defers it, well inside stop()'s grace.
+ (
+ trap 'kill "$!" 2>/dev/null; exit 0' TERM
+ while kill -0 "$$" 2>/dev/null; do
+ delay=$(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
+ [[ -n "$delay" ]] || exit 0 # it stopped the screen
+ [[ "$delay" =~ ^[0-9]+$ ]] || delay=300
+ sleep "$delay" & wait "$!"
+ done
+ ) &
+ WATCH_PID=$!
+fi
+trap 'kill "$XVNC_PID" $WATCH_PID 2>/dev/null || true' EXIT
+
# ---- private session bus + Xfce components (no xfce4-session) ----
# dbus-run-session scopes the bus to this subshell: no leaked dbus-daemons on restart. The env file
# is written from INSIDE the bus so DBUS_SESSION_BUS_ADDRESS is the real one; runtime.py and every
diff --git a/tools/bot_desktop/runtime.py b/tools/bot_desktop/runtime.py
index 7de13c7617f..6e8bae93f74 100644
--- a/tools/bot_desktop/runtime.py
+++ b/tools/bot_desktop/runtime.py
@@ -413,8 +413,9 @@ def _should_auto_start(env: dict[str, str]) -> bool:
# ---- idle auto-stop -------------------------------------------------------------------------------
# A desktop nobody is using still holds ~220 MiB (plus whatever browser was left open). Every use —
# a computer_use action, a browser spawn onto the screen, a viewer attached, a human takeover — stamps
-# ``activity``; the gateway's display watcher stops a screen idle past ``bot_desktop.idle_stop_minutes``
-# unless a human holds it. The next use starts it again (auto_start or the pane's Start).
+# ``activity``; :func:`stop_if_idle` stops a screen idle past ``bot_desktop.idle_stop_minutes`` unless a
+# human holds it. Two callers apply it: the gateway's display watcher and the screen's own launcher
+# (``idle_watch``), so a screen whose gateway never came back still stops. The next use starts it again.
DEFAULT_IDLE_STOP_MINUTES = 30
@@ -736,6 +737,10 @@ def _spawn_and_wait(sd: Path, wait_seconds: float) -> DesktopStatus:
"HERMES_BD_ENV_FILE": str(env_file),
"HERMES_BD_CONFIG_HOME": str(sd / "xdg"),
"HERMES_BD_GEOMETRY": geometry(),
+ # The launcher's idle self-stop runs tools.bot_desktop.idle_watch with this interpreter and home.
+ "HERMES_BD_PYTHON": sys.executable,
+ "HERMES_BD_SRC_ROOT": str(Path(__file__).resolve().parents[2]),
+ "HERMES_BD_HOME": str(get_hermes_home()),
})
from tools.bot_desktop.browser import dock_exec_line, dock_launch
if (browser := dock_launch()) is not None:
diff --git a/website/docs/user-guide/features/bot-screen.md b/website/docs/user-guide/features/bot-screen.md
index de65327fbf4..2e3345a1d24 100644
--- a/website/docs/user-guide/features/bot-screen.md
+++ b/website/docs/user-guide/features/bot-screen.md
@@ -89,7 +89,9 @@ reverse proxy's access log may record an already-spent ticket.
`hermes computer-use screen start` refuses; a screen already running is never
taken down by this check. A screen nobody uses is stopped after
`bot_desktop.idle_stop_minutes` (default 30) and comes back on the next use, so
- an instance pays for a desktop only while something is on it. Practical guidance
+ an instance pays for a desktop only while something is on it. The screen
+ applies that window itself too, so it also stops when the gateway that
+ started it is gone and never restarts. Practical guidance
for small instances: 4 GB runs the desktop, 8 GB is where a takeover with a
browser is comfortable.