The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): never aim the resize erase past chrome tmux clipped (#95375)
teknium16d57e9ead435
diff --git a/hermes_cli/cli_terminal_mixin.py b/hermes_cli/cli_terminal_mixin.pyindex 32ddd8f3ad9..3b3e5784d2f 100644--- a/hermes_cli/cli_terminal_mixin.py+++ b/hermes_cli/cli_terminal_mixin.py@@ -29,6 +29,11 @@ _NO_REPLAY = (0, 0, False, None)# that long after the change (seconds): output freezes about their sum plus one signal interval._RESIZE_HOLD_MAX = 0.7_RESIZE_SETTLE = 0.03+# How long before a width change was first seen a chrome paint may still have reached the+# terminal after it narrowed (seconds; a paint the width moved under is always suspect): the+# signal lands a few ms after the multiplexer re-wraps, and it reads our output promptly — in+# tmux, paints that ended up to 4 ms before the signal were re-wrapped, never clipped (#95375).+_RESIZE_PAINT_MARGIN = 0.01def _is_eio(exc: BaseException) -> bool:@@ -292,26 +297,65 @@ class CLITerminalMixin:return rows, size.columns, _terminal_reflows() is not True@staticmethod- def _aim_erase_at_reflowed_chrome(app, columns: int) -> None:+ def _painted_row_widths(renderer) -> list[int]:+ """Cells each row of the renderer's last paint reaches: prompt_toolkit writes a row up to+ its last cell that shows something (the blanks after it are erase-to-end-of-line)."""+ screen = renderer._last_screen+ if screen is None:+ return []+ has_style = renderer._style_string_has_style+ return [1 + max((x for x, ch in screen.data_buffer[y].items() if ch.char != " " or has_style[ch.style]),+ default=0) for y in range(screen.height)]++ def _note_chrome_paint(self, app, full: bool) -> None:+ """Remember when each row of the chrome prompt_toolkit just drew was written, and how+ wide — ``full``: the whole chrome was written anew (for ``_aim_erase_at_reflowed_chrome``).+ A row only changes height when its width does, so only those changes are kept."""+ renderer = app.renderer+ size = renderer._last_size+ try: # the width moved while it rendered: the terminal may have got the rows clipped+ suspect = size is None or app.output.get_size().columns != size.columns+ except Exception:+ suspect = True+ now = time.monotonic()+ previous = [] if full else getattr(self, "_chrome_paints", [])+ paints = []+ for y, width in enumerate(self._painted_row_widths(renderer)):+ history = previous[y] if y < len(previous) else []+ if not history or history[-1][1] != width:+ history = [*history[-3:], (now, width, suspect)]+ paints.append(history)+ self._chrome_paints = paints+ self._chrome_paints_screen = renderer._last_screen++ def _aim_erase_at_reflowed_chrome(self, app, columns: int) -> None:"""Point prompt_toolkit's erase at the top of its last paint as a reflowing terminalre-wrapped it to ``columns`` (#95375).``renderer.erase()`` moves up ``_cursor_pos.y`` rows — right where rows stay in place,short of the top on a reflowing terminal, whose re-wrapped chrome rows would stay- above the new paint. prompt_toolkit writes a row up to its last cell that shows- something (the blanks after it are erase-to-end-of-line, which a reflow drops): that- width, re-wrapped, is the row's height now.+ above the new paint. A row's width, re-wrapped, is its height now — if the terminal got+ the row before it narrowed. prompt_toolkit writes rows with autowrap off, so one it got+ after narrowing (painted just before the width change was seen, the signal still on its+ way) was clipped to one row instead, and counting it as re-wrapped would erase+ transcript rows above the chrome. Rows painted within ``_RESIZE_PAINT_MARGIN`` of the+ width change, or unrecorded, count as one row: a stale chrome row left above the new+ paint is benign, an erased transcript row is lost for good."""renderer = app.rendererscreen, cursor = renderer._last_screen, renderer._cursor_posif screen is None or columns <= 0:return- has_style = renderer._style_string_has_style+ paints = getattr(self, "_chrome_paints", []) if getattr(self, "_chrome_paints_screen", None) is screen else []+ cutoff = (getattr(self, "_resize_seen_at", None) or time.monotonic()) - _RESIZE_PAINT_MARGINrows = cursor.x // columnsfor y in range(cursor.y):- row = screen.data_buffer[y]- last = max((x for x, ch in row.items() if ch.char != " " or has_style[ch.style]), default=0)- rows += -(-(last + 1) // columns)+ history = paints[y] if y < len(paints) else []+ settled = [i for i, (at, _width, suspect) in enumerate(history) if at < cutoff and not suspect]+ if settled: # re-wrapped as it was then, or as a later, narrower paint reached it+ rows += -(-min(width for _at, width, _suspect in history[settled[-1]:]) // columns)+ else:+ rows += 1renderer._cursor_pos = cursor._replace(y=rows)def _recover_after_resize(self, app, original_on_resize) -> None:@@ -450,6 +494,7 @@ class CLITerminalMixin:if pending or width is None or width != getattr(self, "_last_resize_width", None):if not pending:self._resize_recovery_pending = True+ self._resize_seen_at = now# A hold its last recovery could not release keeps its start: the# next recovery is due at once.if getattr(self, "_resize_hold_since", None) is None:@@ -496,11 +541,14 @@ class CLITerminalMixin:def _redraw_unless_resizing(render_as_done: bool = False) -> None:if render_as_done or not self._output_waits_for_resize(app):+ renderer = app.rendererfloor = _chrome_floor()if floor: # what CPR would tell prompt_toolkit: the rows down to the bottom- renderer = app.rendererrenderer._min_available_height = max(renderer._min_available_height, floor)+ before = renderer._last_screen, renderer._last_sizeoriginal_redraw(render_as_done=render_as_done)+ # prompt_toolkit repaints every row when it has no previous paint or a new size+ self._note_chrome_paint(app, before[0] is None or renderer._last_size != before[1])app._redraw = _redraw_unless_resizing_set_paint_gate(app, lambda: self._output_waits_for_resize(app))diff --git a/tests/e2e/core/cli_tmux/test_resize_scrollback.py b/tests/e2e/core/cli_tmux/test_resize_scrollback.pyindex a4a4cde8acb..bed57e44c73 100644--- a/tests/e2e/core/cli_tmux/test_resize_scrollback.py+++ b/tests/e2e/core/cli_tmux/test_resize_scrollback.py@@ -4,7 +4,9 @@ tmux's scrollback + screen exactly once, with no stray blank or prompt rows.A real ``hermes chat --cli`` runs in a private tmux server against the scripted fake provider.One session goes through a resize storm while a reply streams, a shrink while idle, and atwo-step shrink while the next reply streams; ``capture-pane -J`` then joins tmux's re-wrapped-rows back into lines. Mocked-renderer unit tests cannot see this: what lands in scrollback is+rows back into lines. Reply lines are 146 columns, so each one wraps at every width here, and+the two-step shrink lands as a line is committed — when the chrome may reach tmux before or+after it narrows. Mocked-renderer unit tests cannot see this: what lands in scrollback isdecided by how the terminal re-wraps the rows prompt_toolkit already wrote."""@@ -32,7 +34,7 @@ WORDS = {1: 60, 2: 260, 3: 130}def _reply(turn: int) -> str:words = [f"t{turn}w{i:03d}" for i in range(WORDS[turn])]- return "\n".join(" ".join(words[j:j + 13]) for j in range(0, len(words), 13))+ return "\n".join(" ".join(words[j:j + 21]) for j in range(0, len(words), 21))def test_resizes_keep_each_transcript_line_once_in_tmux_scrollback(tmp_path: Path) -> None:@@ -89,7 +91,7 @@ def test_resizes_keep_each_transcript_line_once_in_tmux_scrollback(tmp_path: Patresize(80) # idle shrinktime.sleep(1.5)ask(3)- wait_for("t3w020")+ wait_for("t3w020") # the end of the first line: its commit repaints the chromeresize(70) # two-step shrink mid-streamtime.sleep(0.8)resize(60)@@ -98,7 +100,13 @@ def test_resizes_keep_each_transcript_line_once_in_tmux_scrollback(tmp_path: Patfinally:tmux("kill-server")- words = Counter(re.findall(r"\bt\dw\d{3}\b", final))+ # A streaming-preview row painted as tmux narrowed may have been re-wrapped or clipped: it is+ # left rather than erased (a stale chrome row is benign, an erased transcript row is lost) —+ # at most one per mid-stream recovery: the drag's and each step's (#95375).+ lines = final.split("\n")+ stale_preview = [line for line in lines if line.lstrip().startswith("\u2026")]+ assert len(stale_preview) <= 3, final+ words = Counter(re.findall(r"\bt\dw\d{3}\b", "\n".join(ln for ln in lines if ln not in stale_preview)))expected = {f"t{t}w{i:03d}" for t, n in WORDS.items() for i in range(n)}assert sorted(w for w in expected if words[w] != 1) == [], finalassert [final.count(f"zq{t}q") for t in WORDS] == [1, 1, 1], finaldiff --git a/tests/hermes_cli/test_cli_force_redraw.py b/tests/hermes_cli/test_cli_force_redraw.pyindex 4da9f6309d4..a4ef4278258 100644--- a/tests/hermes_cli/test_cli_force_redraw.py+++ b/tests/hermes_cli/test_cli_force_redraw.py@@ -35,6 +35,7 @@ def _fake_app(*, rows, columns, chrome, painted=None, cursor_y=0):app = MagicMock()app.renderer.output.get_size.return_value = Size(rows=rows, columns=columns)+ app.output = app.renderer.outputscreen = Noneif painted is not None:screen = Screen()@@ -59,17 +60,23 @@ class TestForceFullRedraw:- @pytest.mark.parametrize("reflows,new_width,history_lines", [- (True, 90, 40), (False, 90, 40), (None, 90, 40), (None, 250, 40), (False, 90, 2)])- def test_resize_never_loses_or_reprints_a_row(self, bare_cli, monkeypatch, reflows, new_width, history_lines):+ @pytest.mark.parametrize("reflows,new_width,history_lines,paint", [+ (True, 90, 40, "settled"), (True, 90, 40, "late"), (True, 90, 40, "clipped"), (False, 90, 40, "settled"),+ (None, 90, 40, "settled"), (None, 250, 40, "settled"), (False, 90, 2, "settled")])+ def test_resize_never_loses_or_reprints_a_row(self, bare_cli, monkeypatch, reflows, new_width, history_lines,+ paint):"""#95375: on a shrink a reflowing terminal has pushed the rows that grew intoscrollback, so nothing is erased and replayed there — prompt_toolkit's erase is only- aimed at the chrome's re-wrapped top. A terminal that does not reflow (or may not)+ aimed at the chrome's re-wrapped top. A chrome paint the terminal may have got after+ it narrowed (painted right before the width change was seen, or while the width moved)+ was clipped, not re-wrapped: its rows count as one each, so the erase never reaches the+ transcript above. A terminal that does not reflow (or may not)keeps every visible row in place, truncated: the viewport is erased row by row (noCSI 2J, no 3J) and refilled from its top row with what it held, counted at the width itwas painted at, before prompt_toolkit repaints. When the viewport holds the wholehistory, only its rows and the chrome are erased: rows above it (the startup banner)were never recorded. A widen truncates nothing and is left alone."""+ import timefrom collections import dequefrom prompt_toolkit.layout.screen import Char@@ -93,14 +100,23 @@ class TestForceFullRedraw:monkeypatch.setattr(cli_mod, "_terminal_reflows", lambda: reflows)monkeypatch.setattr(cli_mod, "CLI_CONFIG", {"display": {"cli_rebuild_scrollback_on_redraw": False}})cli_mod._set_chrome_floor(None)+ from prompt_toolkit.data_structures import Size+ app.renderer._last_size = Size(rows=30, columns=200) # the paint: at the old width+ out.get_size.return_value = Size(rows=30, columns=new_width if paint == "clipped" else 200)+ bare_cli._note_chrome_paint(app, True)+ from hermes_cli.cli_terminal_mixin import _RESIZE_PAINT_MARGIN+ bare_cli._resize_seen_at = time.monotonic() + (_RESIZE_PAINT_MARGIN / 2 if paint == "late" else 1.0)+ out.get_size.return_value = Size(rows=30, columns=new_width)bare_cli._recover_after_resize(app, lambda: events.append(("original_resize", app.renderer._cursor_pos.y)))if new_width > 200:assert events == [("original_resize", 4)]- elif reflows:+ elif reflows and paint == "settled":assert events == [("original_resize", 1 + 3 + 1 + 3)]+ elif reflows:+ assert events == [("original_resize", 4)]elif history_lines == 2: # 2 lines x 2 rows, right above the chromeassert events[:4] == [("raw", "\r"), ("up", 4 + 4), "erase_down", ("replay", (25, 90, True, None), out)]assert events[4][0] == "original_resize" and len(events) == 5