The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): an open TUI reconnects after `hermes gateway stop` instead of discovering forever
Teknium60ed593167ca
diff --git a/tests/tui_gateway/test_gateway_bootstrap_recover.py b/tests/tui_gateway/test_gateway_bootstrap_recover.pyindex e9938b53eb0..4eed73c23d6 100644--- a/tests/tui_gateway/test_gateway_bootstrap_recover.py+++ b/tests/tui_gateway/test_gateway_bootstrap_recover.py@@ -1,4 +1,9 @@-"""Ink reconnect re-ensures a crashed owner, never an explicitly stopped one (W11)."""+"""Ink reconnect re-ensures an owner that is gone, however it went (W11, P2).++Main's TUI owned its own sidecar and never depended on an external daemon, so an open TUI must come+back on its own after ANY end of the shared gateway: a crash, its idle exit, or a planned+`hermes gateway stop` while the TUI is open. The bounded recovery slot (gatewayClient.ts+OWNER_RECOVERY_LIMIT) is what keeps a crash-looping owner from being respawned forever."""from __future__ import annotations@@ -24,24 +29,25 @@ def _load_bootstrap():return module[email protected]("record, ensured", [- ({"gateway_state": "running", "pid": 999999}, True), # SIGKILL / OOM: dead process still claims live- ({"gateway_state": "stopped", "pid": 999999}, False), # `hermes gateway stop`- ({"gateway_state": "running", "desired_state": "stopped"}, False), # durable operator stop intent- # An auto-started owner ended itself (idle exit) while the TUI was suspended: the next client- # starts a fresh one. Its reason, not the bare `stopped`, tells it from an operator stop.- ({"gateway_state": "stopped", "exit_reason": "auto-started gateway idle for 600s "- "(gateway.unmanaged_idle_exit_seconds)"}, True),- ({"gateway_state": "stopped", "exit_reason": "Gateway restart requested"}, False),[email protected]("record", [+ {"gateway_state": "running", "pid": 999999}, # SIGKILL / OOM: dead process still claims live+ {"gateway_state": "stopped", "pid": 999999}, # `hermes gateway stop` while the TUI is open+ {"gateway_state": "running", "desired_state": "stopped"}, # durable operator stop intent+ {"gateway_state": "stopped", "exit_reason": "auto-started gateway idle for 600s "+ "(gateway.unmanaged_idle_exit_seconds)"},+ {"gateway_state": "stopped", "exit_reason": "Gateway restart requested"},+ None, # no record at all])-def test_recover_reensures_only_a_crashed_owner(monkeypatch, tmp_path, record, ensured):+def test_recover_reensures_an_owner_that_is_gone(monkeypatch, tmp_path, record):+ ensured = Truemodule = _load_bootstrap()home = (tmp_path / "home").resolve()home.mkdir()- (home / "gateway_state.json").write_text(json.dumps(record))+ if record is not None:+ (home / "gateway_state.json").write_text(json.dumps(record))monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: home)monkeypatch.setattr(gateway_runtime, "discover_gateway_endpoint",- lambda h, timeout=5: SimpleNamespace(state="absent", endpoint=None, reason_code=None))+ lambda h, timeout=5: SimpleNamespace(state="absent", endpoint=None, reason_code=None, detail=None))calls = []def ensure(h, timeout=30, idle_exit=False):@@ -60,6 +66,26 @@ def test_recover_reensures_only_a_crashed_owner(monkeypatch, tmp_path, record, eassert calls == [][email protected]("observed", [+ SimpleNamespace(state="incompatible", endpoint=None, reason_code="runtime_protocol", detail=None),+ SimpleNamespace(state="starting", endpoint=None, reason_code=None, detail=None),+])+def test_recover_reensures_any_unready_owner(monkeypatch, tmp_path, observed):+ """A reconnect that finds an old (incompatible) owner, or one still starting, ensures like the+ first launch does instead of reporting the same verdict every 30 s."""+ module = _load_bootstrap()+ home = (tmp_path / "home").resolve()+ home.mkdir()+ monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: home)+ monkeypatch.setattr(gateway_runtime, "discover_gateway_endpoint", lambda h, timeout=5: observed)+ calls = []+ monkeypatch.setattr(gateway_runtime, "ensure_gateway_runtime", lambda h, timeout=30, idle_exit=False: (+ calls.append(h), SimpleNamespace(state="starting", endpoint=None, reason_code="deadline", detail=None))[1])+ with pytest.raises(RuntimeError):+ module.bootstrap(False, recover=True)+ assert calls == [home]++def test_failure_names_the_reason_and_its_remedy(monkeypatch, tmp_path):"""The TUI echoes this text; a refusal's detail (what to do) must travel with the verdict."""module = _load_bootstrap()diff --git a/ui-tui/scripts/gateway_bootstrap.py b/ui-tui/scripts/gateway_bootstrap.pyindex a3958515e62..bd88378c0b8 100644--- a/ui-tui/scripts/gateway_bootstrap.py+++ b/ui-tui/scripts/gateway_bootstrap.py@@ -1,11 +1,10 @@"""Ink's private pipe bootstrap; the child is a client, never an agent owner.``--start`` ensures the owner (first launch). A reconnect discovers only, except ``--recover``-re-ensures an owner that is gone without anyone asking: it CRASHED (its retained runtime record-still claims it live) or it ended ITSELF by the auto-started idle exit (``gateway/run_idle_exit.py``,-"the next client starts a fresh gateway" — this reconnecting client is that next client). An-explicitly stopped gateway (``hermes gateway stop`` / a planned stop: ``stopped`` without the idle-exit's reason, or a durable ``desired_state: stopped``) is never resurrected by a reconnect.+(a bounded slot, ``gatewayClient.ts`` ``OWNER_RECOVERY_LIMIT`` per window) re-ensures whenever the+owner is not ready: it crashed, ended by its idle exit, was stopped with ``hermes gateway stop``+while this TUI was open, or an older Hermes's gateway answers (ensure replaces that one). Main's TUI+ran its own sidecar and never depended on an external daemon, so an open TUI comes back on its own."""import contextlibimport json@@ -15,26 +14,6 @@ import syssys.path.insert(0, str(Path(__file__).resolve().parents[2]))-# ``gateway_state`` values only a live owner publishes; ``hermes gateway stop`` and planned stops-# persist ``stopped``, so a dead process still claiming one of these did not stop cleanly.-_LIVE_CLAIMS = frozenset({"running", "starting", "draining", "degraded"})---def owner_crashed(home: Path) -> bool:- """After discovery answered ``absent``: did the owner serving *home* end without anyone asking- (a crash, or its own idle exit while this client was away — suspended, asleep, disconnected)?"""- from gateway.run_idle_exit import IDLE_EXIT_STOP_PREFIX- from gateway.status import read_runtime_status- from hermes_cli.gateway_runtime_multiplex import implied_host_root, multiplexer_serves_home- owner = multiplexer_serves_home(home) or implied_host_root(home) or home- record = read_runtime_status(owner / "gateway_state.json")- if not isinstance(record, dict) or record.get("desired_state") == "stopped":- return False- # The owner's own idle exit (gateway/run_idle_exit.py) persists ``stopped`` with this reason;- # no operator asked for it, and "the next client starts a fresh gateway" is this client.- idle_exited = (record.get("gateway_state") == "stopped"- and str(record.get("exit_reason") or "").startswith(IDLE_EXIT_STOP_PREFIX))- return idle_exited or record.get("gateway_state") in _LIVE_CLAIMSdef failure_message(receipt) -> str:@@ -67,7 +46,7 @@ def bootstrap(start: bool, recover: bool = False) -> dict:os.environ.pop(key, None)receipt = (ensure_gateway_runtime(home, timeout=30, idle_exit=True) if startelse discover_gateway_endpoint(home, timeout=5))- if not start and recover and receipt.state == "absent" and owner_crashed(home):+ if not start and recover and receipt.state != "ready":receipt = ensure_gateway_runtime(home, timeout=30, idle_exit=True)if receipt.state != "ready" or receipt.endpoint is None:raise RuntimeError(failure_message(receipt))diff --git a/ui-tui/src/gatewayClient.ts b/ui-tui/src/gatewayClient.tsindex 0e20dc98390..30859ef4167 100644--- a/ui-tui/src/gatewayClient.ts+++ b/ui-tui/src/gatewayClient.ts@@ -122,8 +122,10 @@ const redactUrl = (raw: string): string => {export interface LocalGatewayGrant { url: string; protocols: string[]; profile_id: string; instance_id: string }// Reconnects after the first launch are discovery-only, except that a bounded number per window-// may re-ensure an owner that crashed (gateway_bootstrap.py --recover decides from the owner's-// retained runtime record; an explicitly stopped gateway is never resurrected).+// re-ensure an owner that is not ready (gateway_bootstrap.py --recover): crashed, idle-exited,+// stopped with `hermes gateway stop` while this TUI is open, or an older Hermes's gateway. Main's+// TUI owned its sidecar, so an open TUI comes back on its own; the budget keeps a crash-looping+// owner from being respawned without pause.export const OWNER_RECOVERY_LIMIT = 3export const OWNER_RECOVERY_WINDOW_MS = 60_000