Skip to content

The agent that grows with you

fix(pty): recover sessions after socket send failures

MKanso6d622d8eba5d
diff --git a/hermes_cli/pty_session.py b/hermes_cli/pty_session.py
index 378be522fc1..7a35bd1aec4 100644
--- a/hermes_cli/pty_session.py
+++ b/hermes_cli/pty_session.py
@@ -71,11 +71,12 @@ class PtySession:
await asyncio.sleep(0)
continue
self.buffer.append(chunk)
+ ws = self._ws
try:
- if self._ws is not None:
- await self._ws.send_bytes(chunk)
+ if ws is not None:
+ await ws.send_bytes(chunk)
except Exception:
- pass # detached mid-send; keep buffering
+ self.detach(ws)
async def write(self, ws, data: bytes) -> bool:
"""Serialize input and discard bytes from a superseded socket."""
@@ -108,7 +109,11 @@ class PtySession:
self.attached = True
self.last_detached_at = None
if snap := self.buffer.snapshot():
- await ws.send_bytes(snap)
+ try:
+ await ws.send_bytes(snap)
+ except Exception:
+ self.detach(ws)
+ raise
if force_redraw:
return await self.write(ws, TUI_FORCE_REDRAW)
return True
diff --git a/tests/hermes_cli/test_pty_session.py b/tests/hermes_cli/test_pty_session.py
index 19e42fc7f26..ee69295db0d 100644
--- a/tests/hermes_cli/test_pty_session.py
+++ b/tests/hermes_cli/test_pty_session.py
@@ -65,6 +65,16 @@ class FakeWS:
self.close_code = code
+class FailingWS(FakeWS):
+ def __init__(self):
+ super().__init__()
+ self.send_started = asyncio.Event()
+
+ async def send_bytes(self, data):
+ self.send_started.set()
+ raise RuntimeError("socket closed")
+
+
@pytest.mark.asyncio
async def test_attach_replays_buffer_then_streams_live():
from hermes_cli.pty_session import PtySession
@@ -79,6 +89,38 @@ async def test_attach_replays_buffer_then_streams_live():
await s.close()
+async def test_failed_replay_detaches_session():
+ from hermes_cli.pty_session import PtySession
+
+ s = PtySession("k", FakeBridge([b""]), buffer_cap=1024, read_timeout=0.01)
+ s.buffer.append(b"replay")
+
+ with pytest.raises(RuntimeError, match="socket closed"):
+ await s.attach(FailingWS())
+
+ assert s.attached is False
+ assert s.last_detached_at is not None
+ assert s._ws is None
+ await s.close()
+
+
+async def test_failed_live_send_detaches_session():
+ from hermes_cli.pty_session import PtySession
+
+ s = PtySession("k", FakeBridge([b"live"]), buffer_cap=1024, read_timeout=0.01)
+ await s.start()
+ ws = FailingWS()
+ await s.attach(ws)
+ await asyncio.wait_for(ws.send_started.wait(), timeout=1)
+
+ assert s.attached is False
+ assert s.last_detached_at is not None
+ assert s._ws is None
+ await s.close()
+
+
@pytest.mark.asyncio
async def test_reattach_can_force_complete_tui_redraw_after_replay():
"""A fresh terminal cannot reconstruct a differential ANSI tail alone."""