The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): resize keeps each transcript row once on tmux and never loses rows elsewhere (#95375)
teknium168b0f85d46ca
diff --git a/cli.py b/cli.pyindex 4e36e22b3c2..87584f3d115 100644--- a/cli.py+++ b/cli.py@@ -121,6 +121,7 @@ from hermes_cli.cli_render import ( # noqa: F401,E402_query_osc11_background,_record_output_history,_record_output_history_entry,+ _release_paints,_render_final_assistant_content,_rich_text_from_ansi,_strip_markdown_syntax,@@ -650,12 +651,15 @@ def _suspend_output_history():_OUTPUT_HISTORY_SUPPRESSED = old_value-def _replay_output_history(fit=None) -> None:+def _replay_output_history(fit=None, output=None) -> None:"""Repaint recent output above the prompt after a full screen clear.``fit=(rows, columns, painted)`` replays only the newest lines whose wrapped heightfits ``rows`` (see ``_output_tail_fitting``) — the older ones are still in scrollback- (#95375).+ (#95375). ``output``: paint now, straight to this prompt_toolkit output, where the caller+ just erased the viewport and reset the renderer — ``run_in_terminal`` would first erase+ below the top row, which scroll-on-clear terminals (tmux) take as a clear and copy the+ blank screen into scrollback."""global _OUTPUT_HISTORY_REPLAYINGif not _OUTPUT_HISTORY_ENABLED or not _OUTPUT_HISTORY:@@ -677,7 +681,12 @@ def _replay_output_history(fit=None) -> None:rendered_lines = _output_tail_fitting(rendered_lines, *fit)if rendered_lines:# One payload: per-line pt prints each force a sync redraw (a waterfall of old output).- _pt_print(_PT_ANSI("\n".join(rendered_lines)))+ if output is None:+ _pt_print(_PT_ANSI("\n".join(rendered_lines)))+ else:+ from prompt_toolkit.renderer import print_formatted_text as _paint_formatted_text+ from prompt_toolkit.styles import Style+ _paint_formatted_text(output, _PT_ANSI("\n".join(rendered_lines) + "\n"), Style([]))width = _painted_columns()for line in rendered_lines: # repainted: they wrap at today's width from now onif isinstance(line, _PaintedLine):@@ -1479,6 +1488,8 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,else:raisefinally:+ # A resize right before exit leaves its recovery (and the paints it held) unrun.+ _release_paints()self._tui_shutdown()# /update relaunch happens here, after prompt_toolkit restored terminal modes, on thediff --git a/hermes_cli/cli_chat_turn_mixin.py b/hermes_cli/cli_chat_turn_mixin.pyindex 5dec6ac71ca..a7da8013cfe 100644--- a/hermes_cli/cli_chat_turn_mixin.py+++ b/hermes_cli/cli_chat_turn_mixin.py@@ -117,7 +117,7 @@ class CLIChatTurnMixin:self._chat_settle_turn(turn)return self._chat_render_turn(turn, agent_thread, interrupt_msg)except Exception as e:- print(f"Error: {e}")+ _cprint(f"Error: {e}")return Nonefinally:self._chat_release_turn_audio(turn)@@ -397,7 +397,7 @@ class CLIChatTurnMixin:def _chat_monitor_agent_thread(self, turn, agent_thread):"""Poll the interrupt queue while the agent thread runs; returns the interrupting message (or None)."""- from cli import _hermes_home, logger+ from cli import _cprint, _hermes_home, logger# Ambient "thinking" blips in voice mode; skipped per-blip while TTS speaks, the mic# records or a barge capture is live. voice.thinking_sound gates it (default on).if self._voice_mode:@@ -430,7 +430,7 @@ class CLIChatTurnMixin:passinterrupt_msg = Nonecontinue- print("\n⚡ New message detected, interrupting...")+ _cprint("\n⚡ New message detected, interrupting...")if turn.stop_event is not None:turn.stop_event.set()self.agent.interrupt(interrupt_msg)@@ -594,16 +594,16 @@ class CLIChatTurnMixin:payload = (combined, image_parts) if image_parts else combinedpreview = combined[:50] + ("..." if len(combined) > 50 else "")if len(all_parts) > 1:- print(f"\n⚡ Sending {len(all_parts)} messages after interrupt: '{preview}'")+ _cprint(f"\n⚡ Sending {len(all_parts)} messages after interrupt: '{preview}'")else:- print(f"\n⚡ Sending after interrupt: '{preview}'")+ _cprint(f"\n⚡ Sending after interrupt: '{preview}'")self._pending_input.put(payload)# A /steer the agent finished before absorbing becomes the next user turn._leftover_steer = turn.result.get("pending_steer") if turn.result else Noneif _leftover_steer:preview = _leftover_steer[:60] + ("..." if len(_leftover_steer) > 60 else "")- print(f"\n⏩ Delivering leftover /steer as next turn: '{preview}'")+ _cprint(f"\n⏩ Delivering leftover /steer as next turn: '{preview}'")self._pending_input.put(_leftover_steer)return responsediff --git a/hermes_cli/cli_render.py b/hermes_cli/cli_render.pyindex 127f9ba885c..bb696ec084d 100644--- a/hermes_cli/cli_render.py+++ b/hermes_cli/cli_render.py@@ -500,14 +500,11 @@ class _PaintedLine(str):def _painted_columns():"""The width the terminal soft-wraps a print at right now, or ``None``."""+ from prompt_toolkit.application import get_app_or_none+ app = get_app_or_none()try:- from prompt_toolkit.application import get_app_or_none- app = get_app_or_none()if app is not None:return app.output.get_size().columns- except Exception:- pass- try:return os.get_terminal_size(sys.__stdout__.fileno()).columnsexcept (AttributeError, OSError, ValueError):return None@@ -549,19 +546,38 @@ def _ansi_drop_cells(line: str, cells: int) -> str:return "".join(out)-def _terminal_reflows() -> bool:- """Whether the terminal re-wraps the rows it shows when its width changes.+# Environment a terminal (or multiplexer) sets for its own children. Checked first: an xterm+# started from a VTE shell inherits VTE_VERSION but sets XTERM_VERSION itself.+_NO_REFLOW_ENV = ("STY", "XTERM_VERSION")+_REFLOW_ENV = ("TMUX", "VTE_VERSION", "KITTY_WINDOW_ID", "WT_SESSION", "KONSOLE_VERSION",+ "ALACRITTY_WINDOW_ID", "WEZTERM_PANE", "GHOSTTY_RESOURCES_DIR")+_REFLOW_TERM_PROGRAMS = ("iTerm.app", "Apple_Terminal", "WezTerm", "vscode", "ghostty", "Tabby", "Hyper")+# TERM is all that survives ssh; these prefixes name terminals that truncate rows in place.+_NO_REFLOW_TERM_PREFIXES = ("linux", "st", "screen", "mosh", "vt", "cons")+_REFLOW_TERM_PREFIXES = ("tmux", "xterm-kitty", "alacritty", "foot", "xterm-ghostty", "wezterm", "contour")- Most do (tmux, VTE, kitty, iTerm2, Terminal.app, WezTerm, Alacritty, Windows Terminal):- a shrink pushes the rows that grew into scrollback. xterm, GNU screen and the Linux- console keep every row in place, truncated. Unknown terminals count as reflowing.- """++def _terminal_reflows() -> bool | None:+ """Whether the terminal re-wraps the rows it shows when its width changes: ``True``+ (tmux, VTE, kitty, iTerm2, Terminal.app, WezTerm, Alacritty, Windows Terminal — a shrink+ pushes the rows that grew into scrollback), ``False`` (xterm, GNU screen, st, mosh, the+ Linux console keep every row in place, truncated) or ``None`` when nothing says (xterm or+ iTerm2 over ssh both look like ``TERM=xterm-256color``)."""env = os.environif env.get("TMUX"):return True- if env.get("STY") or env.get("XTERM_VERSION"):+ if any(env.get(name) for name in _NO_REFLOW_ENV):return False- return env.get("TERM", "") != "linux"+ if any(env.get(name) for name in _REFLOW_ENV) or env.get("TERM_PROGRAM") in _REFLOW_TERM_PROGRAMS:+ return True+ if env.get("LC_TERMINAL") == "iTerm2": # iTerm2 sets it so that ssh forwards it (LC_*)+ return True+ term = env.get("TERM", "").lower()+ if term.startswith(_NO_REFLOW_TERM_PREFIXES):+ return False+ if term.startswith(_REFLOW_TERM_PREFIXES):+ return True+ return Nonedef _output_tail_fitting(lines: list[str], max_rows: int, columns: int, painted: bool = True) -> list[str]:diff --git a/hermes_cli/cli_stream_mixin.py b/hermes_cli/cli_stream_mixin.pyindex f29ffd992cd..3462970309a 100644--- a/hermes_cli/cli_stream_mixin.py+++ b/hermes_cli/cli_stream_mixin.py@@ -563,13 +563,14 @@ class CLIStreamMixin:Most sync slash commands reserve the composer (their completion changes session state);manual compression is safe to draft through (queued input runs against compacted history)."""+ from cli import _cprintprevious_blocks_input = getattr(self, "_command_blocks_input", False)self._command_running = Trueself._command_blocks_input = blocks_inputself._command_status = statusself._invalidate(min_interval=0.0)try:- print(f"⏳ {status}")+ _cprint(f"⏳ {status}")yieldfinally:self._command_running = Falsediff --git a/hermes_cli/cli_terminal_mixin.py b/hermes_cli/cli_terminal_mixin.pyindex 3199228e3c1..9ce353eccaa 100644--- a/hermes_cli/cli_terminal_mixin.py+++ b/hermes_cli/cli_terminal_mixin.py@@ -15,6 +15,10 @@ from hermes_cli.cli_render import _hold_paints, _release_paintsfrom hermes_constants import get_hermes_home+# A replay ``fit`` with no room: nothing is replayed.+_NO_REPLAY = (0, 0, False)++def _is_eio(exc: BaseException) -> bool:return getattr(exc, "errno", None) == errno.EIO@@ -132,7 +136,9 @@ class CLITerminalMixin:fit = self._clear_prompt_toolkit_screen(app, rebuild_scrollback=self._redraw_rebuilds_scrollback())if getattr(self, "_terminal_io_broken", False):return- _replay_output_history(fit)+ # A viewport refill paints at once, before prompt_toolkit's next erase; after CSI 3J+ # the whole history goes through the usual print (the screen was cleared anyway).+ _replay_output_history(fit, None if fit is None else app.renderer.output)self._pet_queue_kitty_frame()self._app_invalidate(app, "force_full_redraw", swallow=True)@@ -187,32 +193,28 @@ class CLITerminalMixin:passself._force_full_redraw()- def _clear_prompt_toolkit_screen(self, app, *, rebuild_scrollback: bool = False, reflowed: bool = False):+ def _clear_prompt_toolkit_screen(self, app, *, rebuild_scrollback: bool = False):"""Clear the terminal and reset prompt_toolkit renderer state.Returns the ``fit`` for the replay that follows (``_transcript_room``). ``None``- means replay the whole history (scrollback wiped by CSI 3J, or the clear failed).- Without 3J the older transcript stays in scrollback, so the replay may only repaint- what the viewport held (#95375); the viewport is erased row by row because CSI 2J- makes scroll-on-clear terminals (tmux, VTE) copy the whole screen into scrollback- first, stacking a duplicate.+ means replay the whole history (scrollback wiped by CSI 3J). Without 3J the older+ transcript stays in scrollback, so the replay may only repaint what the viewport held+ (#95375); the viewport is erased row by row because CSI 2J makes scroll-on-clear+ terminals (tmux, VTE) copy the whole screen into scrollback first, stacking a duplicate.+ A clear that fails replays nothing: the history is already on screen or in scrollback."""if getattr(self, "_terminal_io_broken", False):- return None+ return _NO_REPLAYtry:renderer = app.rendererout = renderer.output+ fit = None if rebuild_scrollback else self._transcript_room(app)out.reset_attributes()- fit = Noneif rebuild_scrollback:out.erase_screen()- try:- out.write_raw("\x1b[3J")- except Exception:- pass+ out.write_raw("\x1b[3J")else:- fit = self._transcript_room(app, reflowed=reflowed)- for row in range(out.get_size().rows):+ for row in range(1, out.get_size().rows + 1): # CUP rows count from 1out.cursor_goto(row, 0)out.erase_end_of_line()out.cursor_goto(0, 0)@@ -226,18 +228,18 @@ class CLITerminalMixin:self._mark_terminal_io_broken("clear_screen")except Exception:pass- return None+ return _NO_REPLAY@staticmethod- def _transcript_room(app, *, reflowed: bool = False):+ def _transcript_room(app):"""``(rows, columns, painted)``: the viewport rows the transcript fills above the- prompt chrome, how to count them — at the current ``columns``, or with ``painted`` at- the width each line was painted at (a terminal that does not reflow keeps them so).+ prompt chrome, and how to count them — at the current ``columns``, or with ``painted``+ at the width each line was painted at, as a terminal that does not reflow keeps them.+ Unless the terminal is known to reflow, count as painted: that replays at least what+ the viewport held, never less.The chrome is the renderer's last paint: prompt_toolkit may draw the app taller than- its preferred height (it fills the rows below the cursor it measured). ``reflowed``:- the terminal just re-wrapped that paint to a narrower width, so each of its rows- now takes as many rows as the new width needs.+ its preferred height (it fills the rows below the cursor it measured)."""from cli import _terminal_reflowsrenderer = app.renderer@@ -245,44 +247,53 @@ class CLITerminalMixin:screen = renderer._last_screenif screen is None:drawn = app.layout.container.preferred_height(size.columns, size.rows).preferred- elif reflowed and size.columns > 0:- # prompt_toolkit writes a row up to its last cell that shows something (trailing- # blanks without a colour are left to erase-to-end-of-line): that is its width.- has_style = renderer._style_string_has_style-- def shows(ch):- if ch.char != " ":- return True- try:- return bool(has_style[ch.style]) if has_style is not None else bool(ch.style)- except Exception:- return bool(ch.style)- drawn = 0- for y in range(screen.height):- last = max((x for x, ch in screen.data_buffer[y].items() if shows(ch)), default=0)- drawn += -(-(last + 1) // size.columns)else:drawn = screen.heightrows = max(0, size.rows - max(renderer._min_available_height, drawn))- return rows, size.columns, not _terminal_reflows()+ return rows, size.columns, _terminal_reflows() is not True++ @staticmethod+ def _aim_erase_at_reflowed_chrome(app, columns: int, reflows) -> int:+ """Point prompt_toolkit's erase at the top of its last paint as a reflowing terminal+ re-wrapped it to ``columns``; return how many transcript rows that erase takes if the+ terminal did not reflow after all (#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.+ """+ renderer = app.renderer+ screen, cursor = renderer._last_screen, renderer._cursor_pos+ if reflows is False or screen is None or columns <= 0:+ return 0+ has_style = renderer._style_string_has_style+ rows = cursor.x // columns+ for 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)+ renderer._cursor_pos = cursor._replace(y=rows)+ return 0 if reflows else rows - cursor.ydef _recover_after_resize(self, app, original_on_resize) -> None:"""Recover a resized classic CLI without desynchronizing cursor state.Never clears scrollback (the startup banner lives there and replay cannot rebuildit) and never resets the renderer before prompt_toolkit's own ``_on_resize``,- which erases via the cached cursor position. The status bar / input rules are- suppressed while the reflow settles: on column shrink the terminal reflows+ which erases the chrome from the cached cursor position. The status bar / input+ rules are suppressed while the reflow settles: on column shrink the terminal reflowsalready-painted rows into scrollback first, so a fresh bar looks duplicated- (#19280, #22976). Suppression cannot erase the already-reflowed OLD bar- (``renderer.erase()`` uses ``_cursor_pos.y`` cached at the OLD width), so on an- OBSERVED column shrink on a reflowing terminal we wipe the viewport (banner-safe)- and replay what it held first. Otherwise the transcript is left as the terminal shows- it and the stale-cursor erase still covers the chrome: a widen re-wraps nothing into- extra rows, and a terminal that does not reflow (xterm) truncates rows in place —- rows the replay could not size for both kinds of terminal, so it would duplicate or- drop them (#95375). With ``display.cli_rebuild_scrollback_on_redraw`` (3J +- whole-history replay) every width change rebuilds.+ (#19280, #22976). On a column shrink a reflowing terminal has re-wrapped the old+ chrome into more rows than that cached cursor reaches, so the erase is aimed at the+ re-wrapped top instead; the transcript above is left exactly as the terminal+ re-wrapped it, never erased and replayed (a replay cannot know which rows the+ terminal kept on screen and which it pushed into scrollback, #95375). When nothing+ says whether the terminal reflows, the rows that aim would take on one that does not+ are replayed: the erase never takes more than the replay puts back.+ With ``display.cli_rebuild_scrollback_on_redraw`` (3J + whole-history replay) every+ width change rebuilds.Same-width SIGWINCH (tmux attach, GNOME tab bar, focus) and the first signalwithout a seeded baseline are left alone — 2J+replay against preserved scrollbackduplicates ``_OUTPUT_HISTORY`` (#65293). tmux-attach's stale previous_screen is@@ -302,18 +313,18 @@ class CLITerminalMixin:new_width = Noneprev_width = getattr(self, "_last_resize_width", None)width_changed = new_width is not None and prev_width is not None and new_width != prev_width- rebuild = self._redraw_rebuilds_scrollback()- if width_changed and (rebuild or (new_width < prev_width and _terminal_reflows())):- try:- fit = self._clear_prompt_toolkit_screen(app, rebuild_scrollback=rebuild, reflowed=True)- _replay_output_history(fit)- except Exception:- pass+ restore_rows = 0+ if width_changed and self._redraw_rebuilds_scrollback():+ _replay_output_history(self._clear_prompt_toolkit_screen(app, rebuild_scrollback=True))+ elif width_changed and new_width < prev_width:+ restore_rows = self._aim_erase_at_reflowed_chrome(app, new_width, _terminal_reflows())if new_width is not None:self._last_resize_width = new_widthif width_changed:self._pet_queue_kitty_frame()original_on_resize()+ if restore_rows:+ _replay_output_history((restore_rows, new_width, True))self._schedule_status_bar_unsuppress(app)finally:# Output held since the signal paints now, against the settled screen.@@ -353,8 +364,13 @@ class CLITerminalMixin:# Fail open: never leave the bar stuck hidden.self._status_bar_suppressed_after_resize = False- def _schedule_resize_recovery(self, app, original_on_resize, delay: float = 0.12) -> None:- """Debounce resize redraws so footer chrome is not stamped into scrollback."""+ def _schedule_resize_recovery(self, app, original_on_resize, delay: float = 0.3) -> None:+ """Debounce resize redraws so footer chrome is not stamped into scrollback.++ The delay outwaits tmux, which re-wraps a pane on every resize but signals it at most+ every 250 ms, so mid-drag the width a recovery reads is stale — also over ssh from a+ tmux pane, where nothing says tmux is there (#95375).+ """try:lock = getattr(self, "_resize_recovery_lock", None)if lock is None:@@ -398,6 +414,15 @@ class CLITerminalMixin:self._last_resize_width = widthoriginal_on_resize = app._on_resizeapp._on_resize = lambda: self._schedule_resize_recovery(app, original_on_resize)+ # A paint before the recovery lands at the new width from the old geometry and strands+ # chrome rows; the recovery repaints everything anyway (#95375).+ original_invalidate = app.invalidate++ def _invalidate_unless_resizing() -> None:+ if not getattr(self, "_resize_recovery_pending", False):+ original_invalidate()++ app.invalidate = _invalidate_unless_resizingdef _try_attach_clipboard_image(self) -> bool:"""Save a clipboard image to ~/.hermes/images/ and attach it; True if attached."""diff --git a/tests/e2e/core/cli_tmux/__init__.py b/tests/e2e/core/cli_tmux/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/e2e/core/cli_tmux/test_resize_scrollback.py b/tests/e2e/core/cli_tmux/test_resize_scrollback.pynew file mode 100644index 00000000000..a4a4cde8acb--- /dev/null+++ b/tests/e2e/core/cli_tmux/test_resize_scrollback.py@@ -0,0 +1,107 @@+"""#95375 on a reflowing terminal: resizing the classic CLI leaves every transcript line in+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 a+two-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+decided by how the terminal re-wraps the rows prompt_toolkit already wrote.+"""++from __future__ import annotations++import os+import re+import shutil+import subprocess+import sys+import time+import uuid+from collections import Counter+from pathlib import Path++import pytest++from tests.fakes.fake_llm_provider import FakeLLMServer, Text, write_hermes_home++pytestmark = pytest.mark.skipif(shutil.which("tmux") is None, reason="needs tmux")++REPO_ROOT = Path(__file__).resolve().parents[4]+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))+++def test_resizes_keep_each_transcript_line_once_in_tmux_scrollback(tmp_path: Path) -> None:+ sock = f"hermes-e2e-{uuid.uuid4().hex[:8]}"+ home = tmp_path / "home"+ (tmp_path / "work").mkdir()++ def tmux(*args: str) -> str:+ return subprocess.run(["tmux", "-L", sock, *args], capture_output=True, text=True, timeout=30).stdout++ def transcript() -> str:+ return tmux("capture-pane", "-p", "-J", "-t", "p", "-S", "-", "-E", "-")++ def wait_for(needle: str, timeout: float = 60.0) -> None:+ end = time.monotonic() + timeout+ while needle not in transcript():+ assert time.monotonic() < end, f"{needle!r} never appeared:\n{transcript()[-3000:]}"+ time.sleep(0.1)++ def resize(cols: int) -> None:+ tmux("resize-window", "-t", "p", "-x", str(cols), "-y", "24")++ def ask(turn: int) -> None:+ tmux("send-keys", "-t", "p", "-l", f"question zq{turn}q please")+ time.sleep(0.5) # typed text + Enter in one write is a paste, not a submit+ tmux("send-keys", "-t", "p", "Enter")++ def reply_done(turn: int) -> None:+ wait_for(f"t{turn}w{WORDS[turn] - 1:03d}")+ time.sleep(2.0)++ script = [Text(_reply(t), chunk_chars=10, delay_per_chunk=0.03) for t in WORDS]+ with FakeLLMServer(script, aux=lambda _r: Text("Scripted session title")) as llm:+ write_hermes_home(home / ".hermes", llm.base_url)+ env = {k: v for k, v in os.environ.items() if not k.startswith(("HERMES_", "TMUX"))}+ env.update(HOME=str(home), HERMES_HOME=str(home / ".hermes"), PYTHONPATH=str(REPO_ROOT),+ TERM="xterm-256color")+ argv = [sys.executable, "-m", "hermes_cli.main", "chat", "--cli", "--yolo"]+ subprocess.run(["tmux", "-L", sock, "-f", os.devnull, "new-session", "-d", "-s", "p", "-x", "120",+ "-y", "24", "-c", str(tmp_path / "work"), *argv], env=env, check=True, timeout=30)+ try:+ tmux("set", "-g", "window-size", "manual")+ wait_for("Welcome to Hermes", timeout=120)+ time.sleep(2.0)++ ask(1)+ reply_done(1)+ ask(2)+ wait_for("t2w040")+ for cols in (110, 95, 80, 70, 90, 85, 100): # a drag: 7 resizes in 0.35 s+ resize(cols)+ time.sleep(0.05)+ reply_done(2)+ resize(80) # idle shrink+ time.sleep(1.5)+ ask(3)+ wait_for("t3w020")+ resize(70) # two-step shrink mid-stream+ time.sleep(0.8)+ resize(60)+ reply_done(3)+ final = transcript()+ finally:+ tmux("kill-server")++ words = Counter(re.findall(r"\bt\dw\d{3}\b", final))+ 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) == [], final+ assert [final.count(f"zq{t}q") for t in WORDS] == [1, 1, 1], final+ assert sum(1 for line in final.split("\n") if line.lstrip().startswith("❯")) == 1, final+ blank_runs = [len(run) for run in re.findall(r"(?:^[ \t]*\n)+", final, flags=re.M)]+ assert max(blank_runs, default=0) <= 2, final # the reply panel's own spacing, nothing morediff --git a/tests/hermes_cli/test_cli_force_redraw.py b/tests/hermes_cli/test_cli_force_redraw.pyindex 259ef10c86d..bb3fe49a0b9 100644--- a/tests/hermes_cli/test_cli_force_redraw.py+++ b/tests/hermes_cli/test_cli_force_redraw.py@@ -24,10 +24,13 @@ def bare_cli():return cli-def _fake_app(*, rows, columns, chrome, painted=None):+def _fake_app(*, rows, columns, chrome, painted=None, cursor_y=0):"""MagicMock app whose output reports a real size and whose layout is ``chrome`` rows tall;- ``painted`` lists the row widths of the renderer's last paint (``None``: nothing yet)."""- from prompt_toolkit.data_structures import Size+ ``painted`` lists the row widths of the renderer's last paint (``None``: nothing yet), its+ cursor on row ``cursor_y``."""+ from collections import defaultdict++ from prompt_toolkit.data_structures import Point, Sizefrom prompt_toolkit.layout.screen import Char, Screenapp = MagicMock()@@ -40,7 +43,8 @@ def _fake_app(*, rows, columns, chrome, painted=None):screen.data_buffer[y][x] = Char("─")screen.height = len(painted)app.renderer._last_screen = screen- app.renderer._style_string_has_style = None+ app.renderer._cursor_pos = Point(x=0, y=cursor_y)+ app.renderer._style_string_has_style = defaultdict(bool)app.renderer._min_available_height = 0app.layout.container.preferred_height.return_value.preferred = chromereturn app@@ -55,54 +59,61 @@ class TestForceFullRedraw:- def test_resize_recovery_clears_viewport_on_width_change(self, bare_cli, monkeypatch):- """A column shrink must wipe the visible viewport and replay what it held.-- On column shrink the terminal reflows the old full-width chrome into- extra rows that prompt_toolkit's stale-cursor erase cannot reach,- leaving a duplicated status bar (#19280/#5474 class). We route through- the same recovery as Ctrl+L: erase the viewport + replay transcript.- It must be banner-safe — CSI 3J (write_raw) must NOT fire. The replay- refills exactly the rows the transcript still has on screen: the terminal- height minus the chrome as last painted (taller than its preferred- height), each of its rows re-wrapped to the new width (#95375).- """- app = _fake_app(rows=30, columns=90, chrome=5, painted=[0, 200, 50, 200, 30, 200, 89])+ @pytest.mark.parametrize("reflows,new_width,cursor_y,replayed", [+ (True, 90, 1 + 3 + 1 + 3, None), # re-wrapped rows: erase from their new top, replay nothing+ (None, 90, 8, (8 - 4, 90, True)), # unknown: same aim, and replay what it takes if rows stayed+ (False, 90, 4, None), # rows kept in place: prompt_toolkit's own erase is right+ (True, 250, 4, None), # a widen re-wraps nothing into more rows+ ])+ def test_resize_erases_the_chrome_where_the_terminal_left_it(+ self, bare_cli, monkeypatch, reflows, new_width, cursor_y, replayed):+ """#95375: the transcript above the chrome is never wiped and replayed — a replay cannot+ know which rows a reflowing terminal kept on screen and which it pushed into scrollback.+ On a shrink prompt_toolkit's erase is aimed at the chrome's top as re-wrapped; when+ nothing says the terminal reflows, the rows that aim takes on one that does not are+ replayed, so the erase never takes more than the replay puts back."""from prompt_toolkit.layout.screen import Char+ app = _fake_app(rows=30, columns=new_width, chrome=5, painted=[0, 200, 50, 200, 30], cursor_y=4)for x in range(200): # blanks without a colour are never written: one row, not threeapp.renderer._last_screen.data_buffer[0][x] = Char(" ")- events = []- fits = []+ events, aimed = [], []app.renderer.output.erase_end_of_line.side_effect = lambda: events.append("erase")+ app.renderer.output.erase_screen.side_effect = lambda: events.append("erase")app.renderer.output.write_raw.side_effect = lambda *_: events.append("scrollback_wipe")- original_on_resize = lambda: events.append("original_resize")bare_cli._status_bar_suppressed_after_resize = Falsebare_cli._last_resize_width = 200- monkeypatch.setattr(bare_cli, "_get_tui_terminal_width", lambda: 90)+ monkeypatch.setattr(bare_cli, "_get_tui_terminal_width", lambda: new_width)monkeypatch.setattr(bare_cli, "_schedule_status_bar_unsuppress", lambda *_: None)- monkeypatch.setattr(- cli_mod, "_replay_output_history", lambda fit=None: (events.append("replay"), fits.append(fit)))- monkeypatch.setattr(cli_mod, "_terminal_reflows", lambda: True)- monkeypatch.setattr(- cli_mod,- "CLI_CONFIG",- {"display": {"cli_rebuild_scrollback_on_redraw": False}},- )+ monkeypatch.setattr(cli_mod, "_replay_output_history", lambda fit=None: events.append(("replay", fit)))+ monkeypatch.setattr(cli_mod, "_terminal_reflows", lambda: reflows)+ monkeypatch.setattr(cli_mod, "CLI_CONFIG", {"display": {"cli_rebuild_scrollback_on_redraw": False}})- bare_cli._recover_after_resize(app, original_on_resize)+ bare_cli._recover_after_resize(+ app, lambda: (events.append("original_resize"), aimed.append(app.renderer._cursor_pos.y)))- # Viewport cleared and transcript replayed BEFORE prompt_toolkit's resize.- assert "erase" in events- assert "replay" in events- assert events.index("erase") < events.index("original_resize")- assert fits == [(30 - (1 + 3 + 1 + 3 + 1 + 3 + 1), 90, False)]- # Banner-safe: scrollback (CSI 3J) must never be wiped on a resize.- assert "scrollback_wipe" not in events- # New width recorded for the next comparison.- assert bare_cli._last_resize_width == 90+ assert events == ["original_resize"] + ([("replay", replayed)] if replayed else [])+ assert aimed == [cursor_y]+ assert bare_cli._last_resize_width == new_widthassert bare_cli._status_bar_suppressed_after_resize is True+ @pytest.mark.parametrize("env,reflows", [+ ({"TMUX": "/tmp/tmux-1/default,1,0", "TERM": "screen-256color"}, True),+ ({"XTERM_VERSION": "XTerm(390)", "VTE_VERSION": "7600"}, False), # xterm started from a VTE shell+ ({"LC_TERMINAL": "iTerm2", "TERM": "xterm-256color"}, True), # iTerm2 over ssh+ ({"TERM": "xterm-256color"}, None), # xterm or iTerm2 over ssh+ ({"TERM": "st-256color"}, False),+ ({"TERM": "screen.xterm-256color"}, False), # GNU screen over ssh+ ({"TERM": "linux"}, False),+ ])+ def test_terminal_reflows_from_what_the_environment_says(self, monkeypatch, env, reflows):+ from hermes_cli import cli_render+ for name in (*cli_render._NO_REFLOW_ENV, *cli_render._REFLOW_ENV, "TERM_PROGRAM", "LC_TERMINAL", "TERM"):+ monkeypatch.delenv(name, raising=False)+ for name, value in env.items():+ monkeypatch.setenv(name, value)+ assert cli_render._terminal_reflows() is reflows+def test_force_redraw_refills_only_the_viewport_without_a_screen_clear(self, bare_cli, monkeypatch):"""#95375: scrollback already holds the older transcript, so a redraw mustneither emit CSI 2J (scroll-on-clear terminals — tmux, VTE — copy the whole@@ -110,7 +121,7 @@ class TestForceFullRedraw:app = _fake_app(rows=30, columns=100, chrome=6)bare_cli._app = appfits = []- monkeypatch.setattr(cli_mod, "_replay_output_history", lambda fit=None: fits.append(fit))+ monkeypatch.setattr(cli_mod, "_replay_output_history", lambda fit=None, output=None: fits.append((fit, output)))monkeypatch.setattr(cli_mod,"CLI_CONFIG",@@ -124,15 +135,18 @@ class TestForceFullRedraw:out = app.renderer.outputout.erase_screen.assert_not_called()out.write_raw.assert_not_called()+ assert [c.args for c in out.cursor_goto.call_args_list][:30] == [(row, 0) for row in range(1, 31)]assert out.erase_end_of_line.call_count == 30- # Rows kept where they were painted count at the width they were painted at.- assert fits == [(24, 100, True)]+ # Rows kept where they were painted count at the width they were painted at, and the+ # refill is painted straight away: prompt_toolkit's own erase would start at the top+ # row, which tmux takes as a clear and copies the blank screen into scrollback.+ assert fits == [((24, 100, True), out)]def test_force_redraw_can_clear_scrollback_when_configured(self, bare_cli, monkeypatch):app = MagicMock()bare_cli._app = appfits = []- monkeypatch.setattr(cli_mod, "_replay_output_history", lambda fit=None: fits.append(fit))+ monkeypatch.setattr(cli_mod, "_replay_output_history", lambda fit=None, output=None: fits.append((fit, output)))monkeypatch.setattr(cli_mod,"CLI_CONFIG",@@ -144,7 +158,7 @@ class TestForceFullRedraw:app.renderer.output.erase_screen.assert_called_once()app.renderer.output.write_raw.assert_called_once_with("\x1b[3J")# Scrollback was wiped, so the whole history is replayed to rebuild it.- assert fits == [None]+ assert fits == [(None, None)]def test_resize_recovery_can_clear_scrollback_when_configured(self, bare_cli, monkeypatch):app = MagicMock()@@ -169,35 +183,6 @@ class TestForceFullRedraw:assert events[:3] == ["erase", "scrollback_wipe", "replay"]assert events.index("scrollback_wipe") < events.index("original_resize")- @pytest.mark.parametrize("prev_width,new_width,env", [- (116, 132, {"TMUX": "/tmp/tmux-1/default,1,0"}), # widen on a reflowing terminal- (132, 100, {"XTERM_VERSION": "XTerm(390)"}), # shrink on one that keeps rows in place- ])- def test_resize_leaves_the_transcript_in_place(self, bare_cli, monkeypatch, prev_width, new_width, env):- """#95375: a widen wraps nothing into extra rows, and a terminal that does not reflow- truncates the chrome in place: prompt_toolkit's own erase still covers it. A replay- would print again rows the terminal still shows, or erase rows it cannot size."""- for name in ("TMUX", "STY", "XTERM_VERSION"):- monkeypatch.delenv(name, raising=False)- for name, value in env.items():- monkeypatch.setenv(name, value)- app = _fake_app(rows=24, columns=new_width, chrome=5, painted=[prev_width] * 5)- events = []- app.renderer.output.erase_end_of_line.side_effect = lambda: events.append("erase")- app.renderer.output.erase_screen.side_effect = lambda: events.append("erase")- original_on_resize = lambda: events.append("original_resize")-- bare_cli._last_resize_width = prev_width- monkeypatch.setattr(bare_cli, "_get_tui_terminal_width", lambda: new_width)- monkeypatch.setattr(bare_cli, "_schedule_status_bar_unsuppress", lambda *_: None)- monkeypatch.setattr(cli_mod, "_replay_output_history", lambda *_: events.append("replay"))- monkeypatch.setattr(cli_mod, "CLI_CONFIG", {"display": {"cli_rebuild_scrollback_on_redraw": False}})-- bare_cli._recover_after_resize(app, original_on_resize)-- assert events == ["original_resize"]- assert bare_cli._last_resize_width == new_width-def test_same_width_sigwinch_is_left_untouched(self, bare_cli, monkeypatch):"""Same-width SIGWINCH (tmux attach, benign focus/tab signals) must notclear the viewport or replay: a 2J without replay erases the visible@@ -388,23 +373,24 @@ class TestFirstSigwinchBaseline:def test_real_width_change_after_baseline_still_replays(self, bare_cli, monkeypatch):- """The #49120 recovery (viewport erase + replay) must still fire on a real change."""- app = _fake_app(rows=30, columns=90, chrome=5)+ """The #49120 recovery must still fire on a real change: here a shrink on a terminal+ that may not reflow, so the rows the aimed erase takes are replayed."""+ app = _fake_app(rows=30, columns=90, chrome=3, painted=[120, 120, 30], cursor_y=2)events = []- app.renderer.output.erase_end_of_line.side_effect = lambda: events.append("erase")original_on_resize = lambda: events.append("original_resize")bare_cli._status_bar_suppressed_after_resize = Falsebare_cli._last_resize_width = 120monkeypatch.setattr(bare_cli, "_get_tui_terminal_width", lambda: 90)monkeypatch.setattr(bare_cli, "_schedule_status_bar_unsuppress", lambda *_: None)+ monkeypatch.setattr(cli_mod, "_terminal_reflows", lambda: None)monkeypatch.setattr(cli_mod, "_replay_output_history", lambda *_: events.append("replay"))bare_cli._recover_after_resize(app, original_on_resize)- assert "erase" in events and "replay" in events+ assert events == ["original_resize", "replay"]assert bare_cli._last_resize_width == 90def test_install_resize_recovery_seeds_width_baseline(self, bare_cli):@@ -470,17 +456,18 @@ class TestReplayFitsViewport:"""#95375: a redraw that keeps scrollback replays only what the viewport holds."""def test_replay_keeps_newest_lines_that_fit_wrapped(self, monkeypatch):+ """A viewport refill paints at once to the given output (no ``run_in_terminal``)."""cli_mod._configure_output_history(True, 200)for i in range(200):cli_mod._record_output_history(f"history line {i}")cli_mod._record_output_history("x" * 150) # soft-wraps to 2 rows at 100 cols- printed = []- monkeypatch.setattr(cli_mod, "_pt_print", lambda x: printed.append(x))- monkeypatch.setattr(cli_mod, "_PT_ANSI", lambda t: t)+ monkeypatch.setattr(cli_mod, "_pt_print", lambda *_: pytest.fail("deferred print"))+ out = MagicMock()- cli_mod._replay_output_history((10, 100))+ cli_mod._replay_output_history((10, 100), output=out)- assert printed[0].split("\n") == [f"history line {i}" for i in range(192, 200)] + ["x" * 150]+ written = "".join(c.args[0] for c in out.write.call_args_list)+ assert written.split("\r\n") == [f"history line {i}" for i in range(192, 200)] + ["x" * 150, ""]assert len(cli_mod._OUTPUT_HISTORY) == 200 # the buffer itself is untoucheddef test_tail_counts_rows_at_the_painted_width_and_keeps_a_tall_lines_bottom(self):diff --git a/tests/hermes_cli/test_cprint_bg_thread.py b/tests/hermes_cli/test_cprint_bg_thread.pyindex 0db76c21872..f5513779e9c 100644--- a/tests/hermes_cli/test_cprint_bg_thread.py+++ b/tests/hermes_cli/test_cprint_bg_thread.py@@ -142,44 +142,12 @@ def test_cprint_swallows_prompt_toolkit_import_error(monkeypatch):-def test_cprint_from_a_worker_is_recorded_when_painted(monkeypatch):- """#95375: a worker's print is queued for the app loop. A resize replay that runs before- it must not find it in the history (it would print it, then the queued print again), and- the row is tagged with the width the terminal wraps it at when it is painted."""- cli._configure_output_history(True, 10)- painted = []- monkeypatch.setattr(cli, "_pt_print", lambda x: painted.append(x))- monkeypatch.setattr(cli, "_PT_ANSI", lambda t: t)- queued = []-- class FakeLoop:- def is_running(self):- return True-- def call_soon_threadsafe(self, cb, *args):- queued.append(cb)-- fake_app = SimpleNamespace(- _is_running=True, loop=FakeLoop(),- output=SimpleNamespace(get_size=lambda: SimpleNamespace(columns=77)))- fake_pt_app = types.ModuleType("prompt_toolkit.application")- fake_pt_app.get_app_or_none = lambda: fake_app- fake_pt_app.run_in_terminal = lambda fn, **kw: fn()- monkeypatch.setitem(sys.modules, "prompt_toolkit.application", fake_pt_app)-- cli._cprint("streamed line") # not on the app loop: no running loop in this thread-- assert painted == [] and list(cli._OUTPUT_HISTORY) == []- queued.pop()()- assert painted == ["streamed line"]- assert list(cli._OUTPUT_HISTORY) == ["streamed line"]- assert cli._OUTPUT_HISTORY[0].width == 77---def test_cprint_waits_for_a_pending_resize_recovery(monkeypatch):- """#95375: between a resize and its recovery a paint would erase the re-wrapped chrome- from a stale cursor, leaving rows of it in the transcript. Held output is neither on- screen nor in the history the recovery replays; it paints, in order, afterwards."""+def test_cprint_is_recorded_when_painted_and_waits_for_a_pending_resize(monkeypatch):+ """#95375: a worker's print is queued for the app loop; a resize replay that runs before it+ must not find it in the history (it would print it, then the queued print again), and the+ row is tagged with the width the terminal wraps it at when painted. Between a resize and+ its recovery a paint would erase the re-wrapped chrome from a stale cursor: held output is+ neither on screen nor in the replayed history, and paints, in order, afterwards."""from hermes_cli import cli_rendercli._configure_output_history(True, 10)@@ -204,14 +172,17 @@ def test_cprint_waits_for_a_pending_resize_recovery(monkeypatch):monkeypatch.setitem(sys.modules, "prompt_toolkit.application", fake_pt_app)monkeypatch.setattr(cli_render, "_HELD_PAINTS", None)- cli._cprint("before")+ cli._cprint("before") # not on the app loop: no running loop in this thread+ assert painted == [] and list(cli._OUTPUT_HISTORY) == []queued.pop()()+ assert painted == ["before"] and list(cli._OUTPUT_HISTORY) == ["before"]+ assert cli._OUTPUT_HISTORY[0].width == 77+cli_render._hold_paints()cli._cprint("during 1")cli._cprint("during 2")for cb in queued:cb()-assert painted == ["before"] and list(cli._OUTPUT_HISTORY) == ["before"]cli_render._release_paints()assert painted == ["before", "during 1", "during 2"]