The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
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.pyindex ddcb6eacbf4..a87b3b72838 100644--- a/hermes_cli/gateway_agent.py+++ b/hermes_cli/gateway_agent.py@@ -19,7 +19,7 @@ import uuidfrom contextlib import suppressfrom 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_beforelogger = 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.pyindex 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``: nodeadline; 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 += 1rid = 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 abovedef private_control_query(home: Path, request: bytes, timeout: float = 5) -> bytes:diff --git a/hermes_cli/gateway_queue.py b/hermes_cli/gateway_queue.pyindex 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, GatewayRPCErrorsubmission = uuid.uuid4().hexfor attempt in (1, 2):try:diff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.pyindex b26800530e3..a474a8d9f98 100644--- a/tests/hermes_cli/test_gateway_agent.py+++ b/tests/hermes_cli/test_gateway_agent.py@@ -8,7 +8,7 @@ import pytestfrom hermes_cli.gateway_agent import GatewayAgentfrom hermes_cli.gateway_client import GatewayClientError, GatewayRPCError-from hermes_cli.gateway_connection import DISCONNECTED, GatewayConnection+from hermes_cli.gateway_connection import DISCONNECTED, NOT_SENT, GatewayConnectionSID = "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 commitsthe 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.pyindex 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 jsonfrom contextlib import asynccontextmanagerimport pytest+from websockets.protocol import Statefrom hermes_cli import gateway_clientfrom 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 = eventsself.inbox = asyncio.Queue()diff --git a/tests/hermes_cli/test_gateway_client_recovery_backlog.py b/tests/hermes_cli/test_gateway_client_recovery_backlog.pyindex 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 jsonfrom unittest.mock import AsyncMockimport pytest+from websockets.protocol import Statedef 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 = burstself.frames = asyncio.Queue()@@ -77,6 +80,8 @@ async def test_resume_answer_behind_a_burst_stays_reachable(monkeypatch, consumeclass PostAckWire:+ state = State.OPEN # GatewayClient.rpc reads the socket state before it sends+def __init__(self):self.frames = asyncio.Queue()self.submit_id = Nonediff --git a/tests/hermes_cli/test_gateway_client_rpc.py b/tests/hermes_cli/test_gateway_client_rpc.pyindex 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 jsonimport pytest+from websockets.exceptions import ConnectionClosedError+from websockets.protocol import State+from hermes_cli.gateway_client import NOT_SENT, GatewayClient, GatewayClientError, GatewayRPCErrorclass _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 = replyself.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.asyncioasync 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 writtensent.append(raw)+ raise ConnectionClosedError(None, None)async def __anext__(self):raise StopAsyncIteration # the socket closed: iteration endsasync 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 closeassert 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.pyindex 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 typesfrom contextlib import asynccontextmanagerimport pytest+from websockets.protocol import Statefrom hermes_cli.cli_chat_error_copy import chat_error_responsefrom 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.pyindex 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 asyncioimport jsonimport pytest+from websockets.protocol import Statefrom hermes_cli import kanban_worker_clientfrom hermes_cli.gateway_client import GatewayClient@@ -19,6 +20,8 @@ from hermes_cli.gateway_client import GatewayClientclass _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(), []