The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): keep detached sessions alive while a background process will notify them
Ben Barclayff63499e900f
diff --git a/tests/tui_gateway/test_detached_process_notify_keepalive.py b/tests/tui_gateway/test_detached_process_notify_keepalive.pynew file mode 100644index 00000000000..acba23506ce--- /dev/null+++ b/tests/tui_gateway/test_detached_process_notify_keepalive.py@@ -0,0 +1,133 @@+"""A detached Desktop/TUI session waiting on a background process's completion notice must survive the reapers.++The agent starts ``terminal(background=True, notify_on_complete=True)`` and ends its turn on "I'll report back".+The completion reaches the model only through that session's notification poller, and closing the session kills+the process (``agent_close``). The LRU cap evicted such sessions seconds after the turn ended, so the process died+with exit -15, no completion was ever delivered, and the promised follow-up silently never happened.+"""++from __future__ import annotations++import importlib+import threading+import time+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest+++def server(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(home))+ with patch.dict("sys.modules", {"hermes_cli.env_loader": MagicMock(), "hermes_cli.banner": MagicMock()}):+ mod = importlib.import_module("tui_gateway.server")+ yield mod+ mod._sessions.clear()+ mod._pending_ws_reaps.clear()+++def registry():+ from tools.process_registry import process_registry++ saved = dict(process_registry._running)+ process_registry._running.clear()+ yield process_registry+ process_registry._running.clear()+ process_registry._running.update(saved)+++class _Timer:+ created: list = []++ def __init__(self, delay, callback):+ self.delay, self.callback = delay, callback+ _Timer.created.append(self)++ def start(self):+ pass++ def cancel(self):+ pass+++def detached(server, monkeypatch):+ _Timer.created = []+ monkeypatch.setattr(server.threading, "Timer", _Timer)+ monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 20)+ monkeypatch.setattr(server, "_session_has_active_delegations", lambda *a: False)+ popped = []+ monkeypatch.setattr(server, "_teardown_popped_session", lambda s, **kw: popped.append(s))+ sid = "sid-detached-proc"+ session = {+ "session_key": "desktop-proc-session",+ "transport": server._detached_ws_transport,+ "running": False,+ "history_lock": threading.Lock(),+ "last_active": 0.0,+ "created_at": 0.0,+ }+ server._sessions[sid] = session+ return sid, session, popped+++def _spawn(registry, session_key: str, **kw):+ from tools.process_registry import ProcessSession++ proc = ProcessSession(id=f"proc_{len(registry._running)}", command="hermes -p reviewer chat",+ session_key=session_key, started_at=time.time(), **kw)+ registry._running[proc.id] = proc+ return proc++[email protected]("notify", [{"notify_on_complete": True}, {"watch_patterns": ["VERDICT"]}])+def test_cap_and_ttl_reapers_spare_session_with_pending_process_notice(server, registry, detached, notify):+ sid, session, _ = detached+ assert server._session_is_reapable(sid, session) # idle and clientless: evictable today++ _spawn(registry, session["session_key"], **notify)++ assert not server._session_is_reapable(sid, session)+ assert not server._session_is_evictable(sid, session, time.time() + 10 * 86400)+++def test_orphan_reap_rearms_while_process_will_notify(server, registry, detached):+ sid, session, popped = detached+ _spawn(registry, session["session_key"], notify_on_complete=True)++ server._schedule_ws_orphan_reap(sid)+ _Timer.created[-1].callback()++ assert server._sessions.get(sid) is session and not popped+ assert server._pending_ws_reaps[sid] is _Timer.created[-1]+++def test_session_released_once_process_exits(server, registry, detached):+ sid, session, popped = detached+ proc = _spawn(registry, session["session_key"], notify_on_complete=True)+ proc.exited = True++ server._schedule_ws_orphan_reap(sid)+ _Timer.created[-1].callback()++ assert sid not in server._sessions and popped == [session]+++def test_silent_background_process_does_not_pin_session(server, registry, detached):+ """A process nobody asked to hear from (a dev server) must not make its session immortal."""+ sid, session, _ = detached+ _spawn(registry, session["session_key"])++ assert server._session_is_reapable(sid, session)+++def test_another_sessions_process_does_not_pin_session(server, registry, detached):+ sid, session, _ = detached+ _spawn(registry, "some-other-session", notify_on_complete=True)++ assert server._session_is_reapable(sid, session)diff --git a/tui_gateway/session_lifecycle.py b/tui_gateway/session_lifecycle.pyindex 86313fa9734..a5c1993e925 100644--- a/tui_gateway/session_lifecycle.py+++ b/tui_gateway/session_lifecycle.py@@ -1016,9 +1016,11 @@ def _schedule_ws_orphan_reap(if _session_has_active_delegations(sid, current) or (not current.get("running")and not current.get("_client_gone_interrupt_requested")- and _session_owns_live_wakeup_schedule(current)):- # Live background work, or an active /loop or /heartbeat only this process's poller can fire. A- # settled client-gone interrupt wins over the schedule: its latches block every tick and reattach.+ and (_session_owns_live_wakeup_schedule(current)+ or _session_owns_pending_process_notification(current))):+ # Live background work, or a wake-up only this process's poller can deliver: an active /loop or+ # /heartbeat, or a running process that will notify this session. A settled client-gone interrupt+ # wins over both: its latches block every tick and reattach.reschedule_delay = _WS_ORPHAN_REAP_GRACE_Selif not current.get("running"):session = _pop_session_by_id(sid)diff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.pyindex f369786c9fd..ae2f9ef7c16 100644--- a/tui_gateway/session_notifications.py+++ b/tui_gateway/session_notifications.py@@ -322,6 +322,19 @@ def _session_owns_live_wakeup_schedule(session: dict) -> bool:return False+def _session_owns_pending_process_notification(session: dict) -> bool:+ """True while a background process this session started will report back into it (``notify_on_complete`` or+ ``watch_patterns``) and is still running. The completion reaches the model only through THIS session's+ notification poller, and closing the session kills the process (``agent_close``), so the reapers must keep it+ alive. Bounded by the process itself: it releases the session the moment it exits."""+ keys = {str(session.get("session_key") or ""), _session_lookup_key(session)} - {""}+ if not keys:+ return False+ from tools.process_registry import process_registry+ return any(proc["status"] == "running" and (proc.get("notify_on_complete") or proc.get("watch_patterns"))+ for key in keys for proc in process_registry.list_sessions(session_key=key))++def _maybe_fire_tui_loop_tick(sid: str, session: dict) -> None:"""Fire a due /loop wakeup for an idle TUI/Desktop/dashboard session (per-session poller, coarse cadence). Claimsthe session (running=True) before dispatching so a racing user prompt wins; the post-turn hook completes the tick."""diff --git a/tui_gateway/session_reaper.py b/tui_gateway/session_reaper.pyindex 6c6eb4c286f..e156a3f111f 100644--- a/tui_gateway/session_reaper.py+++ b/tui_gateway/session_reaper.py@@ -240,10 +240,12 @@ def _sessions_quiescent(exclude: str | None = None) -> bool:def _session_is_reapable(sid: str, session: dict) -> bool:- """Reaper eligibility: the LRU exemptions, and not the sole driver of an active /loop or /heartbeat- (closing the session stops the notification poller that fires it, freezing the schedule until a client- reattaches). Kept out of ``_sessions_quiescent``: an idle looping session does not block a memory trim."""- return _session_is_lru_evictable(sid, session) and not _session_owns_live_wakeup_schedule(session)+ """Reaper eligibility: the LRU exemptions, and not the sole receiver of a pending wake-up — an active /loop or+ /heartbeat, or a running background process that will notify it (closing the session stops the notification+ poller that delivers both, and ``agent_close`` kills the process). Kept out of ``_sessions_quiescent``: an idle+ session waiting on a wake-up does not block a memory trim."""+ return (_session_is_lru_evictable(sid, session) and not _session_owns_live_wakeup_schedule(session)+ and not _session_owns_pending_process_notification(session))def _session_is_evictable(sid: str, session: dict, now: float) -> bool: