The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): detach a host terminal whose tab closes while a paste waits for the program
emozillacab0f9fee8c4
diff --git a/hermes_cli/web_host_terminal_sessions.py b/hermes_cli/web_host_terminal_sessions.pyindex aef3f52c7ca..61f2d110b99 100644--- a/hermes_cli/web_host_terminal_sessions.py+++ b/hermes_cli/web_host_terminal_sessions.py@@ -259,9 +259,11 @@ async def _admit(ws: WebSocket, registry: HostTerminalRegistry):return session, owner-async def _read_frames(ws: WebSocket, inbox: asyncio.Queue) -> None:+async def _read_frames(ws: WebSocket, inbox: asyncio.Queue, ended: asyncio.Future) -> None:"""Queue inbound frames. The last item is None, or the error that ended reading- (re-raised by ``_pump_input`` so the route's handlers still see it)."""+ (re-raised by ``_pump_input`` so the route's handlers still see it). ``ended`` gets the same+ item as soon as reading ends, before it is queued: a write waiting on the shell, or a full+ inbox behind it, must not keep the pump from seeing that the socket is gone."""end = Nonetry:while (msg := await ws.receive()).get("type") != "websocket.disconnect":@@ -271,9 +273,47 @@ async def _read_frames(ws: WebSocket, inbox: asyncio.Queue) -> None:# health: allow BLE001 -- forwarded, not swallowed: _pump_input re-raises it, and a reader that died unqueued would hang the pumpexcept Exception as exc:end = exc+ ended.set_result(end)await inbox.put(end)+async def _write_while_open(session: PtySession, ws: WebSocket, data: bytes, fence,+ ended: asyncio.Future) -> bool | None:+ """``session.write`` of *data* with no deadline while the socket is open, or None once the+ socket has ended and the write has to wait for the program to read.++ The program may leave its input unread for as long as it likes, but not past the viewer. Input+ the tab sent before it closed still reaches the program as far as the program takes it; the+ first time the write then has to wait for room, it is cancelled (the rest is dropped, as on a+ takeover) and the session stays alive for the caller to detach.+ """+ loop = asyncio.get_running_loop()+ stalled = asyncio.Event()++ def watched(write):+ accepted = fence(write)+ # The POSIX bridge reports 0 bytes taken when the program's input queue is full; it then+ # waits for room. Runs in the bridge's worker thread.+ full = type(accepted) is int and accepted == 0+ loop.call_soon_threadsafe(stalled.set if full else stalled.clear)+ return accepted++ write = asyncio.ensure_future(session.write(ws, data, fence=watched, timeout=None))+ try:+ await asyncio.wait((write, ended), return_when=asyncio.FIRST_COMPLETED)+ if not write.done():+ stall = asyncio.ensure_future(stalled.wait())+ try:+ await asyncio.wait((write, stall), return_when=asyncio.FIRST_COMPLETED)+ finally:+ stall.cancel()+ finally:+ if not write.done():+ write.cancel()+ await asyncio.wait((write,))+ return None if write.cancelled() else write.result()++def _input_runs(frames: list[dict], resize_re):"""``frames`` in order: consecutive keystrokes joined into one run, resizes as ``(cols, rows)``."""run = b""@@ -306,13 +346,15 @@ async def _pump_input(ws: WebSocket, registry: HostTerminalRegistry, token: str,Writes have no deadline. While the foreground program is not reading (``sleep``,``npm install``) the PTY takes about 1 KB of input on macOS, so a paste waits forthat program, in order, with any Ctrl-C behind it, as in native Desktop's terminal.- A re-attach cancels the wait and keeps the shell; only a closed bridge (the shell+ A re-attach or the socket closing cancels the wait and keeps the shell (``host_terminal``+ then detaches it, so the retention reaper owns it again); only a closed bridge (the shellexited or the terminal was closed) or a deleted profile drops the session. ConPTYbuffers input itself, so Windows writes land at once and keep the bridge's deadline."""from hermes_cli.web_server_chat import _RESIZE_REinbox: asyncio.Queue = asyncio.Queue(maxsize=_INPUT_BATCH_FRAMES)- reader = asyncio.create_task(_read_frames(ws, inbox))+ ended = asyncio.get_running_loop().create_future()+ reader = asyncio.create_task(_read_frames(ws, inbox, ended))try:# No Ctrl-L/redraw input: arbitrary foreground shell programs own stdin.while session._ws is ws and session.alive:@@ -325,10 +367,16 @@ async def _pump_input(ws: WebSocket, registry: HostTerminalRegistry, token: str,session.resize(ws, cols=item[0], rows=item[1])continuetry:- delivered = await session.write(ws, item, fence=owner.admit, timeout=None)+ delivered = await _write_while_open(session, ws, item, owner.admit, ended)except (TerminalExpired, FileNotFoundError):await registry.remove(token)return+ if delivered is None:+ # The socket ended and this input was left waiting for the program: stop here,+ # so the caller detaches a shell that is still running.+ if isinstance(ended.result(), Exception):+ raise ended.result()+ returnif not delivered:# A closed bridge marked the session dead. A takeover only cancelled this# write: drop the rest of the batch and leave this socket for the new viewerdiff --git a/tests/hermes_cli/test_host_terminal_viewer_ownership.py b/tests/hermes_cli/test_host_terminal_viewer_ownership.pyindex 2684faabda1..76b686b51c9 100644--- a/tests/hermes_cli/test_host_terminal_viewer_ownership.py+++ b/tests/hermes_cli/test_host_terminal_viewer_ownership.py@@ -252,3 +252,161 @@ async def test_host_reaper_releases_dead_shell_before_drain_observes_eof(tmp_patfinally:await registry.close_all()await asyncio.to_thread(bridge.close)+++class ClosingTab:+ """A browser tab on the host terminal: it sends ``frames``, then whatever ``type`` adds, and its+ socket ends when ``close`` is called. Closing never cancels the route: like uvicorn, it only+ queues the disconnect for the next ``receive``."""++ app = None+ query_params: dict = {}++ def __init__(self, *frames):+ self.inbound = asyncio.Queue()+ self.type(*frames)++ def type(self, *frames):+ for frame in frames:+ self.inbound.put_nowait({"type": "websocket.receive", "bytes": frame})++ def close_tab(self):+ self.inbound.put_nowait({"type": "websocket.disconnect"})++ async def receive(self):+ return await self.inbound.get()++ async def send_text(self, _text):+ pass++ async def send_bytes(self, _data):+ pass++ async def close(self, code=1000, reason=None):+ pass+++class UnreadInput:+ """The POSIX bridge while the foreground program is not reading: its input queue is full, so a+ write takes 0 bytes and then, with no deadline, waits for room until it is cancelled."""++ def __init__(self):+ self._closed = False+ self.waiting, self.cancelled = threading.Event(), threading.Event()++ async def write(self, data, *, timeout=10.0, fence=None):+ assert timeout is None, "host terminal input has no deadline"+ assert await asyncio.to_thread(fence, lambda: 0) == 0+ self.waiting.set()+ try:+ await asyncio.get_running_loop().create_future()+ except asyncio.CancelledError:+ self.cancelled.set()+ raise++ def resize(self, cols, rows):+ pass++ def close(self):+ self._closed = True++ def is_alive(self):+ return not self._closed+++@contextmanager+def unread_input(_monkeypatch):+ bridge = UnreadInput()+ yield bridge, bridge.waiting, bridge.cancelled+++@contextmanager+def unread_posix_pty(_monkeypatch):+ """The POSIX bridge on a real pseudo-terminal that nobody reads: a paste fills its input buffers+ and then waits for room."""+ import pty+ import tty+ from hermes_cli import pty_bridge++ master, slave = pty.openpty()+ tty.setraw(slave)+ os.set_blocking(master, False)+ bridge = pty_bridge.PtyBridge.__new__(pty_bridge.PtyBridge)+ bridge._fd, bridge._closed, bridge._fd_lock = master, False, threading.Lock()+ waiting, cancelled = threading.Event(), threading.Event()+ wait_writable = bridge._wait_writable++ async def watched(timeout):+ waiting.set()+ try:+ return await wait_writable(timeout)+ except asyncio.CancelledError:+ cancelled.set()+ raise++ bridge._wait_writable = watched+ try:+ yield bridge, waiting, cancelled+ finally:+ os.close(master)+ os.close(slave)++[email protected]("typed_after", [0, 64], ids=["quiet", "full-inbox"])[email protected]("terminal", [+ pytest.param(unread_posix_pty, id="posix-pty", marks=pytest.mark.platforms("posix")),+ pytest.param(unread_input, id="unread-input", marks=pytest.mark.platforms("any")),+])+async def test_closing_the_tab_during_a_waiting_paste_detaches_and_keeps_the_shell(+ tmp_path, monkeypatch, terminal, typed_after,+):+ """A paste into a program that is not reading (``sleep``, ``npm install``) waits for it with no+ deadline. When the tab closes meanwhile, the wait is cancelled and the shell is detached, as on+ any disconnect: it keeps running, retained for a reattach, and the reaper retires it once its+ retention runs out. A full input queue behind the paste (keys typed while it waited) does not+ hide the close."""+ from hermes_cli import web_host_terminal_sessions as host_sessions++ assert typed_after in (0, host_sessions._INPUT_BATCH_FRAMES)+ home = tmp_path / ".hermes"+ profile = home / "profiles" / "worker"+ profile.mkdir(parents=True)+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(home))+ owner = HostOwner(("loopback", "test"), profile, "sh", str(tmp_path))+ registry = HostTerminalRegistry()+ # 1 MiB: more than a pseudo-terminal buffers anywhere between its master and the program.+ paste = b"".join(b"%05d %s\n" % (n, b"x" * 57) for n in range(16 * 1024))+ handler = None+ with terminal(monkeypatch) as (bridge, waiting, cancelled):+ session = PtySession("terminal", bridge, buffer_cap=32, read_timeout=0.01)+ registry._sessions[session.key] = session+ registry.owners[session.key] = owner++ async def admit(_ws, _registry):+ return session, owner++ monkeypatch.setattr(host_sessions, "get_host_terminals", lambda _app: registry)+ monkeypatch.setattr(host_sessions, "_admit", admit)+ tab = ClosingTab(paste)+ try:+ handler = asyncio.create_task(host_sessions.host_terminal(tab))+ assert await asyncio.to_thread(waiting.wait, 5), "the paste never waited for the program"+ tab.type(*[b"k"] * typed_after)+ tab.close_tab()+ async with asyncio.timeout(5):+ await handler+ assert cancelled.is_set()+ assert session.alive and not bridge._closed+ assert registry._sessions.get(session.key) is session+ assert not session.attached and session._ws is None+ assert session.last_detached_at is not None+ assert registry.expired(session, session.last_detached_at + registry._ttl + 1)+ finally:+ if handler is not None:+ handler.cancel()+ await asyncio.gather(handler, return_exceptions=True)+ registry._sessions.clear()+ registry.owners.clear()+ await registry.close_all()