Skip to content

The agent that grows with you

fix(webapp): hold the redraw's step back until the program answered the step

unsupportedpastelse843e0427f1d
diff --git a/apps/desktop/src/lib/browser-terminal.ts b/apps/desktop/src/lib/browser-terminal.ts
index ecf437a55b7..040dba87470 100644
--- a/apps/desktop/src/lib/browser-terminal.ts
+++ b/apps/desktop/src/lib/browser-terminal.ts
@@ -72,7 +72,8 @@ function settleOpen(state: TerminalState): void {
}
/** A trimmed replay can start mid-way through a full-screen program's output, and an
- * unchanged size sends no SIGWINCH: step one row away first so the program redraws. */
+ * unchanged size sends no SIGWINCH: step one row away first so the program redraws. The server
+ * holds the step back until the program has answered the step (web_host_terminal_sessions._resize). */
function sendResumeSize(socket: WebSocket, state: TerminalState, trimmed?: boolean): void {
if (trimmed) {socket.send(`\u001b[RESIZE:${state.cols};${state.rows > 1 ? state.rows - 1 : state.rows + 1}]`)}
socket.send(`\u001b[RESIZE:${state.cols};${state.rows}]`)
diff --git a/hermes_cli/pty_bridge.py b/hermes_cli/pty_bridge.py
index 80bd8c826f1..8221afa3d7e 100644
--- a/hermes_cli/pty_bridge.py
+++ b/hermes_cli/pty_bridge.py
@@ -302,6 +302,17 @@ class PtyBridge:
except OSError:
pass
+ def size(self) -> Optional[tuple[int, int]]:
+ """The child's ``(cols, rows)`` (``TIOCGWINSZ``), or None once the PTY is closed."""
+ if self._closed:
+ return None
+ try:
+ rows, cols, _xpixel, _ypixel = struct.unpack(
+ "HHHH", fcntl.ioctl(self._fd, termios.TIOCGWINSZ, bytes(8)))
+ except OSError:
+ return None
+ return cols, rows
+
def _discard_output(self, timeout: float) -> None:
# Exiting children flush their pending terminal output first; on macOS a process stays in
# exit (and a SIGHUP save outlasts the grace) until someone drains the master. The drain
diff --git a/hermes_cli/pty_session.py b/hermes_cli/pty_session.py
index 3d6d1aa7f28..dbd22186e5b 100644
--- a/hermes_cli/pty_session.py
+++ b/hermes_cli/pty_session.py
@@ -127,6 +127,9 @@ class PtySession:
self._output_lock = asyncio.Lock()
self._input_task: Optional[asyncio.Task] = None
self._close_task: Optional[asyncio.Task] = None
+ # Chunks of output read so far, and set when one arrives (``wait_for_output``).
+ self._outputs = 0
+ self._output_arrived = asyncio.Event()
async def start(self) -> None:
self._drain_task = asyncio.create_task(self._drain())
@@ -149,6 +152,8 @@ class PtySession:
await asyncio.sleep(0)
continue
self.buffer.append(chunk)
+ self._outputs += 1
+ self._output_arrived.set()
ws = self._ws
output_lock = self._output_lock
try:
@@ -211,6 +216,30 @@ class PtySession:
if self._ws is ws and self.alive:
self.bridge.resize(cols=cols, rows=rows)
+ def size(self) -> Optional[tuple[int, int]]:
+ """The PTY's ``(cols, rows)``, or None where the bridge cannot tell (ConPTY, stubs)."""
+ return self.bridge.size() if hasattr(self.bridge, "size") else None
+
+ @property
+ def outputs(self) -> int:
+ """How many chunks of output have been read from the program so far."""
+ return self._outputs
+
+ async def wait_for_output(self, since: int, timeout: float) -> None:
+ """Return once output past ``since`` (an ``outputs`` value) has been read, the session has
+ ended, or ``timeout`` seconds have passed."""
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + timeout
+ while self.alive and self._outputs == since:
+ self._output_arrived.clear()
+ remaining = deadline - loop.time()
+ if remaining <= 0:
+ return
+ try:
+ await asyncio.wait_for(self._output_arrived.wait(), remaining)
+ except TimeoutError:
+ return
+
async def attach(
self, ws, *, force_redraw: bool = False,
initial_text: Optional[str | Callable[[bool], str]] = None,
diff --git a/hermes_cli/web_host_terminal_sessions.py b/hermes_cli/web_host_terminal_sessions.py
index 61f2d110b99..ca303501cd6 100644
--- a/hermes_cli/web_host_terminal_sessions.py
+++ b/hermes_cli/web_host_terminal_sessions.py
@@ -31,6 +31,8 @@ RETENTION_SECONDS = 15 * 60
_MAX_SHELLS = 16
# Inbound frames buffered while one batch is written (backpressure bound).
_INPUT_BATCH_FRAMES = 64
+# How long a resize that undoes the previous one waits for the program to answer that one (``_resize``).
+_RESIZE_ANSWER_SECONDS = 1.0
TOKEN_RE = re.compile(r"^[A-Za-z0-9_-]{43}$")
@@ -333,6 +335,24 @@ def _input_runs(frames: list[dict], resize_re):
yield run
+async def _resize(session: PtySession, ws: WebSocket, size: tuple[int, int], undo):
+ """Apply ``size``; return what the next resize needs to tell whether it undoes this one.
+
+ A program can read the size well after its SIGWINCH (Node, behind its event loop, and reports a
+ 'resize', which Hermes' TUI redraws on, only when the size it reads has changed). A step undone
+ before it looks is never seen: both signals find the size it already had. So a resize back to
+ the size before the previous one first waits until the program has written output since that
+ one, as a program that redraws on a resize does, or ``_RESIZE_ANSWER_SECONDS`` for one that
+ does not. ``undo`` is ``(size before the previous resize, outputs when it was applied)``, set
+ only when that resize changed the size.
+ """
+ if undo is not None and undo[0] == size:
+ await session.wait_for_output(undo[1], _RESIZE_ANSWER_SECONDS)
+ before = session.size()
+ session.resize(ws, cols=size[0], rows=size[1])
+ return (before, session.outputs) if before is not None and before != size else None
+
+
async def _pump_input(ws: WebSocket, registry: HostTerminalRegistry, token: str,
session: PtySession, owner: HostOwner) -> None:
"""Forward keystrokes and resizes while ``ws`` is the attached viewer.
@@ -355,6 +375,7 @@ async def _pump_input(ws: WebSocket, registry: HostTerminalRegistry, token: str,
inbox: asyncio.Queue = asyncio.Queue(maxsize=_INPUT_BATCH_FRAMES)
ended = asyncio.get_running_loop().create_future()
reader = asyncio.create_task(_read_frames(ws, inbox, ended))
+ undo = None
try:
# No Ctrl-L/redraw input: arbitrary foreground shell programs own stdin.
while session._ws is ws and session.alive:
@@ -364,7 +385,7 @@ async def _pump_input(ws: WebSocket, registry: HostTerminalRegistry, token: str,
frames = [msg for msg in batch if isinstance(msg, dict)]
for item in _input_runs(frames, _RESIZE_RE):
if isinstance(item, tuple):
- session.resize(ws, cols=item[0], rows=item[1])
+ undo = await _resize(session, ws, item, undo)
continue
try:
delivered = await _write_while_open(session, ws, item, owner.admit, ended)
diff --git a/tests/hermes_cli/test_host_terminal_redraw.py b/tests/hermes_cli/test_host_terminal_redraw.py
new file mode 100644
index 00000000000..53d45fc3713
--- /dev/null
+++ b/tests/hermes_cli/test_host_terminal_redraw.py
@@ -0,0 +1,143 @@
+"""The resize pair that redraws a host terminal's program reaches it as two observed sizes."""
+import asyncio
+import shutil
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_cli import web_host_terminal_sessions
+from hermes_cli.pty_session import PtySession
+from hermes_cli.web_host_terminal_sessions import HostOwner, _pump_input, _resize
+
+# Programs that, like Node's stdout 'resize' event (Hermes' TUI redraws on it), report a size only
+# when the one they read differs from the last, and read it after a busy event loop gets to it.
+_PYTHON_SIZE_WATCHER = """
+import os, signal, time
+pending = []
+signal.signal(signal.SIGWINCH, lambda *_: pending.append(1))
+last = os.get_terminal_size(1)
+print('READY', flush=True)
+while True:
+ time.sleep(0.2)
+ if pending:
+ pending.clear()
+ size = os.get_terminal_size(1)
+ if size != last:
+ last = size
+ print('RESIZE', size.lines, flush=True)
+ print('WINCH', flush=True)
+ print('TICK', flush=True)
+"""
+_NODE_SIZE_WATCHER = (
+ "process.stdout.on('resize', () => process.stdout.write('RESIZE ' + process.stdout.rows + '\\n'));"
+ "process.on('SIGWINCH', () => process.stdout.write('WINCH\\n'));"
+ "process.stdout.write('READY\\n'); setInterval(() => process.stdout.write('TICK\\n'), 200)"
+)
+
+
+class Tab:
+ """The attached browser tab: it keeps what the program prints and sends ``send``'s frames."""
+
+ query_params: dict = {}
+
+ def __init__(self):
+ self.output = b""
+ self.inbound = asyncio.Queue()
+
+ def send(self, *frames):
+ for frame in frames:
+ self.inbound.put_nowait({"type": "websocket.receive", "text": 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):
+ self.output += data
+
+ async def close(self, code=1000, reason=None):
+ pass
+
+
[email protected]("answered", [True, False], ids=["answered", "unanswered"])
[email protected]("watcher", ["python", "node"])
+async def test_a_resize_back_waits_until_the_program_answered_the_step(tmp_path, monkeypatch, watcher, answered):
+ """After a trimmed replay the browser steps the size one row away and back (browser-terminal.ts)
+ so the foreground program redraws. Applied back to back, both SIGWINCHes can reach the program
+ after the size is back where it was: it sees no change and does not redraw. The step back waits
+ until the program has answered the first step; without that wait (``unanswered``) the signals
+ arrive but neither step is seen."""
+ from hermes_cli.pty_bridge import PtyBridge
+
+ if watcher == "node":
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("node is not installed")
+ argv = [node, "-e", _NODE_SIZE_WATCHER]
+ else:
+ argv = [sys.executable, "-u", "-c", _PYTHON_SIZE_WATCHER]
+ if not answered:
+ monkeypatch.setattr(web_host_terminal_sessions, "_RESIZE_ANSWER_SECONDS", 0, raising=False)
+
+ async def remove(_token):
+ pass
+
+ bridge = PtyBridge.spawn(argv, cwd=str(tmp_path), cols=80, rows=24)
+ session = PtySession("terminal", bridge, buffer_cap=1 << 16, read_timeout=0.01)
+ owner = HostOwner(("loopback", "test"), tmp_path, "sh", str(tmp_path))
+ tab = Tab()
+ pump = None
+ await session.start()
+ try:
+ assert await session.attach(tab)
+ async with asyncio.timeout(10):
+ while b"READY" not in tab.output:
+ await asyncio.sleep(0.01)
+ start = len(tab.output)
+ # The redraw's two frames, arriving together as they leave the browser.
+ tab.send("\x1b[RESIZE:80;23]", "\x1b[RESIZE:80;24]")
+ pump = asyncio.create_task(_pump_input(tab, SimpleNamespace(remove=remove), "terminal", session, owner))
+ # The program prints TICK five times a second: give it three seconds.
+ async with asyncio.timeout(10):
+ while b"RESIZE 24" not in tab.output[start:] and tab.output[start:].count(b"TICK") < 15:
+ await asyncio.sleep(0.01)
+ seen = tab.output[start:]
+ tab.close_tab()
+ await asyncio.wait_for(pump, 5)
+ finally:
+ if pump is not None:
+ pump.cancel()
+ await session.close()
+ await asyncio.to_thread(bridge.close)
+ assert b"WINCH" in seen
+ reported = [line for line in seen.split(b"\r\n") if line.startswith(b"RESIZE ")]
+ assert reported == ([b"RESIZE 23", b"RESIZE 24"] if answered else [])
+
+
[email protected]("knows_size", [True, False], ids=["posix", "conpty"])
+async def test_only_a_resize_that_undoes_the_previous_one_waits(knows_size):
+ """A drag's resizes are applied at once; so are repeats of the same size and every resize on a
+ bridge that cannot report its size."""
+ current = [(80, 24)]
+ waits = []
+
+ async def wait_for_output(since, timeout):
+ waits.append((since, timeout))
+
+ session = SimpleNamespace(
+ size=lambda: current[0] if knows_size else None, outputs=7, wait_for_output=wait_for_output,
+ resize=lambda _ws, *, cols, rows: current.__setitem__(0, (cols, rows)))
+ undo = None
+ for step in [(80, 23), (80, 24), (100, 30), (100, 30), (80, 24), (90, 24)]:
+ undo = await _resize(session, None, step, undo)
+ assert current[0] == step
+ assert waits == ([(7, web_host_terminal_sessions._RESIZE_ANSWER_SECONDS)] if knows_size else [])