The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui-gateway): gate the ws-orphan interrupt of running turns on activity staleness
Teknium67de93862c39
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex ae73c74eb55..c6a6a977b5b 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1733,6 +1733,15 @@ DEFAULT_CONFIG = {# override for backward compatibility. 0 disables the reap# (park forever)."ws_orphan_reap_grace_s": 20.0,+ # Activity-staleness threshold (seconds) gating the WS-orphan+ # interrupt of a detached RUNNING turn (#98028/#100325). A+ # client-absent turn is only interrupted once its agent activity+ # clock (the same one the agent.turn_liveness watchdog samples —+ # stamped by API waits, stream tokens, tool heartbeats) has been+ # idle at least this long; an actively-working detached turn runs+ # to completion. Default matches agent.turn_liveness.timeout_s.+ # 0 restores the old interrupt-at-grace-regardless behavior.+ "ws_orphan_activity_stale_s": 600.0,# Startup sweep of session rows orphaned by a dead gateway process# (#65194). The ws-orphan grace timer above is in-process, so a# gateway restart (update, crash, systemd) leaves disconnecteddiff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.pyindex 08ecdcfd6e1..49a27a1cf19 100644--- a/tests/test_tui_gateway_server.py+++ b/tests/test_tui_gateway_server.py@@ -5765,6 +5765,147 @@ def test_ws_orphan_reap_disabled_when_grace_zero(monkeypatch):assert fired["timer"] is False+def test_ws_orphan_reap_defers_running_turn_with_fresh_activity(monkeypatch):+ """#98028/#100325: a client-absent turn whose activity clock is fresh is+ NOT interrupted — it keeps running detached and the reaper re-polls at the+ grace interval. Once the clock goes stale the wedged-turn interrupt fires,+ and after the turn settles the session is reaped as before."""+ callbacks = []+ delays = []+ interrupted = []+ torn_down = []++ class _Timer:+ def __init__(self, delay, callback):+ delays.append(delay)+ callbacks.append(callback)+ self.daemon = False++ def start(self):+ return None++ activity = {"seconds_since_activity": 1.0}+ agent = types.SimpleNamespace(+ get_activity_summary=lambda: dict(activity),+ interrupt=lambda message=None: interrupted.append("interrupted"),+ )++ class _DeadThread:+ def is_alive(self):+ return False++ session = _session(+ agent=agent,+ transport=server._detached_ws_transport,+ running=True,+ _run_thread=_DeadThread(),+ )+ server._sessions["fresh-sid"] = session+ monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0.01)+ monkeypatch.setattr(server, "_WS_ORPHAN_ACTIVITY_STALE_S", 300.0)+ monkeypatch.setattr(server.threading, "Timer", _Timer)+ monkeypatch.setattr(server, "_load_cfg", lambda: {})+ monkeypatch.setattr(+ server,+ "_teardown_popped_session",+ lambda claimed, *, end_reason: torn_down.append((claimed, end_reason)) or True,+ )++ try:+ server._schedule_ws_orphan_reap("fresh-sid")++ # Two grace cycles with fresh activity: no interrupt, reschedule at+ # the GRACE interval (not the 1s interrupt-settle poll).+ for _ in range(2):+ callbacks.pop(0)()+ assert interrupted == []+ assert not session.get("_client_gone_interrupt_requested")+ assert delays[-1] == server._WS_ORPHAN_REAP_GRACE_S+ assert "fresh-sid" in server._sessions++ # Activity goes stale (turn wedged) -> interrupt fires on next poll.+ activity["seconds_since_activity"] = 301.0+ callbacks.pop(0)()+ assert interrupted == ["interrupted"]+ assert session["_client_gone_interrupt_requested"] is True++ # Turn settles -> reap proceeds exactly as today.+ session["running"] = False+ callbacks.pop(0)()+ assert "fresh-sid" not in server._sessions+ assert torn_down == [(session, "ws_orphan_reap")]+ finally:+ server._sessions.pop("fresh-sid", None)+++def test_ws_orphan_activity_gate_zero_restores_interrupt_at_grace(monkeypatch):+ """ws_orphan_activity_stale_s=0 opts out: fresh activity no longer defers+ the client-gone interrupt (pre-#98028 behaviour)."""+ callbacks = []+ interrupted = []++ class _Timer:+ def __init__(self, _delay, callback):+ callbacks.append(callback)+ self.daemon = False++ def start(self):+ return None++ class _LiveThread:+ def is_alive(self):+ return True++ agent = types.SimpleNamespace(+ get_activity_summary=lambda: {"seconds_since_activity": 0.5},+ interrupt=lambda message=None: interrupted.append("interrupted"),+ )+ session = _session(+ agent=agent,+ transport=server._detached_ws_transport,+ running=True,+ _run_thread=_LiveThread(),+ )+ server._sessions["optout-sid"] = session+ monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0.01)+ monkeypatch.setattr(server, "_WS_ORPHAN_ACTIVITY_STALE_S", 0.0)+ monkeypatch.setattr(server.threading, "Timer", _Timer)+ monkeypatch.setattr(server, "_load_cfg", lambda: {})++ try:+ server._schedule_ws_orphan_reap("optout-sid")+ callbacks.pop(0)()+ assert interrupted == ["interrupted"]+ assert session["_client_gone_interrupt_requested"] is True+ finally:+ server._sessions.pop("optout-sid", None)+++def test_ws_orphan_activity_gate_unreadable_summary_stays_eligible(monkeypatch):+ """A broken/opaque activity summary must fail CLOSED (not fresh): the+ wedged-turn interrupt-at-grace safety net is preserved."""++ def _boom():+ raise RuntimeError("summary unavailable")++ agent = types.SimpleNamespace(get_activity_summary=_boom)+ monkeypatch.setattr(server, "_WS_ORPHAN_ACTIVITY_STALE_S", 300.0)+ assert server._ws_orphan_turn_activity_is_fresh({"agent": agent}) is False+ # No agent / no summary method: same conservative answer.+ assert server._ws_orphan_turn_activity_is_fresh({"agent": None}) is False+ assert (+ server._ws_orphan_turn_activity_is_fresh(+ {"agent": types.SimpleNamespace()}+ )+ is False+ )+ # Never-stamped clock (None) is not fresh either.+ agent2 = types.SimpleNamespace(+ get_activity_summary=lambda: {"seconds_since_activity": None}+ )+ assert server._ws_orphan_turn_activity_is_fresh({"agent": agent2}) is False++def test_init_session_fires_reset_hook(monkeypatch):hooks = []diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 8eed4f00e4c..470a7b19b8b 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -205,6 +205,40 @@ def _resolve_ws_orphan_reap_grace() -> float:_WS_ORPHAN_REAP_GRACE_S = _resolve_ws_orphan_reap_grace()+++def _resolve_ws_orphan_activity_stale() -> float:+ """Resolve the detached-turn activity staleness threshold (seconds).++ A detached RUNNING turn is only interrupted by the WS-orphan reaper once+ its activity clock has been idle at least this long (#98028/#100325);+ while the turn keeps producing (API waits, stream tokens, tool+ heartbeats all stamp the clock) it runs to completion detached.+ Config-driven via ``dashboard.ws_orphan_activity_stale_s``; the+ ``HERMES_TUI_WS_ORPHAN_ACTIVITY_STALE_S`` env var is an internal+ override. Defaults to 600s, matching the turn-liveness watchdog's idle+ bound (``agent.turn_liveness.timeout_s``) so "wedged" means the same+ thing on both paths. ``0`` disables the gate (pre-#98028 behavior:+ interrupt at grace regardless of activity).+ """+ raw = os.environ.get("HERMES_TUI_WS_ORPHAN_ACTIVITY_STALE_S")+ if raw is None or not str(raw).strip():+ try:+ from hermes_cli.config import load_config++ raw = (load_config().get("dashboard") or {}).get(+ "ws_orphan_activity_stale_s"+ )+ except Exception:+ raw = None+ try:+ stale = float(raw) if raw is not None else 600.0+ except (ValueError, TypeError):+ stale = 600.0+ return max(0.0, stale)+++_WS_ORPHAN_ACTIVITY_STALE_S = _resolve_ws_orphan_activity_stale()_WS_ORPHAN_INTERRUPT_REAP_POLL_S = 1.0# Total budget for the interrupt-then-reap poll chain. If an interrupted turn# never settles (agent thread hung in a syscall, supervisor lost), each 1s poll@@ -1393,6 +1427,34 @@ def _cancel_ws_orphan_reap(sid: str) -> None:pass+def _ws_orphan_turn_activity_is_fresh(session: dict) -> bool:+ """Whether a detached RUNNING turn's activity clock is still fresh.++ Reuses the agent's existing activity summary (``_touch_activity`` is+ stamped by API waits, stream tokens, and tool heartbeats — the same+ clock the turn-liveness watchdog samples; see agent/turn_liveness.py).+ Fresh means the WS-orphan reaper must NOT interrupt the turn yet+ (#98028/#100325): deliberate client absence (closed laptop, backgrounded+ mobile app, desktop update/relaunch) keeps healthy work running detached.++ Conservative fallbacks preserve the wedged-turn safety net: a disabled+ threshold (<= 0), a missing/opaque agent, an unreadable summary, or a+ never-stamped clock all report NOT fresh, i.e. eligible for the+ interrupt-at-grace path exactly as before.+ """+ if _WS_ORPHAN_ACTIVITY_STALE_S <= 0:+ return False+ agent = session.get("agent")+ summary_fn = getattr(agent, "get_activity_summary", None)+ if not callable(summary_fn):+ return False+ try:+ elapsed = summary_fn().get("seconds_since_activity")+ return elapsed is not None and float(elapsed) < _WS_ORPHAN_ACTIVITY_STALE_S+ except Exception:+ return False++def _schedule_ws_orphan_reap(sid: str, *, delay_s: float | None = None) -> None:"""After a grace window, reap session ``sid`` iff it's still orphaned.@@ -1429,30 +1491,47 @@ def _schedule_ws_orphan_reap(sid: str, *, delay_s: float | None = None) -> None:if _session_has_active_delegations(sid, current):reschedule_delay = _WS_ORPHAN_REAP_GRACE_Selif current.get("running"):- # Mid-turn detached sessions must never drop the single- # Timer (#85578): after the reconnect grace the turn is- # interrupted once, then the reap keeps polling until the- # normal turn-finalization path settles.- polls = int(current.get("_client_gone_interrupt_polls") or 0) + 1- current["_client_gone_interrupt_polls"] = polls- if polls > _WS_ORPHAN_INTERRUPT_REAP_MAX_POLLS:- # The interrupted turn never settled inside the budget —- # force-reap rather than parking the session + a timer- # chain forever. Loud by design: this only fires when a- # turn is genuinely stuck past interrupt.- logger.error(- "client_gone sid=%s: turn did not settle after %d "- "interrupt polls (%.0fs) — force-reaping detached "- "session",- sid, polls - 1,- (polls - 1) * _WS_ORPHAN_INTERRUPT_REAP_POLL_S,+ if not current.get(+ "_client_gone_interrupt_requested"+ ) and _ws_orphan_turn_activity_is_fresh(current):+ # Client-absent but actively producing (#98028/#100325):+ # the turn keeps running detached (the sentinel transport+ # already buffers emits) and the reaper re-checks each+ # grace interval. Only a turn whose activity clock has+ # gone stale — genuinely wedged, the case the interrupt+ # was added for — falls through to the interrupt below.+ logger.debug(+ "client_gone sid=%s action=defer (turn activity "+ "fresh; stale threshold %.0fs)",+ sid,+ _WS_ORPHAN_ACTIVITY_STALE_S,)- session = _pop_session_by_id(sid)+ reschedule_delay = _WS_ORPHAN_REAP_GRACE_Selse:- if not current.get("_client_gone_interrupt_requested"):- current["_client_gone_interrupt_requested"] = True- interrupt_session = current- reschedule_delay = _WS_ORPHAN_INTERRUPT_REAP_POLL_S+ # Mid-turn detached sessions must never drop the single+ # Timer (#85578): after the reconnect grace the turn is+ # interrupted once, then the reap keeps polling until the+ # normal turn-finalization path settles.+ polls = int(current.get("_client_gone_interrupt_polls") or 0) + 1+ current["_client_gone_interrupt_polls"] = polls+ if polls > _WS_ORPHAN_INTERRUPT_REAP_MAX_POLLS:+ # The interrupted turn never settled inside the budget+ # — force-reap rather than parking the session + a+ # timer chain forever. Loud by design: this only fires+ # when a turn is genuinely stuck past interrupt.+ logger.error(+ "client_gone sid=%s: turn did not settle after %d "+ "interrupt polls (%.0fs) — force-reaping detached "+ "session",+ sid, polls - 1,+ (polls - 1) * _WS_ORPHAN_INTERRUPT_REAP_POLL_S,+ )+ session = _pop_session_by_id(sid)+ else:+ if not current.get("_client_gone_interrupt_requested"):+ current["_client_gone_interrupt_requested"] = True+ interrupt_session = current+ reschedule_delay = _WS_ORPHAN_INTERRUPT_REAP_POLL_Selse:session = _pop_session_by_id(sid)diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 7e087add374..ef001c8a171 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -2716,6 +2716,7 @@ dashboard:ws_ping_interval: 20.0 # Non-loopback WebSocket keepalive ping interval (seconds)ws_ping_timeout: 20.0 # Non-loopback WebSocket keepalive pong timeout (seconds)ws_orphan_reap_grace_s: 20.0 # Grace before a WS-detached session is reaped (seconds)+ ws_orphan_activity_stale_s: 600.0 # Activity idle bound before a detached RUNNING turn is interrupted (seconds)startup_orphan_sweep: true # Close session rows orphaned by a dead gateway process at boot```@@ -2726,4 +2727,5 @@ dashboard:- `oauth` / `basic_auth` / `drain_auth` — auth provider config read by the bundled dashboard-auth plugins. The drain secret itself is **not** set here; it's provisioned via the `HERMES_DASHBOARD_DRAIN_SECRET` env var. See [Web Dashboard](/user-guide/features/web-dashboard) for full auth setup.- `ws_ping_interval` / `ws_ping_timeout` — WebSocket keepalive tuning for non-loopback binds (loopback connections never ping). Raise these on high-latency links (Tailscale, distant SSH tunnels) where the 20 s defaults can manufacture spurious 1006 disconnects.- `ws_orphan_reap_grace_s` — how long a WS-detached session waits before the orphan reaper collects it. Raise alongside the keepalive values if clients reconnect slowly. (`HERMES_TUI_WS_ORPHAN_REAP_GRACE_S` remains as an internal override.)+- `ws_orphan_activity_stale_s` (default `600`) — how long a detached **running** turn's activity clock (the same clock the `agent.turn_liveness` watchdog samples: API waits, stream tokens, tool heartbeats) must be idle before the orphan reaper interrupts it. A client-absent turn that is still actively producing keeps running to completion detached — closing the laptop, backgrounding the mobile app, or a desktop update no longer cancels healthy long turns; only a genuinely wedged turn is interrupted. Set `0` to interrupt at the grace window regardless of activity (old behavior).- `startup_orphan_sweep` (default `true`) — the WS-orphan reap timer above is in-process, so a gateway restart (update, crash, systemd) before it fires leaves the session row open forever — phantom "active" work in `/resume` and dashboards. On every gateway boot — both the stdio TUI (`entry.main`) and the desktop/dashboard WebSocket sidecar (`handle_ws`) — rows with source `tui` / `desktop` / `subagent` whose start time **and** newest message are both older than the session TTL (`HERMES_TUI_SESSION_TTL_S`, default 6 hours) are closed with `end_reason: startup_orphan_reap`. Messaging-platform sessions (Telegram, Discord, …) are never touched, live in-memory sessions (a client that already resumed) are excluded, and swept sessions remain resumable.