Skip to content

The agent that grows with you

fix(webapp): detach a host terminal whose tab closes behind a full input queue

Adolaniumc2f6d93a49be
diff --git a/hermes_cli/web_host_terminal_sessions.py b/hermes_cli/web_host_terminal_sessions.py
index d0c48b7d7a2..ab487f6602b 100644
--- a/hermes_cli/web_host_terminal_sessions.py
+++ b/hermes_cli/web_host_terminal_sessions.py
@@ -9,7 +9,6 @@ refused and the reaper closes it.
from __future__ import annotations
import asyncio
-from collections import deque
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager, suppress
from dataclasses import dataclass
@@ -21,8 +20,8 @@ import secrets
from fastapi import HTTPException, WebSocket, WebSocketDisconnect
from hermes_cli.pty_session import (
- WS_CLOSE_VIEWER_STALLED, WS_CLOSE_VIEWER_STALLED_REASON, PtySession, PtySessionRegistry,
- RegistryFull, _close_ws, run_reaper,
+ _VIEWER_SEND_ERRORS, _VIEWER_SEND_TIMEOUT_SECONDS, WS_CLOSE_VIEWER_STALLED,
+ WS_CLOSE_VIEWER_STALLED_REASON, PtySession, PtySessionRegistry, RegistryFull, _close_ws, run_reaper,
)
from hermes_cli.web_host_terminal import META_PREFIX
from hermes_constants import assert_named_profile_home_live, get_hermes_home
@@ -32,11 +31,11 @@ RETENTION_SECONDS = 15 * 60
_MAX_SHELLS = 16
# Inbound frames buffered while one batch is written (backpressure bound).
_INPUT_BATCH_FRAMES = 64
+# How often a reader held up by that bound checks that the tab is still there (``_queue_frame``).
+# Once the connection is gone a check fails within about three: the first can still reach the
+# kernel before the peer's reset comes back.
+_LIVENESS_PROBE_SECONDS = 1.0
TOKEN_RE = re.compile(r"^[A-Za-z0-9_-]{43}$")
-# Puts abandoned because this task is already cancelling. Awaiting them here is
-# cancelled again before they finish; holding them until the callback reads the
-# result keeps "exception was never retrieved" off the loop.
-_DROPPED_TASKS: set[asyncio.Task] = set()
class TerminalDenied(Exception):
@@ -264,120 +263,47 @@ async def _admit(ws: WebSocket, registry: HostTerminalRegistry):
return session, owner
-def _read_dropped_task(task: asyncio.Task) -> None:
- _DROPPED_TASKS.discard(task)
- if not task.cancelled():
- task.exception()
+async def _queue_frame(ws: WebSocket, inbox: asyncio.Queue, ended: asyncio.Future, msg) -> None:
+ """``inbox.put(msg)``, checking that the tab is still there while the inbox stays full.
-
-def _drop_task(task: asyncio.Task) -> None:
- """Cancel ``task`` without awaiting it. Safe while this task is itself cancelling."""
- if not task.done():
- task.cancel()
- _DROPPED_TASKS.add(task)
- task.add_done_callback(_read_dropped_task)
-
-
-class _SocketTail:
- """Socket reads that stay ahead of a full inbox.
-
- The inbox bound is backpressure for a live viewer. A put that waits for room must
- not be the only thing the reader is doing: the tab's close is the next socket
- message, possibly behind further keystrokes, and it has to surface while that
- put is blocked. Frames already pulled are kept, in order, so a program that is
- still reading takes them. They are not dropped to make the queue move.
+ A full inbox stops the reader taking frames. That backpressure bounds what a tab can queue, but
+ it also leaves the tab's close unread behind those frames, and short of reading them only a send
+ can find out that the connection is gone. So while the put waits, the tab gets an empty binary
+ frame (no output, which the client ignores) every ``_LIVENESS_PROBE_SECONDS``; attach has already
+ sent the replay, so it is never taken for one. A send that fails means the connection is gone:
+ ``ended`` is set, which cancels a write waiting on the program, and the put goes on waiting
+ unprobed.
"""
-
- def __init__(self, ws: WebSocket):
- self._ws = ws
- self._ahead: deque = deque()
- self._recv: asyncio.Task | None = asyncio.create_task(ws.receive())
-
- def close(self) -> None:
- recv, self._recv = self._recv, None
- if recv is not None:
- _drop_task(recv)
-
- def pending_receive(self) -> asyncio.Task | None:
- return self._recv
-
- async def next_message(self):
- """The next data frame, or None once the socket has disconnected."""
- if self._ahead:
- return self._ahead.popleft()
- if self._recv is None:
- return None
- msg = await self._recv
- if msg.get("type") == "websocket.disconnect":
- self._recv = None
- return None
- self._recv = asyncio.create_task(self._ws.receive())
- return msg
-
- def saw_disconnect(self) -> bool:
- """Consume a receive that has already finished. Data stays queued ahead."""
- recv = self._recv
- if recv is None or not recv.done():
- return False
- msg = recv.result()
- if msg.get("type") == "websocket.disconnect":
- self._recv = None
- return True
- self._ahead.append(msg)
- self._recv = asyncio.create_task(self._ws.receive())
- return False
-
-
-async def _put_frame(inbox: asyncio.Queue, tail: _SocketTail, ended: asyncio.Future, msg) -> None:
- """Queue ``msg``. A full inbox still leaves the socket readable.
-
- On disconnect, ``ended`` is set before this put finishes, so a write waiting on
- the program is cancelled even though the frame itself stays queued for a pump
- that is still delivering input.
- """
- if not inbox.full():
- inbox.put_nowait(msg)
- return
- put = asyncio.create_task(inbox.put(msg))
- try:
- while not put.done():
- pending = tail.pending_receive()
- if pending is None:
- break
- await asyncio.wait((put, pending), return_when=asyncio.FIRST_COMPLETED)
- if tail.saw_disconnect() and not ended.done():
- ended.set_result(None)
- await put
- finally:
- if not put.done():
- _drop_task(put)
-
-
-async def _queue_until_close(tail: _SocketTail, inbox: asyncio.Queue, ended: asyncio.Future) -> None:
- while (msg := await tail.next_message()) is not None:
- await _put_frame(inbox, tail, ended, msg)
+ while not ended.done():
+ try:
+ return await asyncio.wait_for(inbox.put(msg), _LIVENESS_PROBE_SECONDS)
+ except TimeoutError:
+ pass
+ try:
+ await asyncio.wait_for(ws.send_bytes(b""), _VIEWER_SEND_TIMEOUT_SECONDS)
+ except _VIEWER_SEND_ERRORS:
+ ended.set_result(None)
+ await inbox.put(msg)
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). ``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."""
+ item as soon as reading ends, before it is queued, or None as soon as a full inbox finds the
+ socket gone (``_queue_frame``): 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 = None
- tail = _SocketTail(ws)
try:
- try:
- await _queue_until_close(tail, inbox, ended)
- except RuntimeError: # a superseding/drain task already closed us
- pass
- # health: allow BLE001 -- forwarded, not swallowed: _pump_input re-raises it, and a reader that died unqueued would hang the pump
- except Exception as exc:
- end = exc
- if not ended.done():
- ended.set_result(end)
- await inbox.put(end)
- finally:
- tail.close()
+ while (msg := await ws.receive()).get("type") != "websocket.disconnect":
+ await _queue_frame(ws, inbox, ended, msg)
+ except RuntimeError: # a superseding/drain task already closed us
+ pass
+ # health: allow BLE001 -- forwarded, not swallowed: _pump_input re-raises it, and a reader that died unqueued would hang the pump
+ except Exception as exc:
+ end = exc
+ if not ended.done():
+ ended.set_result(end)
+ await inbox.put(end)
async def _write_while_open(session: PtySession, ws: WebSocket, data: bytes, fence,
diff --git a/tests/hermes_cli/test_host_terminal_viewer_ownership.py b/tests/hermes_cli/test_host_terminal_viewer_ownership.py
index 4f9375a0ac1..1f1e4496355 100644
--- a/tests/hermes_cli/test_host_terminal_viewer_ownership.py
+++ b/tests/hermes_cli/test_host_terminal_viewer_ownership.py
@@ -1,15 +1,16 @@
"""Viewer takeover linearizes at the PTY sink, including off-loop writes."""
import asyncio
-from contextlib import contextmanager
+from contextlib import contextmanager, suppress
import os
from pathlib import Path
+import socket
import threading
import pytest
from hermes_cli.pty_session import PtySession, WS_CLOSE_SUPERSEDED
from hermes_cli.web_host_terminal_sessions import HostOwner, HostTerminalRegistry
-from tests.waiting import async_wait_until
+from tests.waiting import async_wait_until, wait_until
class Socket:
@@ -257,13 +258,15 @@ async def test_host_reaper_releases_dead_shell_before_drain_observes_eof(tmp_pat
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``."""
+ queues the disconnect for the next ``receive``. ``inbound`` holds what the server has not read
+ yet; ``sent`` is every binary frame the tab received."""
app = None
query_params: dict = {}
def __init__(self, *frames):
self.inbound = asyncio.Queue()
+ self.sent = []
self.type(*frames)
def type(self, *frames):
@@ -279,8 +282,8 @@ class ClosingTab:
async def send_text(self, _text):
pass
- async def send_bytes(self, _data):
- pass
+ async def send_bytes(self, data):
+ self.sent.append(data)
async def close(self, code=1000, reason=None):
pass
@@ -353,11 +356,7 @@ def unread_posix_pty(_monkeypatch):
@pytest.mark.asyncio
- "typed_after",
- ["quiet", "full", "overflow"],
- ids=["quiet", "full-inbox", "close-behind-full-inbox"],
-)
[email protected]("typed_after", [0, 64], ids=["quiet", "full-inbox"])
@pytest.mark.parametrize("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")),
@@ -369,13 +368,10 @@ async def test_closing_the_tab_during_a_waiting_paste_detaches_and_keeps_the_she
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, including when the close sits behind more frames than the queue holds."""
+ hide the close."""
from hermes_cli import web_host_terminal_sessions as host_sessions
- fill = host_sessions._INPUT_BATCH_FRAMES
- # Overflow is the put that blocks: the close is not the frame that fills the queue,
- # it is behind further keystrokes the reader has not queued yet.
- typed = {"quiet": 0, "full": fill, "overflow": fill + 17}[typed_after]
+ assert typed_after in (0, host_sessions._INPUT_BATCH_FRAMES)
home = tmp_path / ".hermes"
profile = home / "profiles" / "worker"
profile.mkdir(parents=True)
@@ -400,7 +396,7 @@ async def test_closing_the_tab_during_a_waiting_paste_detaches_and_keeps_the_she
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)
+ tab.type(*[b"k"] * typed_after)
tab.close_tab()
async with asyncio.timeout(5):
await handler
@@ -419,13 +415,140 @@ async def test_closing_the_tab_during_a_waiting_paste_detaches_and_keeps_the_she
await registry.close_all()
-class SlowAccept:
- """A program that reads every byte, but not until ``release``: slow, not stopped.
+class BrowserTab:
+ """A browser's end of the host terminal socket: a real WebSocket client on a plain TCP socket."""
+
+ def __init__(self, port):
+ from websockets.client import ClientProtocol
+ from websockets.protocol import State
+ from websockets.uri import parse_uri
+
+ self.protocol = ClientProtocol(parse_uri(f"ws://127.0.0.1:{port}/terminal"))
+ self.sock = socket.create_connection(("127.0.0.1", port), timeout=10)
+ self.protocol.send_request(self.protocol.connect())
+ self._flush()
+ while self.protocol.state is State.CONNECTING:
+ self.protocol.receive_data(self.sock.recv(65536))
+ assert self.protocol.state is State.OPEN, self.protocol.handshake_exc
+
+ def _flush(self):
+ self.sock.sendall(b"".join(self.protocol.data_to_send()))
+
+ def send(self, *frames):
+ for frame in frames:
+ self.protocol.send_binary(frame)
+ self._flush()
+
+ def close(self):
+ """Go away as a closing tab does: a close frame, then the TCP connection. A browser has read
+ everything the server sent, so the connection ends with a FIN, not a reset."""
+ self.protocol.send_close(1001)
+ self._flush()
+ self.sock.setblocking(False)
+ with suppress(BlockingIOError):
+ while self.sock.recv(65536):
+ pass
+ self.sock.close()
- The first write accepts its buffer (it does not report a full queue) and then waits.
- Later writes land immediately. Keystrokes that arrived while the first write waited
- must still be delivered, including ones that did not fit in the input queue.
- """
+
+@contextmanager
+def served_host_terminal(monkeypatch, session, owner):
+ """``host_terminal`` for ``session`` behind real uvicorn and Starlette on a loopback port, with
+ uvicorn's default WebSocket protocol and the loopback Webapp's settings (no WebSocket pings).
+ Yields the port, the frames the route has taken from the socket, and an Event set once the
+ route returns."""
+ import uvicorn
+ from starlette.applications import Starlette
+ from starlette.routing import WebSocketRoute
+ from hermes_cli import web_host_terminal_sessions as host_sessions
+
+ registry = HostTerminalRegistry()
+ taken, finished = [], threading.Event()
+
+ async def admit(_ws, _registry):
+ return session, owner
+
+ monkeypatch.setattr(host_sessions, "get_host_terminals", lambda _app: registry)
+ monkeypatch.setattr(host_sessions, "_admit", admit)
+
+ async def route(ws):
+ await ws.accept()
+ try:
+ await host_sessions.host_terminal(ws)
+ finally:
+ finished.set()
+
+ app = Starlette(routes=[WebSocketRoute("/terminal", route)])
+
+ async def counting(scope, receive, send):
+ async def counted():
+ message = await receive()
+ if message["type"] == "websocket.receive":
+ taken.append(message)
+ return message
+
+ await app(scope, counted, send)
+
+ sock = socket.socket()
+ sock.bind(("127.0.0.1", 0))
+ server = uvicorn.Server(uvicorn.Config(
+ counting, lifespan="off", log_level="error", ws_ping_interval=None, ws_ping_timeout=None,
+ # A route that never returns (the bug) is cancelled instead of holding shutdown forever.
+ timeout_graceful_shutdown=1,
+ ))
+ thread = threading.Thread(target=server.run, kwargs={"sockets": [sock]}, daemon=True)
+ thread.start()
+ try:
+ wait_until(lambda: server.started or not thread.is_alive(), what="uvicorn to start")
+ assert server.started
+ yield sock.getsockname()[1], taken, finished
+ finally:
+ server.should_exit = True
+ thread.join(10)
+ sock.close()
+ asyncio.run(registry.close_all())
+ assert not thread.is_alive()
+
+
[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")),
+])
+def test_a_tab_closed_behind_more_keys_than_the_input_queue_holds_is_detached(tmp_path, monkeypatch, terminal):
+ """Keys typed while a paste waits on a program that is not reading fill the input queue and
+ then some, so the tab's close is unread behind them when it comes, and the browser drops the
+ connection. Over a real socket the shell is still detached within a few seconds: it keeps
+ running, retained for a reattach."""
+ from hermes_cli import web_host_terminal_sessions as host_sessions
+
+ 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))
+ # 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))
+ fill = host_sessions._INPUT_BATCH_FRAMES
+ with terminal(monkeypatch) as (bridge, waiting, cancelled):
+ session = PtySession("terminal", bridge, buffer_cap=32, read_timeout=0.01)
+ with served_host_terminal(monkeypatch, session, owner) as (port, taken, finished):
+ tab = BrowserTab(port)
+ tab.send(paste)
+ assert waiting.wait(5), "the paste never waited for the program"
+ tab.send(*[b"k"] * (fill + 17))
+ # The paste, a full queue, and one more frame the reader holds with no room for it.
+ wait_until(lambda: len(taken) >= fill + 2, timeout=5, what="the reader to fill the input queue")
+ tab.close()
+ assert finished.wait(10), "the shell stayed attached after its tab closed"
+ assert cancelled.is_set()
+ assert session.alive and not bridge._closed
+ assert not session.attached and session._ws is None
+
+
+class SlowAccept:
+ """A program that reads every byte, but not until ``release``: slow, not stopped. The first write
+ takes its bytes and then waits; later writes land at once."""
def __init__(self):
self._closed = False
@@ -435,12 +558,11 @@ class SlowAccept:
async def write(self, data, *, timeout=10.0, fence=None):
assert timeout is None, "host terminal input has no deadline"
- accepted = await asyncio.to_thread(fence, lambda: len(data))
- assert accepted == len(data)
+ assert await asyncio.to_thread(fence, lambda: len(data)) == len(data)
if self._gated:
self._gated = False
self.entered.set()
- assert await asyncio.to_thread(self.release.wait, 5), "slow reader was not released"
+ assert await asyncio.to_thread(self.release.wait, 10), "the slow program was not released"
self.written.extend(data)
return True
@@ -455,10 +577,12 @@ class SlowAccept:
@pytest.mark.asyncio
-async def test_slow_program_keeps_keystrokes_typed_past_a_full_input_queue(tmp_path, monkeypatch):
- """A live tab's input is not dropped when the program reads slowly. Frames past the
- inbox bound stay in order and reach the shell once it takes them; the socket is read
- while the inbox is full, so a later close is not stuck behind that put."""
+async def test_a_live_tab_typing_past_a_full_input_queue_is_held_back_and_loses_nothing(tmp_path, monkeypatch):
+ """Keys typed while a write waits on a slow program queue up to the input bound. Past it the
+ reader takes no more frames, however many the tab sends (they wait in the socket, which pushes
+ back on the browser), and checks only that the tab is still there, which leaves a live tab
+ attached and writes nothing to its terminal. Once the program reads, every key reaches it in
+ order."""
from hermes_cli import web_host_terminal_sessions as host_sessions
home = tmp_path / ".hermes"
@@ -478,24 +602,29 @@ async def test_slow_program_keeps_keystrokes_typed_past_a_full_input_queue(tmp_p
monkeypatch.setattr(host_sessions, "get_host_terminals", lambda _app: registry)
monkeypatch.setattr(host_sessions, "_admit", admit)
+ fill = host_sessions._INPUT_BATCH_FRAMES
+ typed = [bytes([65 + n % 26]) for n in range(16 * fill)]
+ # The first write holds b"A"; the reader queues ``fill`` frames and holds one more with no room.
+ unread = len(typed) - fill - 1
tab = ClosingTab(b"A")
handler = None
try:
handler = asyncio.create_task(host_sessions.host_terminal(tab))
assert await asyncio.to_thread(bridge.entered.wait, 5), "the first write never started"
- extra = [bytes([65 + (n % 26)]) for n in range(host_sessions._INPUT_BATCH_FRAMES + 17)]
- tab.type(*extra)
- await async_wait_until(
- tab.inbound.empty, timeout=5,
- what="the reader to pull keystrokes sitting behind a full input queue",
- )
- assert session.attached, "a full queue is not a disconnect"
+ tab.type(*typed)
+ await async_wait_until(lambda: tab.inbound.qsize() <= unread, timeout=5,
+ what="the reader to fill the input queue")
+ assert tab.inbound.qsize() == unread, "the reader took frames past the input queue"
+ replayed = len(tab.sent)
+ await async_wait_until(lambda: len(tab.sent) > replayed, timeout=5,
+ what="a check on the tab behind the full input queue")
+ assert tab.inbound.qsize() == unread, "the reader took frames while it waited for room"
+ assert session.attached and session._ws is tab, "a live tab was detached"
+ assert b"".join(tab.sent[replayed:]) == b"", "the check wrote to the tab's terminal"
bridge.release.set()
- expected = b"A" + b"".join(extra)
- await async_wait_until(
- lambda: bytes(bridge.written) == expected, timeout=5,
- what="every keystroke to reach the slow program",
- )
+ expected = b"A" + b"".join(typed)
+ await async_wait_until(lambda: bytes(bridge.written) == expected, timeout=5,
+ what="every keystroke to reach the slow program")
tab.close_tab()
async with asyncio.timeout(5):
await handler