Skip to content

The agent that grows with you

fix(cli): a closing socket refuses before the send, and an unsent prompt keeps its turn

kshitijk4poord72b65595e42
diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.py
index ddcb6eacbf4..a87b3b72838 100644
--- a/hermes_cli/gateway_agent.py
+++ b/hermes_cli/gateway_agent.py
@@ -19,7 +19,7 @@ import uuid
from contextlib import suppress
from hermes_cli.gateway_client import GatewayClientError, GatewayRPCError
-from hermes_cli.gateway_connection import DISCONNECTED, CallStopped, lost_before
+from hermes_cli.gateway_connection import DISCONNECTED, NOT_SENT, CallStopped, lost_before
logger = logging.getLogger(__name__)
@@ -794,6 +794,12 @@ class GatewayAgent:
return self._failed(history, user_message, str(exc),
failure_reason="session_busy" if busy else None, retryable=busy)
except GatewayClientError as exc:
+ if str(exc) == NOT_SENT:
+ # Never reached the owner: like a notice, the CLI keeps the turn's local state (no
+ # history row, the /model --once pick and notes) so the resend is the same turn.
+ self._give_back_turn_route()
+ return {**self._failed(history, user_message, str(exc), failure_reason="gateway_connection"),
+ "messages": history, "admitted": False}
return self._failed(history, user_message, str(exc), failure_reason="gateway_connection")
if (receipt or {}).get("voice_stopped") is True:
return self._voice_stopped(history)
diff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.py
index 4e88b54993e..e7bf8eade2e 100644
--- a/hermes_cli/gateway_client.py
+++ b/hermes_cli/gateway_client.py
@@ -216,9 +216,11 @@ class GatewayClient:
"""Send one request and await its answer; ``_timeout`` (seconds, never sent on the wire)
overrides ``DEFAULT_RPC_TIMEOUT`` for a verb that legitimately takes longer (``math.inf``: no
deadline; the answer, a hang-up or the caller's cancel ends the wait)."""
- if self.reader is not None and self.reader.done():
- # The reader ended (the socket closed, e.g. a keepalive timeout, or it gave up): no answer
- # could arrive, so nothing is sent and the caller may safely send again.
+ from websockets.protocol import State
+ if self.websocket.state is not State.OPEN or (self.reader is not None and self.reader.done()):
+ # A closing socket (a keepalive timeout fails it, then waits up to close_timeout for the
+ # peer) is never written to, and a reader that ended (closed socket, bad frame, stalled
+ # consumer) could not read the answer: refuse before writing, so the caller knows nothing left.
raise GatewayClientError(NOT_SENT)
self.sequence += 1
rid = self.sequence
@@ -236,6 +238,8 @@ class GatewayClient:
return await asyncio.wait_for(future, None if budget == float("inf") else budget)
finally:
self.pending.pop(rid, None)
+ if future.done() and not future.cancelled():
+ future.exception() # failed by the reader while the send raised: already reported above
def private_control_query(home: Path, request: bytes, timeout: float = 5) -> bytes:
diff --git a/hermes_cli/gateway_queue.py b/hermes_cli/gateway_queue.py
index c0face814ec..fbc26dffc57 100644
--- a/hermes_cli/gateway_queue.py
+++ b/hermes_cli/gateway_queue.py
@@ -43,8 +43,7 @@ def submit_queued(cli, store, text: str) -> str:
admission it already holds (``admit_session_input`` keys it by principal, session and request id),
so the prompt is queued exactly once. Still no answer: :class:`QueueOutcomeUnknown`.
"""
- from hermes_cli.gateway_client import GatewayRPCError
- from hermes_cli.gateway_connection import NOT_SENT
+ from hermes_cli.gateway_client import NOT_SENT, GatewayRPCError
submission = uuid.uuid4().hex
for attempt in (1, 2):
try:
diff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.py
index b26800530e3..a474a8d9f98 100644
--- a/tests/hermes_cli/test_gateway_agent.py
+++ b/tests/hermes_cli/test_gateway_agent.py
@@ -8,7 +8,7 @@ import pytest
from hermes_cli.gateway_agent import GatewayAgent
from hermes_cli.gateway_client import GatewayClientError, GatewayRPCError
-from hermes_cli.gateway_connection import DISCONNECTED, GatewayConnection
+from hermes_cli.gateway_connection import DISCONNECTED, NOT_SENT, GatewayConnection
SID = "local-abc"
@@ -763,6 +763,23 @@ def test_a_transport_loss_at_submit_is_still_gateway_connection():
assert result["failure_reason"] == "gateway_connection" and result["failure_retryable"] is False
+def test_a_submit_that_never_left_keeps_the_turn_for_the_resend():
+ """NOT_SENT: the owner never saw the prompt. The CLI keeps the turn's local state (no history row,
+ the ``/model --once`` pick) so the resend is the same turn, as a pre-submit notice does."""
+ conn = GatewayConnection(connect=connect_with(RefusingClient(GatewayClientError(NOT_SENT))))
+ conn.start(5)
+ try:
+ agent = GatewayAgent(connection=conn, session_id=SID)
+ pick = {"model": "picked-model", "provider": "openrouter"}
+ agent._turn_route, agent._turn_reasoning = dict(pick), None
+ result = agent.run_conversation("q", conversation_history=[])
+ assert result["failed"] is True and result["error"] == NOT_SENT
+ assert result["admitted"] is False and result["messages"] == []
+ assert agent._turn_route == pick # the pick is still owed
+ finally:
+ conn.close()
+
+
def test_model_switch_is_the_session_model_mutation_and_a_rebuilt_agent_shows_it(make_agent):
"""A session-scoped ``/model`` calls ``agent.switch_model`` (#134889 M1). The gateway commits
the target as a generation-fenced ``session.mutate model`` (no key or endpoint leaves the CLI),
diff --git a/tests/hermes_cli/test_gateway_client_backlog.py b/tests/hermes_cli/test_gateway_client_backlog.py
index 845b2ed4246..993f0080184 100644
--- a/tests/hermes_cli/test_gateway_client_backlog.py
+++ b/tests/hermes_cli/test_gateway_client_backlog.py
@@ -10,6 +10,7 @@ import json
from contextlib import asynccontextmanager
import pytest
+from websockets.protocol import State
from hermes_cli import gateway_client
from hermes_cli.gateway_client import GatewayClient, GatewayClientError
@@ -77,6 +78,8 @@ class CardOwner:
"""A Kanban card's owner as the worker's socket sees it: ``kanban.run`` subscribes the socket,
the card's turn streams ``events`` frames, and the next receipt poll finds it terminal."""
+ state = State.OPEN # GatewayClient.rpc reads the socket state before it sends
+
def __init__(self, events):
self.events = events
self.inbox = asyncio.Queue()
diff --git a/tests/hermes_cli/test_gateway_client_recovery_backlog.py b/tests/hermes_cli/test_gateway_client_recovery_backlog.py
index feadcc01bab..0171abf1987 100644
--- a/tests/hermes_cli/test_gateway_client_recovery_backlog.py
+++ b/tests/hermes_cli/test_gateway_client_recovery_backlog.py
@@ -11,6 +11,7 @@ import json
from unittest.mock import AsyncMock
import pytest
+from websockets.protocol import State
def event(kind, seq=1, sid='s', admission=None):
@@ -20,6 +21,8 @@ def event(kind, seq=1, sid='s', admission=None):
class ResumeWire:
+ state = State.OPEN # GatewayClient.rpc reads the socket state before it sends
+
def __init__(self, burst):
self.burst = burst
self.frames = asyncio.Queue()
@@ -77,6 +80,8 @@ async def test_resume_answer_behind_a_burst_stays_reachable(monkeypatch, consume
class PostAckWire:
+ state = State.OPEN # GatewayClient.rpc reads the socket state before it sends
+
def __init__(self):
self.frames = asyncio.Queue()
self.submit_id = None
diff --git a/tests/hermes_cli/test_gateway_client_rpc.py b/tests/hermes_cli/test_gateway_client_rpc.py
index 3ebdb7f19f1..cd9b0598480 100644
--- a/tests/hermes_cli/test_gateway_client_rpc.py
+++ b/tests/hermes_cli/test_gateway_client_rpc.py
@@ -4,12 +4,17 @@ import json
import pytest
+from websockets.exceptions import ConnectionClosedError
+from websockets.protocol import State
+
from hermes_cli.gateway_client import NOT_SENT, GatewayClient, GatewayClientError, GatewayRPCError
class _Socket:
"""One scripted owner: answers each request with the frame ``reply(request)`` builds."""
+ state = State.OPEN # GatewayClient.rpc reads the socket state before it sends
+
def __init__(self, reply):
self.reply = reply
self.inbox = asyncio.Queue()
@@ -91,6 +96,27 @@ async def test_send_on_a_dead_socket_is_a_client_error_not_a_raw_websockets_one(
assert client.pending == {}
+async def test_a_request_on_a_closing_socket_is_not_sent():
+ """A keepalive timeout fails the socket (CLOSING) and websockets waits up to ``close_timeout`` for
+ the peer before the reader ends. A send in that window is never written either."""
+ sent = []
+
+ class _Closing(_Socket):
+ state = State.CLOSING
+
+ async def send(self, raw):
+ sent.append(raw)
+ raise ConnectionClosedError(None, None)
+
+ async with GatewayClient(_Closing(lambda req: None)) as client:
+ assert not client.reader.done()
+ with pytest.raises(GatewayClientError) as refused:
+ await client.rpc('prompt.submit', session_id='s')
+ assert str(refused.value) == NOT_SENT
+ assert sent == [] and client.pending == {}
+
+
@pytest.mark.asyncio
async def test_a_request_after_the_reader_ended_is_not_sent():
"""The keepalive timeout closes the socket and ends the reader before the dock's next poll: that
@@ -99,14 +125,15 @@ async def test_a_request_after_the_reader_ended_is_not_sent():
sent = []
class _Closed(_Socket):
- async def send(self, raw):
+ async def send(self, raw): # websockets: a send on a closed socket raises, nothing written
sent.append(raw)
+ raise ConnectionClosedError(None, None)
async def __anext__(self):
raise StopAsyncIteration # the socket closed: iteration ends
async with GatewayClient(_Closed(lambda req: None)) as client:
- await asyncio.sleep(0) # let the reader see the close
+ await asyncio.wait({client.reader}, timeout=1) # the reader sees the close
assert client.reader.done()
with pytest.raises(GatewayClientError) as refused:
await client.rpc('prompt.submit', session_id='s')
diff --git a/tests/hermes_cli/test_gateway_connection_reconnect.py b/tests/hermes_cli/test_gateway_connection_reconnect.py
index 15e4ea00ff6..efa23a693f5 100644
--- a/tests/hermes_cli/test_gateway_connection_reconnect.py
+++ b/tests/hermes_cli/test_gateway_connection_reconnect.py
@@ -10,6 +10,7 @@ import types
from contextlib import asynccontextmanager
import pytest
+from websockets.protocol import State
from hermes_cli.cli_chat_error_copy import chat_error_response
from hermes_cli.gateway_agent import GatewayAgent
@@ -267,6 +268,8 @@ def test_close_after_a_failed_resume_is_still_final(gateway, conn):
class _Unanswered:
"""A socket that takes every request and never answers one (a gateway stalled mid-reconnect)."""
+ state = State.OPEN # GatewayClient.rpc reads the socket state before it sends
+
def __init__(self):
self.sent = asyncio.Event()
diff --git a/tests/hermes_cli/test_kanban_worker_admission_wait.py b/tests/hermes_cli/test_kanban_worker_admission_wait.py
index 70bd4de9615..ea7208271ef 100644
--- a/tests/hermes_cli/test_kanban_worker_admission_wait.py
+++ b/tests/hermes_cli/test_kanban_worker_admission_wait.py
@@ -11,6 +11,7 @@ import asyncio
import json
import pytest
+from websockets.protocol import State
from hermes_cli import kanban_worker_client
from hermes_cli.gateway_client import GatewayClient
@@ -19,6 +20,8 @@ from hermes_cli.gateway_client import GatewayClient
class _Owner:
"""Answers ``kanban.run`` after a 120 s (scaled) board wait, then a terminal receipt."""
+ state = State.OPEN # GatewayClient.rpc reads the socket state before it sends
+
def __init__(self):
self.inbox, self.sent = asyncio.Queue(), []