Skip to content

The agent that grows with you

fix: end the classic CLI REPL as soon as the gateway connection dies

Tekniumb813916161ed
diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.py
index 40ff8086e9c..016aaf8844a 100644
--- a/hermes_cli/gateway_chat_view.py
+++ b/hermes_cli/gateway_chat_view.py
@@ -37,6 +37,9 @@ class GatewayChatView:
self.completions = {}
self.changed = asyncio.Event()
self.failure = None
+ # Set once with ``failure``: the interactive composer races its line read against it so a
+ # dead owner ends the REPL immediately instead of on the next keypress.
+ self.failed = asyncio.Event()
from hermes_cli.gateway_mutations import PreparedMutations
self.mutations = PreparedMutations()
@@ -67,8 +70,7 @@ class GatewayChatView:
while True:
event = await self.client.events.get()
if isinstance(event, Exception):
- self.failure = event
- self.changed.set()
+ self._fail(event)
return
params = event.get("params", {})
if params.get("session_id") != self.session_id:
@@ -76,8 +78,7 @@ class GatewayChatView:
kind, payload = params.get("type"), params.get("payload", {})
self.generation = params.get("execution_generation", self.generation)
if kind == "session.replay_gap":
- self.failure = GatewayClientError("session_replay_gap")
- self.changed.set()
+ self._fail(GatewayClientError("session_replay_gap"))
return
admission = params.get("admission_id") or payload.get("admission_id")
if self.finite and kind in _BLOCKING_CONTROL_EVENTS:
@@ -98,6 +99,28 @@ class GatewayChatView:
self._dispatch_event(kind, admission, payload)
self.changed.set()
+ def _fail(self, error):
+ self.failure = error
+ self.failed.set()
+ self.changed.set()
+
+ async def _read_line(self, prompt, symbol):
+ """The next composer line, or ``""`` once the event stream failed first (``self.failure``
+ is then set). The pending read is cancelled (prompt_toolkit restores the terminal) so the
+ caller reports the unknown outcome without waiting for a keypress."""
+ reader = asyncio.ensure_future(prompt.prompt_async(symbol))
+ failed = asyncio.ensure_future(self.failed.wait())
+ try:
+ await asyncio.wait({reader, failed}, return_when=asyncio.FIRST_COMPLETED)
+ finally:
+ failed.cancel()
+ if reader.done():
+ return reader.result()
+ reader.cancel()
+ with suppress(asyncio.CancelledError):
+ await reader
+ return ""
+
def _dispatch_event(self, kind, admission, payload):
handler = {
"message.delta": self._delta, "message.complete": self._complete,
@@ -358,7 +381,8 @@ class GatewayChatView:
with patch_stdout():
while not self.failure:
try:
- text = (await prompt.prompt_async(prompt_symbol)).strip()
+ # Empty when the stream failed first: the loop guard then raises it.
+ text = (await self._read_line(prompt, prompt_symbol)).strip()
if not text:
continue
if text.startswith("/"):
diff --git a/tests/hermes_cli/test_gateway_disconnect_outcome.py b/tests/hermes_cli/test_gateway_disconnect_outcome.py
index 4cefc9729d9..1f756950bb0 100644
--- a/tests/hermes_cli/test_gateway_disconnect_outcome.py
+++ b/tests/hermes_cli/test_gateway_disconnect_outcome.py
@@ -1,5 +1,8 @@
"""Expected keepalive close preserves an honest unknown outcome and no task traceback."""
+import argparse
import asyncio
+from contextlib import nullcontext
+import json
import pytest
from websockets.exceptions import ConnectionClosedError
@@ -23,3 +26,46 @@ async def test_keepalive_close_releases_waiters_without_unhandled_reader_excepti
with pytest.raises(GatewayClientError, match='outcome is unknown'):
await pending
assert 'do not resend' in str(await client.events.get())
+
+
+async def test_idle_composer_exits_with_unknown_outcome_when_owner_dies_without_keypress(monkeypatch):
+ """The owner dying while the REPL waits for input must end the viewer at once with the
+ unknown-outcome hint; the pending line read is cancelled rather than awaited forever."""
+ from websockets.asyncio.server import serve
+
+ from hermes_cli import gateway_chat
+
+ snapshot = {"stored_session_id": "stored", "execution_generation": 1, "pending": []}
+ attached = asyncio.Event()
+ reads = []
+
+ async def peer(ws):
+ async for raw in ws:
+ request = json.loads(raw)
+ result = snapshot if request["method"] == "session.resume" else {}
+ await ws.send(json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": result}))
+
+ class IdleInput:
+ def __init__(self, **_kwargs):
+ pass
+
+ async def prompt_async(self, _prompt):
+ attached.set()
+ try:
+ await asyncio.Future() # nobody ever presses a key
+ except asyncio.CancelledError:
+ reads.append("cancelled")
+ raise
+
+ monkeypatch.setattr("prompt_toolkit.PromptSession", IdleInput)
+ monkeypatch.setattr("prompt_toolkit.patch_stdout.patch_stdout", nullcontext)
+ async with serve(peer, "127.0.0.1", 0) as server:
+ port = server.sockets[0].getsockname()[1]
+ monkeypatch.setenv("HERMES_TUI_GATEWAY_URL", f"ws://127.0.0.1:{port}")
+ viewer = asyncio.create_task(gateway_chat.run_gateway_chat(argparse.Namespace(resume="stored")))
+ await asyncio.wait_for(attached.wait(), 5)
+ server.close(close_connections=True)
+ with pytest.raises(GatewayClientError, match="outcome is unknown"):
+ await asyncio.wait_for(viewer, 3)
+ assert reads == ["cancelled"]