The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: TUI reconnect re-ensures a crashed gateway owner, never a stopped one
Teknium21bd24e2c188
diff --git a/tests/tui_gateway/test_gateway_bootstrap_recover.py b/tests/tui_gateway/test_gateway_bootstrap_recover.pynew file mode 100644index 00000000000..297c16038ec--- /dev/null+++ b/tests/tui_gateway/test_gateway_bootstrap_recover.py@@ -0,0 +1,55 @@+"""Ink reconnect re-ensures a crashed owner, never an explicitly stopped one (W11)."""++from __future__ import annotations++import importlib.util+import json+from pathlib import Path+from types import SimpleNamespace++import pytest++from hermes_cli import gateway_runtime+import hermes_constants+++_SCRIPT = Path(__file__).resolve().parents[2] / "ui-tui" / "scripts" / "gateway_bootstrap.py"+++def _load_bootstrap():+ spec = importlib.util.spec_from_file_location("ink_gateway_bootstrap_recover_test", _SCRIPT)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ 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+])+def test_recover_reensures_only_a_crashed_owner(monkeypatch, tmp_path, record, ensured):+ module = _load_bootstrap()+ home = (tmp_path / "home").resolve()+ home.mkdir()+ (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))+ calls = []++ def ensure(h, timeout=30):+ calls.append(Path(h))+ return SimpleNamespace(state="starting", endpoint=None, reason_code="deadline")++ monkeypatch.setattr(gateway_runtime, "ensure_gateway_runtime", ensure)++ with pytest.raises(RuntimeError):+ module.bootstrap(False, recover=True)+ assert calls == ([home] if ensured else [])+ # A plain reconnect (no recovery slot) stays discovery-only even for a crashed owner.+ calls.clear()+ with pytest.raises(RuntimeError, match="absent"):+ module.bootstrap(False)+ assert calls == []diff --git a/ui-tui/CANONICAL_GATEWAY.md b/ui-tui/CANONICAL_GATEWAY.mdindex c8b56e03805..2cbf2342887 100644--- a/ui-tui/CANONICAL_GATEWAY.md+++ b/ui-tui/CANONICAL_GATEWAY.md@@ -9,8 +9,10 @@ in an endpoint URL or discovery receipt. Explicit remote URLs remain remote: afailed connection cannot fall back to a local daemon.Closing Ink detaches its socket without stopping the gateway. Reconnection gets-a fresh single-use ticket using discovery only; it cannot resurrect an explicitly-stopped gateway. An initial ensure failure is visible and does not create a rival+a fresh single-use ticket using discovery; when discovery finds no owner but the+owner's retained `gateway_state.json` still claims it live (a crash: SIGKILL, OOM),+up to three reconnects per minute re-ensure it. It never resurrects an explicitly+stopped gateway (`stopped` state or `desired_state: stopped`). An initial ensure failure is visible and does not create a rivalowner. Local profile selection remains the launcher's exact effective HERMES_HOME.Ink requires `runtime.describe.session_create` to advertise the `tui` source and@@ -34,7 +36,7 @@ snapshot restores its pending prompt cards. Stop includes the active generation.The disconnected view keeps its destination. Enter writes a private fsync/renamejournal before clearing the composer; reconnect only resumes that destination.-Discovery keeps retrying without starting a stopped daemon. Confirmed admissions+Discovery keeps retrying without starting a stopped daemon (a crashed one is re-ensured, bounded). Confirmed admissionsare retired from the journal; ambiguous prompt retries preserve their original IDand payload. Unknown executions stay paused: select the row with Up and useCtrl+X to discard it through the generation-bound authority resolver. A refuseddiff --git a/ui-tui/scripts/gateway_bootstrap.py b/ui-tui/scripts/gateway_bootstrap.pyindex 339d8e96459..5c9fc7d5c0d 100644--- a/ui-tui/scripts/gateway_bootstrap.py+++ b/ui-tui/scripts/gateway_bootstrap.py@@ -1,4 +1,10 @@-"""Ink's private pipe bootstrap; the child is a client, never an agent owner."""+"""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 CRASHED: discovery finds none while its retained runtime record still+claims it live and the operator recorded no stop intent. An explicitly stopped gateway (its+record says ``stopped``) is never resurrected by a reconnect.+"""import contextlibimport jsonimport os@@ -7,8 +13,22 @@ 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* die without a clean stop?"""+ 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")+ return (isinstance(record, dict) and record.get("desired_state") != "stopped"+ and record.get("gateway_state") in _LIVE_CLAIMS)+-def bootstrap(start: bool) -> dict:+def bootstrap(start: bool, recover: bool = False) -> dict:from hermes_constants import get_hermes_homefrom hermes_cli.gateway_runtime import control_home_for, discover_gateway_endpoint, ensure_gateway_runtimefrom hermes_cli.gateway_runtime_discovery import connect_private@@ -22,6 +42,8 @@ def bootstrap(start: bool) -> dict:os.environ.pop(key, None)receipt = (ensure_gateway_runtime(home, timeout=30) if startelse discover_gateway_endpoint(home, timeout=5))+ if not start and recover and receipt.state == "absent" and owner_crashed(home):+ receipt = ensure_gateway_runtime(home, timeout=30)if receipt.state != "ready" or receipt.endpoint is None:raise RuntimeError(f"gateway {receipt.state}: {receipt.reason_code or 'not ready'}")endpoint = receipt.endpoint@@ -54,7 +76,7 @@ def bootstrap(start: bool) -> dict:if __name__ == "__main__":try:with contextlib.redirect_stdout(sys.stderr):- result = bootstrap("--start" in sys.argv)+ result = bootstrap("--start" in sys.argv, recover="--recover" in sys.argv)print(json.dumps(result))# Discovery/ticket failures: missing modules, socket/pipe I/O (incl. timeouts), DiscoveryError and# bad JSON (ValueError), rejected grants (RuntimeError), malformed reply shapes. Anything elsediff --git a/ui-tui/src/__tests__/gatewayClient.test.ts b/ui-tui/src/__tests__/gatewayClient.test.tsindex dce14acc735..3cd862706c4 100644--- a/ui-tui/src/__tests__/gatewayClient.test.ts+++ b/ui-tui/src/__tests__/gatewayClient.test.ts@@ -237,6 +237,26 @@ describe('GatewayClient websocket attach mode', () => {} finally { gw.kill(); vi.useRealTimers() }})+ it('re-ensures a crashed owner on a bounded number of reconnects, then stays discovery-only', async () => {+ vi.useFakeTimers()+ delete process.env.HERMES_TUI_GATEWAY_URL+ const grant = { url: 'ws://gateway.test/api/ws', protocols: [], instance_id: 'owner', profile_id: 'fixture' }+ const bootstrap = vi.fn().mockResolvedValueOnce(grant).mockRejectedValue(new Error('gateway absent: not ready'))+ const gw = new GatewayClient(bootstrap)++ try {+ gw.start(); gw.drain()+ await vi.advanceTimersByTimeAsync(0)+ FakeWebSocket.instances[0]!.open()+ await vi.advanceTimersByTimeAsync(0)+ FakeWebSocket.instances[0]!.close()+ // Five reconnects inside one recovery window.+ await vi.advanceTimersByTimeAsync(RECONNECT_BASE_MS * (1 + 2 + 4 + 8 + 16))+ expect(bootstrap.mock.calls.map(([start, recover]) => [start, Boolean(recover)])).toEqual([+ [true, false], [false, true], [false, true], [false, true], [false, false], [false, false]])+ } finally { gw.kill(); vi.useRealTimers() }+ })+it('waits for websocket open and resolves RPC requests', async () => {process.env.HERMES_TUI_GATEWAY_URL = 'ws://gateway.test/api/ws?token=abc'const gw = new GatewayClient()diff --git a/ui-tui/src/gatewayClient.ts b/ui-tui/src/gatewayClient.tsindex 1d8f7fd6e11..a5a1a2cb528 100644--- a/ui-tui/src/gatewayClient.ts+++ b/ui-tui/src/gatewayClient.ts@@ -114,11 +114,17 @@ const redactUrl = (raw: string): string => {export interface LocalGatewayGrant { url: string; protocols: string[]; profile_id: string; instance_id: string }-const bootstrapLocalGateway = async (start: boolean): Promise<LocalGatewayGrant> => {+// 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).+export const OWNER_RECOVERY_LIMIT = 3+export const OWNER_RECOVERY_WINDOW_MS = 60_000++const bootstrapLocalGateway = async (start: boolean, recover = false): Promise<LocalGatewayGrant> => {const root = process.env.HERMES_PYTHON_SRC_ROOT ?? resolve(import.meta.dirname, '../../')const { stdout } = await promisify(execFile)(resolvePython(),- [resolve(root, 'ui-tui/scripts/gateway_bootstrap.py'), ...(start ? ['--start'] : [])],+ [resolve(root, 'ui-tui/scripts/gateway_bootstrap.py'), ...(start ? ['--start'] : recover ? ['--recover'] : [])],{ cwd: root, env: { ...process.env, PYTHONPATH: root }, timeout: 40_000, maxBuffer: 1024 * 1024 })return JSON.parse(stdout) as LocalGatewayGrant@@ -168,11 +174,14 @@ export class GatewayClient extends EventEmitter {private bootstrapError: Error | null = nullprivate localStarted = falseprivate localGeneration = 0+ private recoveryAttempts: number[] = []isCanonical = falseprivate creationContract?: CreationContractprivate describeFlight?: Promise<void>- constructor(private bootstrap: (start: boolean) => Promise<LocalGatewayGrant> = bootstrapLocalGateway) {+ constructor(+ private bootstrap: (start: boolean, recover?: boolean) => Promise<LocalGatewayGrant> = bootstrapLocalGateway+ ) {super()// useInput / createGatewayEventHandler can legitimately attach many// listeners. Default 10-cap triggers spurious warnings.@@ -484,9 +493,10 @@ export class GatewayClient extends EventEmitter {private startLocalGateway() {const generation = ++this.localGenerationconst start = !this.localStarted+ const recover = !start && this.claimOwnerRecovery()this.localStarted = truethis.bootstrapError = null- this.bootstrapFlight = this.bootstrap(start).then(grant => {+ this.bootstrapFlight = this.bootstrap(start, recover).then(grant => {if (this.disposed || generation !== this.localGeneration) { return }this.attachUrl = grant.urlthis.isCanonical = true@@ -503,6 +513,19 @@ export class GatewayClient extends EventEmitter {})}+ /** One slot of the sliding owner re-ensure budget, so a crash-looping owner is not respawned forever. */+ private claimOwnerRecovery(now = Date.now()) {+ this.recoveryAttempts = this.recoveryAttempts.filter(at => now - at < OWNER_RECOVERY_WINDOW_MS)++ if (this.recoveryAttempts.length >= OWNER_RECOVERY_LIMIT) {+ return false+ }++ this.recoveryAttempts.push(now)++ return true+ }+private startAttachedGateway(attachUrl: string, protocols?: string[]) {const safeAttachUrl = redactUrl(attachUrl)this.startReadyTimer('websocket', safeAttachUrl)