The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): release the PTY a rotated attach token strands
Konstantin Khlopkov226e557d2870
diff --git a/hermes_cli/pty_session.py b/hermes_cli/pty_session.pyindex a34f8da4cf9..94ed69bd68b 100644--- a/hermes_cli/pty_session.py+++ b/hermes_cli/pty_session.py@@ -42,6 +42,16 @@ async def _close_ws(ws, code: int) -> None:pass+def _resume_target(key: str) -> str:+ """The resume target a keep-alive key was registered under.++ Registry keys read ``token\\0profile\\0resume``; a key without a resume+ target — a chat that was never resumed from — yields ``""``.+ """+ parts = key.split("\0")+ return parts[2] if len(parts) >= 3 else ""++class PtySession:def __init__(self, key: str, bridge, *, buffer_cap: int, read_timeout: float) -> None:self.key = key@@ -133,6 +143,19 @@ class PtySession:self.attached = Falseself.last_detached_at = time.monotonic()+ def runs_pid(self, pid: Optional[int]) -> bool:+ """Whether this PTY's child is the process named by ``pid``.++ A bridge that cannot report one (already reaped, or a stub) is simply+ not a match.+ """+ if pid is None:+ return False+ try:+ return int(self.bridge.pid) == pid+ except (AttributeError, TypeError, ValueError, OSError):+ return False+async def close(self) -> None:self.alive = Falseif self._drain_task is not None:@@ -230,6 +253,34 @@ class PtySessionRegistry:await _close_ws(session._ws, WS_CLOSE_SUPERSEDED)await session.close()+ async def close_orphaned_sessions(+ self, resume: Optional[str], *, keep_key: str, holder_pid: Optional[int] = None,+ ) -> None:+ """Close a keep-alive PTY stranded under a superseded attach token.++ Rotating the token — the dashboard's *New chat* — moves the tab to a+ fresh PTY while the previous one keeps the TUI's single-writer lease on+ its session. That terminal is out of the user's reach, so the next+ return to the same chat is refused as a session held elsewhere. A PTY+ with a live viewer is never a candidate: somebody is still using it.++ A chat that was never resumed from carries no resume target in its key,+ so ``holder_pid`` — the process holding the lease for the session being+ resumed — identifies that terminal instead.+ """+ if not resume:+ return+ async with self._attach_lock:+ doomed = [+ key for key, session in self._sessions.items()+ if key != keep_key and not session.attached+ and (_resume_target(key) == resume or session.runs_pid(holder_pid))+ ]+ for key in doomed:+ session = self._sessions.pop(key, None)+ if session is not None:+ await session.close()+def detach(self, key: str, ws) -> None:s = self._sessions.get(key)if s is not None:diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.pyindex 0192d9b9751..bfb468973fd 100644--- a/hermes_cli/web_routers/chat_ws.py+++ b/hermes_cli/web_routers/chat_ws.py@@ -16,6 +16,7 @@ from typing import Any, Dict, Optionalfrom fastapi import APIRouter, FastAPI, HTTPException, WebSocket, WebSocketDisconnectfrom agent.interrupt_scope import InterruptScope, bind_interrupt_scope+from hermes_cli.active_sessions import ActiveSessionRegistryError, active_session_registry_snapshotfrom hermes_cli.pty_session import RegistryFullfrom hermes_cli.web_deps import LateState, latefrom hermes_cli.web_routers.chat_ws_errors import chat_start_failure_message@@ -435,6 +436,25 @@ async def _pty_fail(ws: WebSocket, exc: BaseException) -> None:await ws.close(code=1011)+def _lease_holder_pid(session_id: Optional[str]) -> Optional[int]:+ """The live process holding ``session_id``'s single-writer lease, if any.++ A keep-alive PTY whose chat was never resumed from carries no resume target+ in its registry key, so the lease holder is what identifies the terminal+ that has to give the session back. A registry that cannot be read is not a+ reason to refuse the attach: the caller simply finds no holder.+ """+ if not session_id:+ return None+ try:+ for entry in active_session_registry_snapshot():+ if entry.get("session_id") == session_id and isinstance(entry.get("pid"), int):+ return entry["pid"]+ except (ActiveSessionRegistryError, OSError, ValueError):+ return None+ return None++@router.websocket("/api/pty")async def pty_ws(ws: WebSocket) -> None:from hermes_cli.web_server_chat import PTY_REGISTRY, PtyBridge, PtyUnavailableError, _PTY_BRIDGE_AVAILABLE, _RESIZE_RE@@ -536,6 +556,8 @@ async def pty_ws(ws: WebSocket) -> None:# Keep-alive path: the PTY outlives this socket; reattach by token.try:await PTY_REGISTRY.close_other_sessions(raw_attach_token, keep_key=attach_token)+ await PTY_REGISTRY.close_orphaned_sessions(+ registry_resume, keep_key=attach_token, holder_pid=_lease_holder_pid(registry_resume))session, _created = await PTY_REGISTRY.attach_or_spawn(attach_token, spawn=_spawn)except (PtyUnavailableError, FileNotFoundError, OSError, RegistryFull) as exc:await _pty_fail(ws, exc)diff --git a/tests/hermes_cli/test_pty_session.py b/tests/hermes_cli/test_pty_session.pyindex 37d2cb2438a..10bdded9db2 100644--- a/tests/hermes_cli/test_pty_session.py+++ b/tests/hermes_cli/test_pty_session.py@@ -21,8 +21,6 @@ def test_ringbuffer_drops_oldest_over_capacity():assert rb.truncated is True--class FakeBridge:"""Implements the bridge contract PtySession depends on."""@@ -315,8 +313,6 @@ async def test_same_key_reattaches_same_session():await reg.close_all()--@pytest.mark.asyncioasync def test_new_key_at_capacity_raises_when_none_reapable():reg = make_registry(max_sessions=1)@@ -370,8 +366,6 @@ async def test_concurrent_attach_on_one_token_forks_one_pty():await reg.close_all()--async def _two_idle_sessions_first_close_gated(reg):"""Two detached (idle) sessions; k0's close() parks until ``release`` is set."""from hermes_cli.pty_session import PtySession@@ -494,6 +488,115 @@ async def test_close_other_sessions_removes_old_profile_session():# The displaced viewer gets the documented supersede code rather than going silent.assert old_ws.close_code == WS_CLOSE_SUPERSEDEDawait reg.close_all()+async def test_close_orphaned_sessions_closes_pty_stranded_by_token_rotation():+ from hermes_cli.pty_session import PtySession++ reg = make_registry()+ stranded_bridge = FakeBridge([b""])+ current_bridge = FakeBridge([b""])+ stranded = PtySession("old-token\0\0session-a", stranded_bridge, buffer_cap=1024, read_timeout=0.01)+ current = PtySession("new-token\0\0session-a", current_bridge, buffer_cap=1024, read_timeout=0.01)+ await stranded.start()+ await current.start()+ stranded.detach(None) # New chat rotated the token and walked away+ reg._sessions[stranded.key] = stranded+ reg._sessions[current.key] = current++ await reg.close_orphaned_sessions("session-a", keep_key=current.key)++ assert stranded_bridge.closed+ assert stranded.key not in reg._sessions+ assert reg._sessions[current.key] is current+ await reg.close_all()+++async def test_close_orphaned_sessions_keeps_a_pty_someone_is_viewing():+ from hermes_cli.pty_session import PtySession++ reg = make_registry()+ viewed_bridge = FakeBridge([b""])+ current_bridge = FakeBridge([b""])+ viewed = PtySession("old-token\0\0session-a", viewed_bridge, buffer_cap=1024, read_timeout=0.01)+ current = PtySession("new-token\0\0session-a", current_bridge, buffer_cap=1024, read_timeout=0.01)+ await viewed.start()+ await current.start()+ assert await viewed.attach(FakeWS()) # a second tab is still watching that terminal+ reg._sessions[viewed.key] = viewed+ reg._sessions[current.key] = current++ await reg.close_orphaned_sessions("session-a", keep_key=current.key)++ assert not viewed_bridge.closed+ assert reg._sessions[viewed.key] is viewed+ assert reg._sessions[current.key] is current+ await reg.close_all()+++async def test_close_orphaned_sessions_without_resume_target_touches_nothing():+ from hermes_cli.pty_session import PtySession++ reg = make_registry()+ other_bridge = FakeBridge([b""])+ other = PtySession("old-token\0\0", other_bridge, buffer_cap=1024, read_timeout=0.01)+ await other.start()+ other.detach(None)+ reg._sessions[other.key] = other++ await reg.close_orphaned_sessions(None, keep_key="new-token\0\0")++ assert not other_bridge.closed+ assert reg._sessions[other.key] is other+ await reg.close_all()+++ "key,expected",+ [+ ("token\0profile\0session-a", "session-a"),+ ("token\0\0session-b", "session-b"),+ ("token\0profile\0", ""),+ ("token", ""),+ ],+)+def test_resume_target_reads_the_last_key_segment(key, expected):+ from hermes_cli.pty_session import _resume_target++ assert _resume_target(key) == expected+++class PidBridge(FakeBridge):+ """A bridge that reports a child pid, like a real PTY does."""++ def __init__(self, chunks, pid):+ super().__init__(chunks)+ self.pid = pid+++async def test_close_orphaned_sessions_finds_the_lease_holder_without_a_resume_key():+ """The reported repro starts a *fresh* chat, so chat A's key carries no+ resume target. Only the process holding the session lease identifies it."""+ from hermes_cli.pty_session import PtySession++ reg = make_registry()+ fresh_a = PtySession("old-token\0\0", PidBridge([b""], 4242), buffer_cap=1024, read_timeout=0.01)+ unrelated = PtySession("other-token\0\0", PidBridge([b""], 5151), buffer_cap=1024, read_timeout=0.01)+ current = PtySession("new-token\0\0session-a", FakeBridge([b""]), buffer_cap=1024, read_timeout=0.01)+ for session in (fresh_a, unrelated, current):+ await session.start()+ session.detach(None)+ reg._sessions[session.key] = session++ await reg.close_orphaned_sessions("session-a", keep_key=current.key, holder_pid=4242)++ assert fresh_a.bridge.closed and fresh_a.key not in reg._sessions+ # A detached terminal for a different session is somebody's reconnect+ # window, not this resume's business.+ assert not unrelated.bridge.closed and reg._sessions[unrelated.key] is unrelated+ assert reg._sessions[current.key] is current@pytest.mark.asyncio@@ -509,9 +612,39 @@ async def test_reap_reaps_dead_process_even_when_attached():await reg.reap_idle()assert "tok" not in reg._sessionsassert b.closed is True++await reg.close_all()+async def test_close_orphaned_sessions_leaves_a_lease_holding_pty_that_is_viewed():+ from hermes_cli.pty_session import PtySession++ reg = make_registry()+ watched = PtySession("old-token\0\0", PidBridge([b""], 4242), buffer_cap=1024, read_timeout=0.01)+ current = PtySession("new-token\0\0session-a", FakeBridge([b""]), buffer_cap=1024, read_timeout=0.01)+ await watched.start()+ await current.start()+ assert await watched.attach(FakeWS())+ reg._sessions[watched.key] = watched+ reg._sessions[current.key] = current++ await reg.close_orphaned_sessions("session-a", keep_key=current.key, holder_pid=4242)++ assert not watched.bridge.closed and reg._sessions[watched.key] is watched+ await reg.close_all()+++def test_runs_pid_tolerates_a_bridge_without_one():+ from hermes_cli.pty_session import PtySession++ session = PtySession("tok", FakeBridge([b""]), buffer_cap=8, read_timeout=0.01)+ assert session.runs_pid(None) is False+ assert session.runs_pid(123) is False+ assert PidBridge([b""], 7).pid == 7++@pytest.mark.asyncioasync def test_reap_keeps_live_attached_session():# A session with a live child and an attached viewer is never reaped,@@ -524,3 +657,5 @@ async def test_reap_keeps_live_attached_session():assert "tok" in reg._sessionsassert b.closed is Falseawait reg.close_all()++