Skip to content

The agent that grows with you

fix(web): clean up PTY active session markers

sinh202456227dd6fd5d
diff --git a/hermes_cli/pty_session.py b/hermes_cli/pty_session.py
index 068c6f3657b..b3bd742be6e 100644
--- a/hermes_cli/pty_session.py
+++ b/hermes_cli/pty_session.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import asyncio
import time
+from pathlib import Path
from typing import Callable, Dict, Optional, Tuple
WS_CLOSE_PROCESS_EXITED = 4410
@@ -65,9 +66,11 @@ def _key_segments(key: str) -> tuple[str, str]:
class PtySession:
- def __init__(self, key: str, bridge, *, buffer_cap: int, read_timeout: float) -> None:
+ def __init__(self, key: str, bridge, *, buffer_cap: int, read_timeout: float, active_session_file: Optional[Path] = None) -> None:
self.key = key
self.bridge = bridge
+ self.active_session_file = active_session_file
+ self.active_session_cleanup: Optional[Callable[[], None]] = None
self.buffer = RingBuffer(buffer_cap)
self.alive = True
self.attached = False
@@ -185,6 +188,17 @@ class PtySession:
await asyncio.to_thread(self.bridge.close)
except Exception:
pass
+ try:
+ if self.active_session_file is not None:
+ self.active_session_file.unlink(missing_ok=True)
+ except OSError:
+ pass
+ if self.active_session_cleanup is not None:
+ try:
+ self.active_session_cleanup()
+ except Exception:
+ pass
+ self.active_session_cleanup = None
class RegistryFull(Exception):
@@ -225,7 +239,7 @@ class PtySessionRegistry:
# awaits them too, and holding the tasks keeps them from being garbage-collected.
self._background_closes: set[asyncio.Task] = set()
- async def attach_or_spawn(self, key: str, *, spawn: Callable[[], object]) -> Tuple[PtySession, bool]:
+ async def attach_or_spawn(self, key: str, *, spawn: Callable[[], object], active_session_file: Optional[Path] = None) -> Tuple[PtySession, bool]:
await self.reap_idle()
async with self._attach_lock:
existing = self._sessions.get(key)
@@ -241,7 +255,13 @@ class PtySessionRegistry:
# PTY spawn does blocking fork/exec work — keep it off the event loop.
# See #53227.
bridge = await asyncio.to_thread(spawn)
- session = PtySession(key, bridge, buffer_cap=self._buffer_cap, read_timeout=self._read_timeout)
+ session = PtySession(
+ key,
+ bridge,
+ buffer_cap=self._buffer_cap,
+ read_timeout=self._read_timeout,
+ active_session_file=active_session_file,
+ )
await session.start()
self._sessions[key] = session
return session, True
diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.py
index 964b0657588..c2b75574820 100644
--- a/hermes_cli/web_routers/chat_ws.py
+++ b/hermes_cli/web_routers/chat_ws.py
@@ -53,6 +53,27 @@ def _get_event_state(app: "FastAPI"):
_VALID_CHANNEL_RE = re.compile(r"^[A-Za-z0-9._-]{1,128}$")
+def _unlink_active_session_file(path: Optional[Path]) -> None:
+ if path is None:
+ return
+ try:
+ path.unlink(missing_ok=True)
+ except OSError:
+ pass
+
+
+def _discard_active_session_file(app: "FastAPI", channel: Optional[str], path: Optional[Path]) -> None:
+ _unlink_active_session_file(path)
+ if not channel or path is None:
+ return
+ try:
+ from hermes_cli.web_server import _get_pty_active_session_files
+ files = _get_pty_active_session_files(app)
+ if files.get(channel) == path:
+ files.pop(channel, None)
+ except Exception:
+ pass
+
def _ws_auth_mode() -> str:
"""Short label for the active WS auth mode — logged on every connection."""
@@ -487,8 +508,13 @@ async def pty_ws(ws: WebSocket) -> None:
sidecar_url = _build_sidecar_url(channel) if channel else None
force_fresh = (ws.query_params.get("fresh") or "").strip().lower() in {"1", "true", "yes", "on"}
active_session_file: Optional[Path] = None
+ marker_preexisting = False
if channel:
+ from hermes_cli.web_server import _get_pty_active_session_files
+ marker_files = _get_pty_active_session_files(ws.app)
+ marker_preexisting = channel in marker_files
+
active_session_file = _active_session_file_for_channel(ws.app, channel)
if force_fresh:
resume = None
@@ -496,6 +522,7 @@ async def pty_ws(ws: WebSocket) -> None:
active_session_file.unlink(missing_ok=True)
except OSError:
pass
+ marker_preexisting = False
elif not resume:
resume = _read_active_session_file(active_session_file)
if resume:
@@ -522,9 +549,13 @@ async def pty_ws(ws: WebSocket) -> None:
try:
argv, cwd, env = await _resolve_chat_argv_async(**resolve_kwargs)
except HTTPException as exc: # unknown/invalid profile
+ if not marker_preexisting:
+ _discard_active_session_file(ws.app, channel, active_session_file)
await _pty_fail(ws, exc)
return
except SystemExit as exc: # _make_tui_argv sys.exit(1)s when node/npm is missing
+ if not marker_preexisting:
+ _discard_active_session_file(ws.app, channel, active_session_file)
await _pty_fail(ws, exc)
return
except InstallError as exc: # PM could not provide node; its remedy names the fix
@@ -551,9 +582,17 @@ async def pty_ws(ws: WebSocket) -> None:
await _pty_fail(ws, exc)
return
except (FileNotFoundError, OSError) as exc:
+ if not marker_preexisting:
+ _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)
return
# Keep-alive path: the PTY outlives this socket; reattach by token.
@@ -561,11 +600,29 @@ async def pty_ws(ws: WebSocket) -> None:
await PTY_REGISTRY.close_other_sessions(raw_attach_token, keep_key=attach_token)
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)
+ session, _created = await PTY_REGISTRY.attach_or_spawn(
+ attach_token,
+ spawn=_spawn,
+ active_session_file=active_session_file,
+ )
except (PtyUnavailableError, FileNotFoundError, OSError, RegistryFull) as exc:
+ if not marker_preexisting:
+ _discard_active_session_file(ws.app, channel, active_session_file)
await _pty_fail(ws, exc)
return
+ if _created:
+ # This PTY now owns this marker for its entire keep-alive lifetime.
+ if channel and active_session_file is not None:
+ session.active_session_cleanup = (
+ lambda app=ws.app, ch=channel, path=active_session_file:
+ _discard_active_session_file(app, ch, path)
+ )
+ elif not marker_preexisting:
+ # A different channel attached to an already-existing PTY. The marker
+ # just allocated for this channel is not owned by that PTY.
+ _discard_active_session_file(ws.app, channel, active_session_file)
+
# A fresh xterm can't rebuild the TUI from an arbitrary tail of alternate-
# screen differential output; reused PTYs emit a full frame after replay.
if not await session.attach(ws, force_redraw=not _created):
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 3d7018b39ab..94cbc1546f9 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -319,6 +319,16 @@ async def _lifespan(app: "FastAPI"):
selftest_task.cancel()
auto_archive_task.cancel()
await PTY_REGISTRY.close_all()
+
+ # PtySession.close() removes markers owned by live registry sessions.
+ # This second pass cleans any channel markers left in app state,
+ # including stale paths from sessions reaped earlier.
+ for marker in set(_get_pty_active_session_files(app).values()):
+ try:
+ marker.unlink(missing_ok=True)
+ except OSError:
+ pass
+
# Stop the managed llama-server with its parent (an orphan pins VRAM).
try:
from hermes_cli.local_runtime.bootstrap import shutdown_local_runtime