Skip to content

The agent that grows with you

fix(dashboard): drop a 1:1 PTY's channel marker even when disconnect cancels the handler

Teknium4a47992695f9
diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.py
index 5bd7a18ec0f..35874ec5c79 100644
--- a/hermes_cli/web_routers/chat_ws.py
+++ b/hermes_cli/web_routers/chat_ws.py
@@ -626,13 +626,18 @@ async def pty_ws(ws: WebSocket) -> None:
_discard_active_session_file(ws.app, channel, active_session_file)
await _pty_fail(ws, exc)
return
- await _legacy_pump(ws, bridge)
- # The 1:1 PTY died with this socket; nothing survives to keep the
- # breadcrumb, so drop the marker instead of leaking the entry (#63553).
- # A preexisting marker belongs to a live keep-alive PTY on this channel
- # — only the marker this handler allocated is ours to drop.
- if not marker_preexisting:
- _discard_active_session_file(ws.app, channel, active_session_file)
+ try:
+ await _legacy_pump(ws, bridge)
+ finally:
+ # The 1:1 PTY died with this socket; nothing survives to keep the
+ # breadcrumb, so drop the marker instead of leaking the entry (#63553).
+ # A preexisting marker belongs to a live keep-alive PTY on this channel
+ # — only the marker this handler allocated is ours to drop. In a
+ # ``finally``: the server may cancel the handler while the pump is still
+ # awaiting the blocking ``bridge.close`` after the disconnect, and that
+ # cancellation must not skip the cleanup.
+ if not marker_preexisting:
+ _discard_active_session_file(ws.app, channel, active_session_file)
return
# Keep-alive path: the PTY outlives this socket; reattach by token.
diff --git a/tests/hermes_cli/test_pty_keepalive_ws.py b/tests/hermes_cli/test_pty_keepalive_ws.py
index cd4d6fa2454..15cbc8be7b5 100644
--- a/tests/hermes_cli/test_pty_keepalive_ws.py
+++ b/tests/hermes_cli/test_pty_keepalive_ws.py
@@ -225,6 +225,29 @@ async def test_legacy_channel_connect_pops_marker_on_disconnect(pty_keepalive_ha
assert "LEGACY63553" not in markers
+async def test_legacy_marker_pops_even_when_disconnect_cancels_a_slow_close(
+ pty_keepalive_harness, monkeypatch
+):
+ """A disconnect may cancel the handler while the pump still awaits the blocking
+ ``bridge.close`` (a loaded host makes the thread hop slow); that cancellation must not
+ skip the marker cleanup, or every such reconnect leaks one entry (#63553)."""
+ import time
+
+ from starlette.testclient import TestClient
+
+ monkeypatch.setattr(FakeBridge, "close", lambda self: time.sleep(0.5))
+ markers = _pty_marker_dict()
+ markers.clear()
+ with TestClient(web_server.app).websocket_connect("/api/pty?channel=SLOWCLOSE") as ws:
+ ws.send_bytes(b"hi")
+ assert "SLOWCLOSE" in markers
+ deadline = time.monotonic() + 5.0
+ while "SLOWCLOSE" in markers and time.monotonic() < deadline:
+ time.sleep(0.01)
+ assert "SLOWCLOSE" not in markers
+
+
@pytest.mark.asyncio
async def test_fresh_start_pops_stale_marker_and_reregisters_child_path(
pty_keepalive_harness, tmp_path, monkeypatch