The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): make startup_orphan_reap recoverable and move its config onto dashboard.*
Teknium47d6ce78a249
diff --git a/cli-config.yaml.example b/cli-config.yaml.exampleindex bdbd9e43fe3..423426a546f 100644--- a/cli-config.yaml.example+++ b/cli-config.yaml.example@@ -879,18 +879,18 @@ max_concurrent_sessions: null# explicitly want one shared "room brain" per group/channel.group_sessions_per_user: true-# Session storage maintenance (state.db).-sessions:- # Close tui/desktop/subagent session rows orphaned by a dead gateway- # process. The normal disconnect cleanup runs on an in-process grace- # timer, so a gateway restart (update, crash, systemd) leaves those rows- # permanently "active". On every gateway boot — stdio TUI *and* the- # desktop/dashboard WS sidecar — rows whose start time AND newest message- # are both older than the session TTL (HERMES_TUI_SESSION_TTL_S, default- # 6h) are closed with end_reason "startup_orphan_reap". Messaging-platform- # sessions (Telegram, Discord, ...) are never touched; live in-memory- # sessions are excluded; swept sessions stay resumable.- orphan_reaper: true+# Startup sweep of session rows orphaned by a dead gateway process.+# The normal disconnect cleanup runs on an in-process grace timer, so a+# gateway restart (update, crash, systemd) leaves those rows permanently+# "active". On every gateway boot — stdio TUI *and* the desktop/dashboard+# WS sidecar — tui/desktop/subagent rows whose start time AND newest+# message are both older than the session TTL (HERMES_TUI_SESSION_TTL_S,+# default 6h) are closed with end_reason "startup_orphan_reap".+# Messaging-platform sessions (Telegram, Discord, ...) are never touched;+# live in-memory sessions are excluded; swept sessions stay resumable.+#+# dashboard:+# startup_orphan_sweep: true# ─────────────────────────────────────────────────────────────────────────────# API Server — per-client model routingdiff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 23c52ad362d..996ec308eea 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1593,6 +1593,18 @@ DEFAULT_CONFIG = {# override for backward compatibility. 0 disables the reap# (park forever)."ws_orphan_reap_grace_s": 20.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 disconnected+ # sessions ``ended_at IS NULL`` forever — phantom "active" rows in+ # /resume and dashboards. On every gateway boot (stdio TUI *and*+ # the desktop/dashboard WS sidecar), tui/desktop/subagent rows whose+ # start time AND newest message are both older than the session TTL+ # (HERMES_TUI_SESSION_TTL_S, default 6h) are closed with+ # end_reason='startup_orphan_reap'. Messaging-gateway sessions+ # (telegram, discord, ...) are never touched; live in-memory+ # sessions are excluded; swept sessions stay resumable.+ "startup_orphan_sweep": True,# OAuth gate configuration (engaged when ``--host`` is set and# ``--insecure`` is not). The bundled Nous Portal plugin reads# both keys at startup; they are the canonical surface for these@@ -3208,17 +3220,6 @@ DEFAULT_CONFIG = {# the sweep on every CLI invocation). Tracked via state_meta in# state.db itself, so it's shared across all processes."min_interval_hours": 24,- # Close tui/desktop/subagent session rows orphaned by a dead gateway- # process (#65194). The ws-orphan grace timer is in-process, so a- # gateway restart leaves disconnected sessions ``ended_at IS NULL``- # forever — phantom "active" rows in /resume and dashboards. On- # every gateway boot (stdio TUI *and* the desktop/dashboard WS- # sidecar), rows whose start time AND newest message are both older- # than the session TTL (HERMES_TUI_SESSION_TTL_S, default 6h) are- # closed with end_reason='startup_orphan_reap'. Messaging-gateway- # sessions (telegram, discord, ...) are never touched; swept- # sessions stay resumable. Live in-memory sessions are excluded.- "orphan_reaper": True,# Legacy per-session JSON snapshot writer. When true, the agent# rewrites ``~/.hermes/sessions/session_{sid}.json`` on every turn# boundary with the full message list. state.db is canonical anddiff --git a/hermes_state_common.py b/hermes_state_common.pyindex 111818bbc04..44e8b91498b 100644--- a/hermes_state_common.py+++ b/hermes_state_common.py@@ -211,6 +211,11 @@ _RECOVERABLE_END_REASONS = (# session.resume of the same stored session (no reclaimed broadcast);# the stored session stays resumable like any accidental end."superseded_by_resume",+ # Startup sweep of rows orphaned by a dead gateway process (#65194):+ # the in-process ws-orphan grace timer died with the process, so the+ # row was closed at the next boot instead. Same accident class as+ # ws_orphan_reap — kept distinct for forensics — and equally resumable.+ "startup_orphan_reap",)_RECOVERABLE_END_REASONS_SQL = ", ".join(f"'{reason}'" for reason in _RECOVERABLE_END_REASONS)diff --git a/tests/tui_gateway/test_startup_orphan_sweep.py b/tests/tui_gateway/test_startup_orphan_sweep.pyindex 971c2129ffa..38c3e11e7f0 100644--- a/tests/tui_gateway/test_startup_orphan_sweep.py+++ b/tests/tui_gateway/test_startup_orphan_sweep.py@@ -5,8 +5,8 @@ A gateway restart destroys the in-process ws-orphan grace timersprevious process stay ``ended_at IS NULL`` forever. Both gateway entrypoints — stdio ``entry.main()`` and the desktop/dashboard WS sidecar``handle_ws`` — must schedule a DB-level sweep, gated by-``sessions.orphan_reaper`` (default on) and the gateway's session TTL,-without ever blocking or crashing startup.+``dashboard.startup_orphan_sweep`` (default on) and the gateway's session+TTL, without ever blocking or crashing startup."""from __future__ import annotations@@ -56,6 +56,51 @@ class TestSweepOrphanedSessionRows:assert row["ended_at"] is not Noneassert row["end_reason"] == "startup_orphan_reap"+ def test_swept_row_stays_resumable(self, monkeypatch, tmp_path):+ """A stranded 'active' row (ended_at NULL, no live runtime) is swept+ AND still resumable afterward (#65194 salvage requirement).++ ``startup_orphan_reap`` must be in the recoverable accidental-end set:+ recovery (find_latest_gateway_session_for_peer), canonical-chat+ resurrection (unarchive_recoverable_session), and reset promotion all+ fence on ``_RECOVERABLE_END_REASONS`` — a sweep that used a+ non-recoverable reason would make the restart LOSE the session+ instead of merely closing its phantom row.+ """+ db = SessionDB(tmp_path / "state.db")+ stale = time.time() - 8 * 3600+ _seed_session(db, "stranded-tui", source="tui", last_active=stale)+ with db._lock:+ db._conn.execute(+ "UPDATE sessions SET session_key = ? WHERE id = ?",+ ("tui:peer-1", "stranded-tui"),+ )+ db._conn.commit()+ monkeypatch.setattr(server, "_get_db", lambda: db)+ monkeypatch.setattr(server, "_SESSION_TTL_S", float(IDLE_S))+ monkeypatch.setattr(server, "_sessions", {}) # no live runtime++ assert server._sweep_orphaned_session_rows() == ["stranded-tui"]+ row = db.get_session("stranded-tui")+ assert row["ended_at"] is not None+ assert row["end_reason"] == "startup_orphan_reap"++ # The distinct reason is a recoverable accident, not a boundary.+ assert "startup_orphan_reap" in SessionDB.RECOVERABLE_END_REASONS++ # Peer-keyed recovery still surfaces the swept row...+ recovered = db.find_latest_gateway_session_for_peer(+ source="tui", session_key="tui:peer-1"+ )+ assert recovered is not None+ assert recovered["id"] == "stranded-tui"++ # ...and the session.resume path (reopen_session) fully revives it.+ db.reopen_session("stranded-tui")+ revived = db.get_session("stranded-tui")+ assert revived["ended_at"] is None+ assert revived["end_reason"] is None+def test_spares_fresh_row_with_old_copied_history(self, monkeypatch, tmp_path):db = SessionDB(tmp_path / "state.db")old_history = time.time() - 8 * 3600@@ -161,9 +206,9 @@ class TestScheduleStartupOrphanSweep:server._schedule_startup_orphan_sweep()assert started["count"] == 1- def test_config_flag_reads_sessions_orphan_reaper(self, monkeypatch):+ def test_config_flag_reads_dashboard_startup_orphan_sweep(self, monkeypatch):monkeypatch.setattr(- server, "_load_cfg", lambda: {"sessions": {"orphan_reaper": False}}+ server, "_load_cfg", lambda: {"dashboard": {"startup_orphan_sweep": False}})assert server._session_orphan_reaper_enabled() is Falsediff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex a90878218f5..a05d7816ea7 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1612,18 +1612,20 @@ def _start_idle_reaper() -> None:# (stdio `entry.main` and the WS sidecar's `handle_ws`) — desktop/dashboard# never run `entry.main()`. state.db is shared by sibling processes on the# same profile, so eligibility is conservative. Disable via-# `sessions.orphan_reaper: false` (default on).+# `dashboard.startup_orphan_sweep: false` (default on)._ORPHAN_SWEEP_SOURCES = ("tui", "desktop", "subagent")_startup_orphan_sweep_ran = False_startup_orphan_sweep_lock = threading.Lock()def _session_orphan_reaper_enabled() -> bool:- """``sessions.orphan_reaper`` (default on). Fail-open on config errors."""+ """``dashboard.startup_orphan_sweep`` (default on). Fail-open on errors."""try:- sessions_cfg = (_load_cfg() or {}).get("sessions") or {}- if isinstance(sessions_cfg, dict) and "orphan_reaper" in sessions_cfg:- return is_truthy_value(sessions_cfg.get("orphan_reaper"), default=True)+ dashboard_cfg = (_load_cfg() or {}).get("dashboard") or {}+ if isinstance(dashboard_cfg, dict) and "startup_orphan_sweep" in dashboard_cfg:+ return is_truthy_value(+ dashboard_cfg.get("startup_orphan_sweep"), default=True+ )# Fail-open: a missing key (raw yaml, no DEFAULT_CONFIG merge on# this loader) must keep the sweep on.return True@@ -1688,7 +1690,7 @@ def _schedule_startup_orphan_sweep() -> None:right after a restart can ``session.resume`` its row before the sweepreads the DB. ``HERMES_TUI_WS_ORPHAN_REAP_GRACE_S=0`` (park forever)and ``HERMES_TUI_SESSION_TTL_S=0`` both suppress the sweep; so does- ``sessions.orphan_reaper: false``.+ ``dashboard.startup_orphan_sweep: false``."""global _startup_orphan_sweep_ranif _WS_ORPHAN_REAP_GRACE_S <= 0 or _SESSION_TTL_S <= 0:diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 587ae624cd8..3cfa3765643 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -2183,17 +2183,6 @@ group_sessions_per_user: true # true = per-user isolation in groups/channels, fFor the behavior details and examples, see [Sessions](/user-guide/sessions) and the [Discord guide](/user-guide/messaging/discord).-## Session Maintenance--Session rows live in `~/.hermes/state.db`. Automatic maintenance is configured under `sessions` in `config.yaml`:--```yaml-sessions:- orphan_reaper: true # Close tui/desktop/subagent rows orphaned by a dead gateway process-```--**Orphan reaper** (`orphan_reaper`, default `true`): the TUI/desktop gateway normally closes a disconnected session's row after a short in-process grace timer. If the gateway restarts (update, crash, systemd) before the timer fires, the row stays open forever and shows up as 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.-## Unauthorized DM BehaviorControl what Hermes does when an unknown user sends a direct message:@@ -2622,6 +2611,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)+ startup_orphan_sweep: true # Close session rows orphaned by a dead gateway process at boot```- `theme` — dashboard visual theme.@@ -2630,3 +2620,4 @@ 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.)+- `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.