Skip to content

The agent that grows with you

fix(serve): expose turn_in_flight as an idle proof for pooled backends

Austin Pickett3eface06f7b9
diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.py
index 64f91b0f129..ba5f67f5116 100644
--- a/hermes_cli/web_routers/status.py
+++ b/hermes_cli/web_routers/status.py
@@ -117,6 +117,16 @@ async def get_health():
"auth_required": bool(getattr(app.state, "auth_required", False))}
[email protected]("/api/health/idle")
+async def get_health_idle(request: Request):
+ """Backend-proven idleness for the Desktop pool's cooperative retirement (token-gated, unlike
+ ``/api/health``: whether a turn is running is activity recon). ``idle`` is True/False/None —
+ None means "cannot prove", which the Desktop treats as busy."""
+ from hermes_cli.web_server_idle_proof import idle_proof
+ _require_token(request)
+ return {"ok": True, **idle_proof()}
+
+
# Profile segment mirrors hermes_cli.profiles._PROFILE_ID_RE. Platform segment mirrors the
# Platform enum's normalized values: built-in members plus plugin directory names
# (lowercased), which allow hyphens as well as underscores (e.g. ``reviewer:foo-bar``).
diff --git a/hermes_cli/web_server_idle_proof.py b/hermes_cli/web_server_idle_proof.py
new file mode 100644
index 00000000000..b0c4618259c
--- /dev/null
+++ b/hermes_cli/web_server_idle_proof.py
@@ -0,0 +1,64 @@
+"""Backend-proven idleness for a Desktop-pooled ``hermes serve`` child.
+
+The Desktop caps local pooled backends (3 by default) and keeps a hard slot lease for the lifetime
+of each child. Its renderer refreshes ``lastActiveAt`` every 60s for every open socket, so a
+bot-tile-pinned resident is "fresh" forever even when it is doing nothing — occupied is not busy.
+When a foreground open finds the pool full, the Desktop may retire one resident, but only one the
+BACKEND itself can prove idle. The renderer's own turn bookkeeping cannot see cron fires
+(``HERMES_DESKTOP=1`` runs the in-process ticker), messaging-platform turns served by a pooled
+backend, or a session blocked on an approval, so it is never the proof.
+
+:func:`idle_proof` reads the same ledgers the SSH idle-exit watchdog trusts
+(:func:`hermes_cli.web_server_idle_exit.turn_in_flight`: running gateway sessions plus running cron
+jobs) and adds the human-input ledgers (open server→client requests, unresolved gateway approvals).
+It fails closed: anything it cannot read yields ``idle: None`` and the Desktop must not retire.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Callable, Optional
+
+from hermes_cli.web_server_idle_exit import turn_in_flight
+
+_log = logging.getLogger(__name__)
+
+_input_probe_failure_logged = False
+
+
+def pending_human_input() -> Optional[int]:
+ """Count of prompts waiting on a human (clarify/approval/sudo/secret requests plus queued
+ gateway approvals); ``None`` when a ledger cannot be read."""
+ global _input_probe_failure_logged
+ try:
+ from tui_gateway import server_requests
+ from tools.approval import pending_gateway_approval_count
+
+ return server_requests.open_request_count() + pending_gateway_approval_count()
+ except Exception:
+ if not _input_probe_failure_logged:
+ _input_probe_failure_logged = True
+ _log.warning("idle-proof input probe unavailable; this backend will report indeterminate",
+ exc_info=True)
+ return None
+
+
+def idle_proof(turn_probe: Callable[[], Optional[bool]] = turn_in_flight,
+ input_probe: Callable[[], Optional[int]] = pending_human_input) -> dict:
+ """``{"idle": True | False | None, "reason": str | None}``.
+
+ ``True`` only when no turn is in flight (session table AND cron ledger) and nothing is waiting
+ on a human. ``None`` whenever either probe is indeterminate — the caller treats it exactly like
+ busy.
+ """
+ turn = turn_probe()
+ if turn is None:
+ return {"idle": None, "reason": "turn_probe_unavailable"}
+ if turn:
+ return {"idle": False, "reason": "turn_in_flight"}
+ pending = input_probe()
+ if pending is None:
+ return {"idle": None, "reason": "input_probe_unavailable"}
+ if pending:
+ return {"idle": False, "reason": "awaiting_human_input"}
+ return {"idle": True, "reason": None}
diff --git a/tests/hermes_cli/test_web_server_idle_proof.py b/tests/hermes_cli/test_web_server_idle_proof.py
new file mode 100644
index 00000000000..eb27be4e934
--- /dev/null
+++ b/tests/hermes_cli/test_web_server_idle_proof.py
@@ -0,0 +1,180 @@
+"""A Desktop-pooled ``hermes serve`` child must PROVE it is idle before the Desktop may retire it
+for a foreground open (supersedes #104871, whose idle signal was renderer bookkeeping).
+
+Occupied is not busy: the renderer keeps every pinned tile's backend keepalive-fresh forever, so
+the Desktop needs the backend's own ledgers — running sessions, running cron jobs (the desktop
+child runs the in-process ticker), and prompts waiting on a human. Anything unreadable is
+``None`` and the caller treats it as busy.
+"""
+
+import os
+import socket
+import subprocess
+import sys
+import threading
+import urllib.error
+import urllib.request
+import json
+from pathlib import Path
+
+import pytest
+
+from hermes_cli.web_server_idle_proof import idle_proof, pending_human_input
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+
+def test_idle_proof_is_true_only_when_every_ledger_is_provably_empty():
+ assert idle_proof(turn_probe=lambda: False, input_probe=lambda: 0) == {"idle": True, "reason": None}
+ assert idle_proof(turn_probe=lambda: True, input_probe=lambda: 0)["idle"] is False
+ assert idle_proof(turn_probe=lambda: False, input_probe=lambda: 1) == {
+ "idle": False, "reason": "awaiting_human_input"}
+ # Fail closed: an indeterminate probe is never reported as idle.
+ assert idle_proof(turn_probe=lambda: None, input_probe=lambda: 0)["idle"] is None
+ assert idle_proof(turn_probe=lambda: False, input_probe=lambda: None)["idle"] is None
+
+
+def test_idle_proof_reads_the_real_cron_and_human_input_ledgers():
+ """The probe must see a running cron job (invisible to the renderer) and a pending approval
+ or open clarify request in the live process ledgers, not a renderer-published flag."""
+ import cron.scheduler as scheduler
+ from tools import approval
+ from tui_gateway import server_requests
+
+ assert idle_proof()["idle"] is True
+
+ with scheduler._running_lock:
+ scheduler._running_job_ids.add("idle-proof-live-job")
+ try:
+ assert idle_proof() == {"idle": False, "reason": "turn_in_flight"}
+ finally:
+ with scheduler._running_lock:
+ scheduler._running_job_ids.discard("idle-proof-live-job")
+
+ from tools.approval_gateway_wait import _ApprovalEntry
+
+ entry = _ApprovalEntry({"request_id": "idle-proof-approval"})
+ with approval._lock:
+ approval._gateway_queues.setdefault("idle-proof-session", []).append(entry)
+ try:
+ assert pending_human_input() == 1
+ assert idle_proof() == {"idle": False, "reason": "awaiting_human_input"}
+ finally:
+ with approval._lock:
+ approval._gateway_queues.pop("idle-proof-session", None)
+
+ req = server_requests.ServerRequest("sid-idle-proof", "clarify", {})
+ with server_requests._lock:
+ server_requests._open[req.id] = req
+ try:
+ assert idle_proof()["idle"] is False
+ finally:
+ with server_requests._lock:
+ server_requests._open.pop(req.id, None)
+
+ assert idle_proof()["idle"] is True
+
+
+# ---------------------------------------------------------------------------
+# Live children: three real desktop-shaped ``serve`` processes, one held busy
+# ---------------------------------------------------------------------------
+
+pytestmark_live = pytest.mark.skipif(sys.platform == "win32", reason="POSIX serve-runner path under test")
+
+TOKEN = "idle-proof-live-token"
+
+
+def _spawn_desktop_child(tmp_path: Path, name: str, *, busy: bool) -> subprocess.Popen:
+ """Mirror the Desktop pool spawn: ``HERMES_DESKTOP=1`` (in-process cron ticker), a per-child
+ HERMES_HOME, an ephemeral port, the session token the Desktop probes with. The busy child
+ registers a cron run in the scheduler's running-job ledger before it serves — the same
+ ledger a real fire uses and the one the probe reads."""
+ home = tmp_path / name
+ home.mkdir()
+ env = dict(os.environ)
+ env.pop("PYTHONPATH", None)
+ for k in ("HERMES_PARENT_PID", "HERMES_PARENT_START_MARKER", "HERMES_PARENT_NONCE"):
+ env.pop(k, None)
+ env.update(
+ HERMES_HOME=str(home),
+ HERMES_SERVE_HEADLESS="1",
+ HERMES_DESKTOP="1",
+ HERMES_DASHBOARD_SESSION_TOKEN=TOKEN,
+ PYTHONUNBUFFERED="1",
+ )
+ hold = (
+ "import cron.scheduler as s\n"
+ "with s._running_lock:\n"
+ " s._running_job_ids.add('live-idle-proof-job')\n"
+ ) if busy else ""
+ code = (
+ hold
+ + "from hermes_cli.web_server import start_server\n"
+ "start_server(host='127.0.0.1', port=0, open_browser=False, headless=True)\n"
+ )
+ return subprocess.Popen(
+ [sys.executable, "-c", code], cwd=str(REPO_ROOT), env=env,
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
+ )
+
+
+def _read_until(proc: subprocess.Popen, token: str, timeout: float = 120.0):
+ lines: list[str] = []
+ hit = threading.Event()
+
+ def _pump():
+ assert proc.stdout is not None
+ for line in proc.stdout:
+ lines.append(line)
+ if token in line:
+ hit.set()
+ return
+
+ threading.Thread(target=_pump, daemon=True).start()
+ hit.wait(timeout)
+ return hit.is_set(), lines
+
+
+def _probe(port: int, token: str | None = TOKEN) -> tuple[int, dict]:
+ req = urllib.request.Request(f"http://127.0.0.1:{port}/api/health/idle",
+ headers={"X-Hermes-Session-Token": token} if token else {})
+ try:
+ with urllib.request.urlopen(req, timeout=10) as resp:
+ return resp.status, json.loads(resp.read().decode())
+ except urllib.error.HTTPError as exc:
+ return exc.code, {}
+
+
+@pytestmark_live
+def test_live_pooled_children_prove_idle_or_busy_over_the_desktop_probe(tmp_path):
+ """Three real children at the Desktop's pool cap; exactly one is busy. The Desktop's probe
+ must get ``idle: false`` from the busy one and ``idle: true`` from the two residents that are
+ merely occupied. The probe is token-gated: an unauthenticated caller learns nothing."""
+ children = {
+ "resident-a": _spawn_desktop_child(tmp_path, "resident-a", busy=False),
+ "resident-b": _spawn_desktop_child(tmp_path, "resident-b", busy=False),
+ "cron-busy": _spawn_desktop_child(tmp_path, "cron-busy", busy=True),
+ }
+ try:
+ ports = {}
+ for name, proc in children.items():
+ ready, lines = _read_until(proc, "HERMES_BACKEND_READY")
+ assert ready, f"{name}: no READY sentinel; output:\n{''.join(lines)}"
+ ready_line = next(l for l in lines if "HERMES_BACKEND_READY" in l)
+ ports[name] = int(ready_line.strip().rsplit("port=", 1)[1])
+
+ verdicts = {name: _probe(port) for name, port in ports.items()}
+ assert verdicts["resident-a"] == (200, {"ok": True, "idle": True, "reason": None}), verdicts
+ assert verdicts["resident-b"] == (200, {"ok": True, "idle": True, "reason": None}), verdicts
+ assert verdicts["cron-busy"] == (200, {"ok": True, "idle": False, "reason": "turn_in_flight"}), verdicts
+
+ status, body = _probe(ports["resident-a"], token=None)
+ assert status == 401 and "idle" not in body
+ finally:
+ for proc in children.values():
+ proc.terminate()
+ for proc in children.values():
+ try:
+ proc.wait(timeout=30)
+ except subprocess.TimeoutExpired:
+ proc.kill()
diff --git a/tools/approval.py b/tools/approval.py
index c22d304fa7c..8f482df8527 100644
--- a/tools/approval.py
+++ b/tools/approval.py
@@ -204,6 +204,12 @@ def has_blocking_approval(session_key: str) -> bool:
return bool(_gateway_queues.get(session_key))
+def pending_gateway_approval_count() -> int:
+ """Unresolved gateway approvals across every session — a backend blocked on one is not idle."""
+ with _lock:
+ return sum(len(queue) for queue in _gateway_queues.values())
+
+
def get_pending_gateway_approval(session_key: str) -> dict | None:
"""Copy of the oldest unresolved gateway approval, for reconnecting clients
to restore a prompt. Read-only snapshot — the queue stays authoritative."""
diff --git a/tui_gateway/server_requests.py b/tui_gateway/server_requests.py
index 564374704ea..7a9ae4b6edb 100644
--- a/tui_gateway/server_requests.py
+++ b/tui_gateway/server_requests.py
@@ -233,6 +233,13 @@ def open_requests(sid: str) -> list[dict]:
return [req.snapshot() for req in reqs]
+def open_request_count() -> int:
+ """Unanswered server→client requests across every session: the process is waiting on a
+ human (clarify, approval, sudo, secret, ...) and must not be treated as idle."""
+ with _lock:
+ return len(_open)
+
+
def pending_kind(sid: str) -> str:
"""Method of the oldest open request for *sid* ("" when none) — the session is waiting on a human."""
with _lock: