The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): find the stranded PTY by lease ancestry, in the chat's own home
Austin Pickettf139d661c7ca
diff --git a/hermes_cli/pty_session.py b/hermes_cli/pty_session.pyindex 94ed69bd68b..785c8a52239 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 _process_ancestors(pid: int) -> set[int]:+ """Pids of ``pid``'s live ancestors; empty when the process is gone or unreadable."""+ import psutil # type: ignore++ try:+ return {parent.pid for parent in psutil.Process(pid).parents()}+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess, ValueError):+ return set()++def _resume_target(key: str) -> str:"""The resume target a keep-alive key was registered under.@@ -143,18 +153,21 @@ 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``.+ def hosts_pid(self, pid: Optional[int]) -> bool:+ """Whether ``pid`` runs inside this PTY: the leader itself or one of its descendants.- A bridge that cannot report one (already reaped, or a stub) is simply- not a match.+ The dashboard's PTY leader is ``node entry.js``; the process that takes the+ session lease is its ``tui_gateway`` child, so the lease pid is never the+ bridge's own pid and only ancestry identifies the terminal. A bridge that+ cannot report a pid (already reaped, or a stub) is simply not a match."""if pid is None:return Falsetry:- return int(self.bridge.pid) == pid+ leader = int(self.bridge.pid)except (AttributeError, TypeError, ValueError, OSError):return False+ return leader == pid or leader in _process_ancestors(pid)async def close(self) -> None:self.alive = False@@ -274,12 +287,14 @@ class PtySessionRegistry: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))+ and (_resume_target(key) == resume or session.hosts_pid(holder_pid))]- for key in doomed:- session = self._sessions.pop(key, None)- if session is not None:- await session.close()+ sessions = [self._sessions.pop(key) for key in doomed]+ # Close outside the registry lock — a close can wait out its helpers' SIGHUP grace and+ # this lock serializes every new chat — but still before the caller spawns: the child's+ # session lease is only released once its close finishes.+ for session in sessions:+ await session.close()def detach(self, key: str, ws) -> None:s = self._sessions.get(key)diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.pyindex bfb468973fd..964b0657588 100644--- a/hermes_cli/web_routers/chat_ws.py+++ b/hermes_cli/web_routers/chat_ws.py@@ -436,18 +436,21 @@ async def _pty_fail(ws: WebSocket, exc: BaseException) -> None:await ws.close(code=1011)-def _lease_holder_pid(session_id: Optional[str]) -> Optional[int]:+def _lease_holder_pid(session_id: Optional[str], *, registry_home: Optional[str] = None) -> 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 targetin 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.+ that has to give the session back. Leases live under the HOME the chat runs+ in — a profile-scoped chat's child claims its lease in the profile's home,+ not the dashboard's launch home — so ``registry_home`` is the child's. 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 Nonetry:- for entry in active_session_registry_snapshot():+ for entry in active_session_registry_snapshot(registry_home=registry_home):if entry.get("session_id") == session_id and isinstance(entry.get("pid"), int):return entry["pid"]except (ActiveSessionRegistryError, OSError, ValueError):@@ -556,8 +559,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))+ holder_pid = _lease_holder_pid(registry_resume, registry_home=(env or {}).get("HERMES_HOME"))+ await PTY_REGISTRY.close_orphaned_sessions(registry_resume, keep_key=attach_token, holder_pid=holder_pid)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 10bdded9db2..72440bba5dd 100644--- a/tests/hermes_cli/test_pty_session.py+++ b/tests/hermes_cli/test_pty_session.py@@ -1,4 +1,5 @@import asyncio+import osimport timeimport pytest@@ -568,29 +569,41 @@ def test_resume_target_reads_the_last_key_segment(key, expected):class PidBridge(FakeBridge):- """A bridge that reports a child pid, like a real PTY does."""+ """A bridge that reports its leader pid, like a real PTY does."""def __init__(self, chunks, pid):super().__init__(chunks)self.pid = pid+def process_tree(monkeypatch):+ """Fake ancestry: ``{pid: {ancestor pids}}``. The dashboard PTY leader (node) is pid 4242;+ the tui_gateway child that actually holds the session lease is 4243 underneath it."""+ import hermes_cli.pty_session as mod++ tree = {4243: {4242, 1}, 5152: {5151, 1}}+ monkeypatch.setattr(mod, "_process_ancestors", lambda pid: tree.get(pid, set()))+ return tree++@pytest.mark.asyncio-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."""+async def test_close_orphaned_sessions_finds_the_lease_holder_without_a_resume_key(process_tree):+ """The reported repro starts a *fresh* chat in the default profile, so chat A's key is+ the bare token — no profile, no resume segment. Only the process holding the session+ lease identifies it, and that process is the PTY leader's CHILD, not the leader."""from hermes_cli.pty_session import PtySessionreg = 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)+ fresh_a = PtySession("old-token", PidBridge([b""], 4242), buffer_cap=1024, read_timeout=0.01)+ unrelated = PtySession("other-token", 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)+ await reg.close_orphaned_sessions("session-a", keep_key=current.key, holder_pid=4243)assert fresh_a.bridge.closed and fresh_a.key not in reg._sessions# A detached terminal for a different session is somebody's reconnect@@ -599,6 +612,47 @@ async def test_close_orphaned_sessions_finds_the_lease_holder_without_a_resume_kassert reg._sessions[current.key] is current+async def test_close_orphaned_sessions_leaves_a_holder_outside_every_pty(process_tree):+ """A lease held by a plain terminal (`hermes` in a shell, pid 9000, no PTY ancestor) is a+ real other window: nothing is closed and the single-writer refusal stands."""+ from hermes_cli.pty_session import PtySession++ reg = make_registry()+ detached = PtySession("old-token", PidBridge([b""], 4242), buffer_cap=1024, read_timeout=0.01)+ await detached.start()+ detached.detach(None)+ reg._sessions[detached.key] = detached++ await reg.close_orphaned_sessions("session-a", keep_key="new-token\0\0session-a", holder_pid=9000)++ assert not detached.bridge.closed and reg._sessions[detached.key] is detached+ await reg.close_all()++[email protected]("posix")+def test_hosts_pid_sees_the_lease_holding_grandchild_of_a_real_pty():+ """Live topology: ptyprocess forks the leader; the leader's child is what claims the lease."""+ from hermes_cli.pty_bridge import PtyBridge+ from hermes_cli.pty_session import PtySession++ bridge = PtyBridge.spawn(+ ["sh", "-c", "python3 -c 'import os,time;print(\"CHILD\",os.getpid(),flush=True);time.sleep(20)'; true"]+ )+ try:+ out, deadline = b"", time.monotonic() + 10+ while b"CHILD" not in out and time.monotonic() < deadline:+ out += bridge.read(timeout=0.2) or b""+ grandchild = int(out.split(b"CHILD", 1)[1].split()[0])+ session = PtySession("tok", bridge, buffer_cap=8, read_timeout=0.01)+ assert grandchild != bridge.pid+ assert session.hosts_pid(grandchild)+ assert session.hosts_pid(bridge.pid)+ assert not session.hosts_pid(os.getpid())+ finally:+ bridge.close()++@pytest.mark.asyncioasync def test_reap_reaps_dead_process_even_when_attached():# Child killed externally (OOM killer / cgroup SIGKILL) while a grandchild@@ -618,11 +672,11 @@ async def test_reap_reaps_dead_process_even_when_attached():@pytest.mark.asyncio-async def test_close_orphaned_sessions_leaves_a_lease_holding_pty_that_is_viewed():+async def test_close_orphaned_sessions_leaves_a_lease_holding_pty_that_is_viewed(process_tree):from hermes_cli.pty_session import PtySessionreg = make_registry()- watched = PtySession("old-token\0\0", PidBridge([b""], 4242), buffer_cap=1024, read_timeout=0.01)+ watched = PtySession("old-token", 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()@@ -630,18 +684,18 @@ async def test_close_orphaned_sessions_leaves_a_lease_holding_pty_that_is_viewedreg._sessions[watched.key] = watchedreg._sessions[current.key] = current- await reg.close_orphaned_sessions("session-a", keep_key=current.key, holder_pid=4242)+ await reg.close_orphaned_sessions("session-a", keep_key=current.key, holder_pid=4243)assert not watched.bridge.closed and reg._sessions[watched.key] is watchedawait reg.close_all()-def test_runs_pid_tolerates_a_bridge_without_one():+def test_hosts_pid_tolerates_a_bridge_without_one():from hermes_cli.pty_session import PtySessionsession = 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 session.hosts_pid(None) is False+ assert session.hosts_pid(123) is Falseassert PidBridge([b""], 7).pid == 7diff --git a/tests/hermes_cli/web_routers/test_chat_ws_lease_holder.py b/tests/hermes_cli/web_routers/test_chat_ws_lease_holder.pynew file mode 100644index 00000000000..74dd50b9b6d--- /dev/null+++ b/tests/hermes_cli/web_routers/test_chat_ws_lease_holder.py@@ -0,0 +1,42 @@+"""The dashboard reads a resumed chat's lease holder from the HOME that chat runs in.++Regression for #131172: a profile-scoped chat's TUI child claims its single-writer lease+under the profile's home, so a lookup against the dashboard's launch home finds nothing and+the stranded PTY holding that lease is never released.+"""++import os++from hermes_cli.active_sessions import try_acquire_active_session+from hermes_cli.web_routers.chat_ws import _lease_holder_pid+++def _claim(home, session_id):+ lease, refusal = try_acquire_active_session(+ session_id=session_id, surface="tui", config={}, registry_home=home,+ metadata={"live_session_id": "x"},+ )+ assert lease is not None, refusal+ return lease+++def test_lease_holder_is_read_from_the_chats_profile_home(tmp_path):+ profile_home = tmp_path / "profiles" / "work"+ launch_home = tmp_path / "default"+ profile_home.mkdir(parents=True)+ launch_home.mkdir()+ lease = _claim(profile_home, "sess-a")+ try:+ assert _lease_holder_pid("sess-a", registry_home=str(profile_home)) == os.getpid()+ assert _lease_holder_pid("sess-a", registry_home=str(launch_home)) is None+ assert _lease_holder_pid("sess-b", registry_home=str(profile_home)) is None+ assert _lease_holder_pid(None, registry_home=str(profile_home)) is None+ finally:+ lease.release()+++def test_unreadable_registry_yields_no_holder(tmp_path):+ bogus = tmp_path / "runtime" / "active_sessions.json"+ bogus.parent.mkdir(parents=True)+ bogus.write_text("{not json")+ assert _lease_holder_pid("sess-a", registry_home=str(tmp_path)) is None