The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): close resize-drag row loss and modal refill dups (#95375)
teknium1e389aa406151
diff --git a/cli.py b/cli.pyindex 87584f3d115..659f6ec1337 100644--- a/cli.py+++ b/cli.py@@ -91,6 +91,7 @@ from hermes_cli.cli_render import ( # noqa: F401,E402_TRUE_RE,_WINDOWS_PATH_WITH_DOT_SEGMENT_RE,_accent_hex,+ _add_suspect_rows,_append_blank_panel_line,_append_panel_line,_assistant_content_as_text,@@ -106,6 +107,7 @@ from hermes_cli.cli_render import ( # noqa: F401,E402_heal_cooked_mode_drift,_hex_to_ansi,_install_skin_light_mode_hook,+ _line_rows,_luminance_from_hex,_maybe_remap_for_light_mode,_output_history_recording,@@ -124,6 +126,7 @@ from hermes_cli.cli_render import ( # noqa: F401,E402_release_paints,_render_final_assistant_content,_rich_text_from_ansi,+ _set_chrome_floor,_strip_markdown_syntax,_strip_reasoning_tags,_terminal_columns,@@ -651,34 +654,55 @@ def _suspend_output_history():_OUTPUT_HISTORY_SUPPRESSED = old_value+def _output_history_lines() -> list[str]:+ """The recorded output as the lines a replay paints (callable entries render now)."""+ rendered_lines = []+ for entry in tuple(_OUTPUT_HISTORY):+ lines = [entry]+ if callable(entry):+ try:+ lines = entry()+ except Exception:+ continue+ if isinstance(lines, str):+ lines = lines.splitlines()+ rendered_lines.extend(line if isinstance(line, str) else str(line) for line in lines)+ return rendered_lines+++def _output_history_rows(limit: int, columns: int, painted: bool):+ """Rows the whole recorded output fills (counted as ``_output_tail_fitting`` does), or+ ``None`` when that is ``limit`` rows or more."""+ if not _OUTPUT_HISTORY_ENABLED:+ return None+ total = 0+ for line in reversed(_output_history_lines()):+ total += _line_rows(line, (getattr(line, "width", None) if painted else None) or columns)+ if total >= limit:+ return None+ return total++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 height+ ``fit=(rows, columns, painted, top)`` replays only the newest lines whose wrapped heightfits ``rows`` (see ``_output_tail_fitting``) — the older ones are still in scrollback- (#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.+ (#95375) — from screen row ``top`` when known (``_set_chrome_floor``). ``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:return_OUTPUT_HISTORY_REPLAYING = Truetry:- rendered_lines = []- for entry in tuple(_OUTPUT_HISTORY):- lines = [entry]- if callable(entry):- try:- lines = entry()- except Exception:- continue- if isinstance(lines, str):- lines = lines.splitlines()- rendered_lines.extend(line if isinstance(line, str) else str(line) for line in lines)+ rendered_lines = _output_history_lines()+ top = Noneif fit is not None:- rendered_lines = _output_tail_fitting(rendered_lines, *fit)+ rows, columns, painted, top = fit+ rendered_lines = _output_tail_fitting(rendered_lines, rows, columns, painted)if rendered_lines:# One payload: per-line pt prints each force a sync redraw (a waterfall of old output).if output is None:@@ -687,7 +711,13 @@ def _replay_output_history(fit=None, output=None) -> None:from prompt_toolkit.renderer import print_formatted_text as _paint_formatted_textfrom prompt_toolkit.styles import Style_paint_formatted_text(output, _PT_ANSI("\n".join(rendered_lines) + "\n"), Style([]))- width = _painted_columns()+ size = output.get_size()+ if top is not None: # the chrome's top is now this many rows down+ top += sum(_line_rows(line, columns) for line in rendered_lines)+ _set_chrome_floor(max(0, size.rows - top))+ if size.columns != columns:+ _add_suspect_rows(top + 1 - size.rows)+ width = _painted_columns() if fit is None else columnsfor line in rendered_lines: # repainted: they wrap at today's width from now onif isinstance(line, _PaintedLine):line.width = widthdiff --git a/hermes_cli/cli_render.py b/hermes_cli/cli_render.pyindex 93a8e4310c3..94ed50b90a0 100644--- a/hermes_cli/cli_render.py+++ b/hermes_cli/cli_render.py@@ -7,6 +7,7 @@ cli-level names through ``from cli import ...`` at call time so facade monkeypatfrom __future__ import annotationsimport functools+import itertoolsimport osimport reimport shutil@@ -480,6 +481,7 @@ def _coerce_output_history_limit(value) -> int:def _clear_output_history() -> None:_cli()._OUTPUT_HISTORY.clear()+ _set_chrome_floor(None) # the screen is cleared with itdef _output_history_recording() -> bool:@@ -546,56 +548,61 @@ def _ansi_drop_cells(line: str, cells: int) -> str:return "".join(out)-# Environment a terminal (or multiplexer) sets for its own children. A multiplexer is what the-# CLI talks to, whatever terminal it runs in; after it, XTERM_VERSION is checked first: an xterm-# started from a VTE shell inherits VTE_VERSION but sets XTERM_VERSION itself.-_MULTIPLEXER_ENV = ("TMUX", "STY")+# TERM names the terminal the CLI talks to, a multiplexer included (tmux, GNU screen), and is set+# by that terminal for its children — decisive whenever it names one. Everything else is inherited+# from whatever started the shell (TMUX, KITTY_WINDOW_ID or TERM_PROGRAM=vscode leak into an st+# or urxvt launched from there), so it only speaks for a generic TERM such as xterm-256color;+# XTERM_VERSION first there: an xterm started from a VTE shell inherits VTE_VERSION but sets+# XTERM_VERSION itself.+_REFLOW_TERM_PREFIXES = ("tmux", "screen", "xterm-kitty", "alacritty", "foot", "xterm-ghostty", "wezterm",+ "contour", "vte")+# TERM is all that survives ssh; these prefixes name terminals that truncate rows in place.+_NO_REFLOW_TERM_PREFIXES = ("linux", "st", "mosh", "vt", "cons", "rxvt")_NO_REFLOW_ENV = ("XTERM_VERSION",)_REFLOW_ENV = ("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", "mosh", "vt", "cons")-_REFLOW_TERM_PREFIXES = ("tmux", "screen", "xterm-kitty", "alacritty", "foot", "xterm-ghostty", "wezterm",- "contour")def _terminal_reflows() -> bool | None:"""Whether the terminal re-wraps the rows it shows when its width changes: ``True``(tmux, GNU screen, VTE, kitty, iTerm2, Terminal.app, WezTerm, Alacritty, Windows Terminal —- a shrink pushes the rows that grew into scrollback), ``False`` (xterm, 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``)."""+ a shrink pushes the rows that grew into scrollback), ``False`` (xterm, st, urxvt, 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.environ- if any(env.get(name) for name in _MULTIPLEXER_ENV):+ term = env.get("TERM", "").lower()+ if term.startswith(_REFLOW_TERM_PREFIXES): # before "vt": TERM=vte-256colorreturn True+ if term.startswith(_NO_REFLOW_TERM_PREFIXES):+ return Falseif any(env.get(name) for name in _NO_REFLOW_ENV):return Falseif any(env.get(name) for name in _REFLOW_ENV) or env.get("TERM_PROGRAM") in _REFLOW_TERM_PROGRAMS:return Trueif 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 Truereturn None+def _line_rows(line: str, columns: int) -> int:+ """Rows ``line`` fills when the terminal soft-wraps it at ``columns``."""+ from prompt_toolkit.formatted_text import ANSI, fragment_list_width, to_formatted_text+ width = fragment_list_width(to_formatted_text(ANSI(line)))+ return max(1, -(-width // columns)) if columns and columns > 0 else 1++def _output_tail_fitting(lines: list[str], max_rows: int, columns: int, painted: bool = True) -> list[str]:"""Newest ``lines`` filling ``max_rows`` rows, soft-wrapped at ``columns`` — or, with``painted``, at the width each was painted at, as a terminal that does not reflow stillshows it. The oldest one may only partly fit: its bottom rows are kept, the rows abovethem are already in scrollback."""- from prompt_toolkit.formatted_text import ANSI, fragment_list_width, to_formatted_textkept, used = [], 0for line in reversed(lines):if used >= max_rows:breakcols = (getattr(line, "width", None) if painted else None) or columns- width = fragment_list_width(to_formatted_text(ANSI(line)))- height = max(1, -(-width // cols)) if cols > 0 else 1+ height = _line_rows(line, cols)if used + height > max_rows:kept.append(_ansi_drop_cells(line, (height - (max_rows - used)) * cols))break@@ -618,6 +625,49 @@ def _pt_print_ansi(text: str) -> None:_HELD_PAINTS: list | None = None_HELD_PAINTS_LOCK = threading.Lock()+_PAINT_SEQ = itertools.count()+# ``(app, gate)`` while the CLI's app runs: ``gate()`` is True when output must wait for a resize+# recovery (see ``CLITerminalMixin._output_waits_for_resize``).+_PAINT_GATE = None+++def _set_paint_gate(app, gate) -> None:+ global _PAINT_GATE+ _PAINT_GATE = (app, gate) if gate is not None else None+++# Rows from the top of the prompt chrome down to the bottom of the screen, once a refill left+# the chrome's top at a known row (``None``: unknown). prompt_toolkit learns that only through+# CPR, which the CLI leaves off; drawn at least this tall, the chrome keeps reaching the bottom+# row, where ``_transcript_room`` counts the transcript from, also when it shrinks (a narrower+# status bar, a closed modal) — rows left blank below it would be counted as transcript (#95375).+_CHROME_FLOOR = None+++def _set_chrome_floor(rows) -> None:+ global _CHROME_FLOOR+ _CHROME_FLOOR = rows+++def _chrome_floor():+ return _CHROME_FLOOR+++# Rows output scrolled into scrollback while the terminal's width changed under it: a terminal+# that does not reflow may have truncated them first, if it resized before reading all of that+# output. The next refill repaints them too — twice rather than truncated for good (#95375).+_SUSPECT_ROWS = 0+++def _add_suspect_rows(rows: int) -> None:+ global _SUSPECT_ROWS+ _SUSPECT_ROWS += max(0, rows)+++def _take_suspect_rows() -> int:+ global _SUSPECT_ROWS+ rows, _SUSPECT_ROWS = _SUSPECT_ROWS, 0+ return rowsdef _hold_paints() -> None:@@ -625,7 +675,8 @@ def _hold_paints() -> None:A paint erases the prompt chrome from prompt_toolkit's cursor, which is stale once theterminal re-wrapped the chrome to its new width: rows of the old chrome would stay in the- transcript, where the replay cannot account for them (#95375).+ transcript, where the replay cannot account for them (#95375). On a terminal that does not+ reflow, a paint would scroll rows it truncated into scrollback before the refill restores them."""global _HELD_PAINTSwith _HELD_PAINTS_LOCK:@@ -634,20 +685,25 @@ def _hold_paints() -> None:def _release_paints() -> None:- """Paint, in order, what ``_hold_paints`` held."""+ """Paint, in the order they were requested, what ``_hold_paints`` held."""global _HELD_PAINTSwith _HELD_PAINTS_LOCK:held, _HELD_PAINTS = _HELD_PAINTS or [], None- for paint in held:+ for _seq, paint in sorted(held, key=lambda item: item[0]):with suppress(Exception):paint()-def _paint_held(paint) -> bool:+def _paint_held(seq: int, paint, app=None) -> bool:+ """Queue ``paint`` (requested ``seq``-th) when paints are held — or must be, because the+ terminal's width changed under ``app`` and its recovery has not run yet."""+ gate = _PAINT_GATE+ if gate is not None and gate[0] is app and gate[1]():+ _hold_paints()with _HELD_PAINTS_LOCK:if _HELD_PAINTS is None:return False- _HELD_PAINTS.append(paint)+ _HELD_PAINTS.append((seq, paint))return True@@ -655,10 +711,11 @@ def _cprint(text: str):"""Print ANSI text through prompt_toolkit's renderer (patch_stdout swallows raw ANSI).From a background thread while an Application runs, a direct print races the input- redraw and gets buried, so those go through ``run_in_terminal`` via ``call_soon_threadsafe``.+ redraw and gets buried, so those are painted on the app's loop via ``call_soon_threadsafe``."""from cli import _PT_ANSI, _output_history_recording, _pt_print, _pt_print_ansi, _record_output_historyrecording = _output_history_recording()+ seq = next(_PAINT_SEQ)def _painted(paint):# Recorded when painted, not when requested: a redraw replaying the history must@@ -702,21 +759,51 @@ def _cprint(text: str):except Exception:current_loop = Noneif loop is None or (current_loop is loop and loop.is_running()):- if not _paint_held(paint_pt):+ if not _paint_held(seq, paint_pt, app):paint_pt()return+ def _print_now():+ from prompt_toolkit.formatted_text import to_formatted_text+ from prompt_toolkit.renderer import print_formatted_text as _paint_formatted_text+ from prompt_toolkit.styles import Style+ _paint_formatted_text(app.output, to_formatted_text(_PT_ANSI(text)) + [("", "\n")], Style([]))+ paint_now = _painted(_print_now)+def _schedule():- # run_in_terminal() returns an awaitable (pt >= 3.0) that must be scheduled or the- # output is dropped, or None (mocks / older pt) when it already ran synchronously.- # Never fall back to a bare print on error: the sync path already printed.- if _paint_held(paint_pt):+ if not getattr(app, "_is_running", False):+ paint_fallback()+ return+ if _paint_held(seq, _schedule, app):returnwith suppress(Exception):- import inspect as _inspect- coro = run_in_terminal(paint_pt)- if coro is not None and (_inspect.isawaitable(coro) or _inspect.iscoroutine(coro)):- _asyncio.ensure_future(coro)+ pending = getattr(app, "_running_in_terminal_f", None)+ if getattr(app, "_running_in_terminal", False) or (pending is not None and not pending.done()):+ # Another run_in_terminal body owns the terminal: paint after it. Never fall back+ # to a bare print on error: run_in_terminal may already have painted.+ import inspect as _inspect+ coro = run_in_terminal(lambda: _paint_held(seq, _schedule, app) or paint_now())+ if coro is not None and (_inspect.isawaitable(coro) or _inspect.iscoroutine(coro)):+ _asyncio.ensure_future(coro)+ return+ # What run_in_terminal does, but now: its erase and print would run a loop pass+ # later, when a resize may have landed after the check above (#95375).+ renderer = app.renderer+ floor = _CHROME_FLOOR+ if floor is not None: # the chrome, as tall as drawn, moves down by the rows printed+ screen = renderer._last_screen+ floor = max(floor, renderer._min_available_height, screen.height if screen else 0)+ columns = app.output.get_size().columns+ renderer.erase()+ paint_now()+ renderer.reset()+ printed = sum(_line_rows(line, columns) for line in text.split("\n"))+ if app.output.get_size().columns != columns:+ _add_suspect_rows(printed)+ if floor is not None:+ _set_chrome_floor(max(0, floor - printed))+ app._request_absolute_cursor_position()+ app._redraw()try:loop.call_soon_threadsafe(_schedule)diff --git a/hermes_cli/cli_terminal_mixin.py b/hermes_cli/cli_terminal_mixin.pyindex 18bdfb8b70e..83e1b645288 100644--- a/hermes_cli/cli_terminal_mixin.py+++ b/hermes_cli/cli_terminal_mixin.py@@ -11,14 +11,22 @@ import sysimport threadingimport time-from hermes_cli.cli_render import _hold_paints, _release_paints+from hermes_cli.cli_render import (+ _chrome_floor,+ _hold_paints,+ _release_paints,+ _set_chrome_floor,+ _set_paint_gate,+ _take_suspect_rows,+)from hermes_constants import get_hermes_home# A replay ``fit`` with no room: nothing is replayed.-_NO_REPLAY = (0, 0, False)-# Longest a resize drag may hold output paints before a recovery runs anyway (seconds).-_RESIZE_HOLD_MAX = 1.0+_NO_REPLAY = (0, 0, False, None)+# How long a resize drag holds output before its next width change runs a recovery anyway+# (seconds): output freezes this long plus one signal interval at most.+_RESIZE_HOLD_MAX = 0.85def _is_eio(exc: BaseException) -> bool:@@ -110,9 +118,9 @@ class CLITerminalMixin:Bypasses the ``_invalidate`` throttle — a modal the user is waiting on must never bedropped (#41098) — mirroring the direct ``event.app.invalidate()`` the modal key-binding- handlers use. While a width change awaits its recovery the app's invalidate is gated+ handlers use. While a width change awaits its recovery the app's redraw is gated(``_install_resize_recovery``), so the paint waits for that recovery, which repaints the- whole app within ``_RESIZE_HOLD_MAX`` even while a drag keeps signalling.+ whole app about every ``_RESIZE_HOLD_MAX`` seconds even while a drag keeps signalling."""if getattr(self, "_terminal_io_broken", False):return@@ -197,31 +205,53 @@ class CLITerminalMixin:passself._force_full_redraw()- def _clear_prompt_toolkit_screen(self, app, *, rebuild_scrollback: bool = False):+ def _clear_prompt_toolkit_screen(self, app, *, rebuild_scrollback: bool = False, keep_above: 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). 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.+ Returns the ``fit`` for the replay that follows (``_transcript_room`` plus where to+ paint it). ``None`` 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. With ``keep_above`` (a resize) and the whole history on screen,+ only its rows and the chrome are erased — what sits above them (the startup banner) was+ never recorded and a replay could not restore it. Counted as painted, the replay leaves the chrome's top at a known+ row: the chrome is drawn from there to the bottom (``_set_chrome_floor``), where the next+ count assumes it. A clear that fails replays nothing: the history is already on screen or+ in scrollback."""+ from cli import _output_history_rowsif getattr(self, "_terminal_io_broken", False):return _NO_REPLAYtry:renderer = app.rendererout = renderer.output- fit = None if rebuild_scrollback else self._transcript_room(app)+ size = out.get_size()+ fit = Noneout.reset_attributes()if rebuild_scrollback:out.erase_screen()out.write_raw("\x1b[3J")+ out.cursor_goto(0, 0)+ _set_chrome_floor(None)else:- for row in range(1, out.get_size().rows + 1): # CUP rows count from 1- out.cursor_goto(row, 0)- out.erase_end_of_line()- out.cursor_goto(0, 0)+ room, columns, painted = self._transcript_room(app)+ room += _take_suspect_rows()+ history_rows = _output_history_rows(room, columns, painted) if keep_above else None+ if keep_above and history_rows is not None:+ # Rows stay where prompt_toolkit's cursor has them: its oldest row is+ # ``history_rows`` above the chrome's top — row ``room`` once that is known.+ out.write_raw("\r")+ out.cursor_up(renderer._cursor_pos.y + history_rows)+ out.erase_down()+ known = painted and _chrome_floor() is not None+ fit = (room, columns, painted, room - history_rows if known else None)+ else:+ for row in range(1, size.rows + 1): # CUP rows count from 1+ out.cursor_goto(row, 0)+ out.erase_end_of_line()+ out.cursor_goto(0, 0)+ fit = (room, columns, painted, 0 if painted else None)out.flush()# Drop cached screen + cursor state so the next _redraw() starts from a# known (0, 0) origin and re-renders every cell instead of diffing stale.@@ -243,7 +273,8 @@ class CLITerminalMixin: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).+ its preferred height (it fills the rows below the cursor it measured, or down to the+ bottom row once a refill left its top at a known row)."""from cli import _terminal_reflowsrenderer = app.renderer@@ -253,7 +284,7 @@ class CLITerminalMixin:drawn = app.layout.container.preferred_height(size.columns, size.rows).preferredelse:drawn = screen.height- rows = max(0, size.rows - max(renderer._min_available_height, drawn))+ rows = max(0, size.rows - max(renderer._min_available_height, drawn, _chrome_floor() or 0))return rows, size.columns, _terminal_reflows() is not True@staticmethod@@ -293,10 +324,11 @@ class CLITerminalMixin:re-wrapped it, never erased and replayed (a replay cannot know which rows theterminal kept on screen and which it pushed into scrollback, #95375). A terminal thatdoes not reflow truncates every visible row at the new width instead and keeps it in- place, out of scrollback: the viewport is refilled as Ctrl+L does, which cannot- duplicate there. When nothing says whether the terminal reflows it is refilled too —- never losing a row outweighs the rows a reflowing terminal had already pushed into- scrollback and now shows twice.+ place, out of scrollback: the viewport is refilled as Ctrl+L does — also after a drag+ that narrowed and widened back, which truncated rows all the same. When nothing says+ whether the terminal reflows it is refilled too: a reflowing terminal had already+ pushed some of those rows into scrollback and now shows them twice, which beats+ truncating them for good.With ``display.cli_rebuild_scrollback_on_redraw`` (3J + whole-history replay) everywidth change rebuilds.Same-width SIGWINCH (tmux attach, GNOME tab bar, focus) and the first signal@@ -317,24 +349,32 @@ class CLITerminalMixin:except Exception:new_width = Noneprev_width = getattr(self, "_last_resize_width", None)+ narrowest = min(filter(None, (new_width, getattr(self, "_resize_narrowest", None))), default=None)+ self._resize_narrowest = Nonewidth_changed = new_width is not None and prev_width is not None and new_width != prev_width+ narrowed = narrowest is not None and prev_width is not None and narrowest < prev_width+ reflows = _terminal_reflows()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:- if _terminal_reflows():- self._aim_erase_at_reflowed_chrome(app, new_width)- else:- fit = self._clear_prompt_toolkit_screen(app)- _replay_output_history(fit, app.renderer.output)+ elif reflows and width_changed and new_width < prev_width:+ self._aim_erase_at_reflowed_chrome(app, new_width)+ elif not reflows and narrowed:+ fit = self._clear_prompt_toolkit_screen(app, keep_above=True)+ _replay_output_history(fit, app.renderer.output)if new_width is not None:self._last_resize_width = new_widthif width_changed:self._pet_queue_kitty_frame()+ # Its redraw is skipped, and the next recovery scheduled, if the width moved again+ # since it was read above (``_output_waits_for_resize``).original_on_resize()self._schedule_status_bar_unsuppress(app)finally:- # Output held since the signal paints now, against the settled screen.- _release_paints()+ # Output held since the signal paints now, against the settled screen — unless+ # another width change is already waiting for its own recovery.+ if not getattr(self, "_resize_recovery_pending", False):+ self._resize_hold_since = None+ _release_paints()def _restart_debounce_timer(self, attr: str, delay: float, fn) -> None:"""Cancel the daemon Timer stored on ``self.<attr>`` (if any) and start a new one.@@ -376,9 +416,9 @@ class CLITerminalMixin:The delay outwaits tmux, which re-wraps a pane on every resize but signals it at mostevery 250 ms, so mid-drag the width a recovery reads is stale — also over ssh from atmux pane, where nothing says tmux is there (#95375). A width change also holds output- paints and invalidates until its recovery; while a drag keeps signalling, a recovery- still runs at least every ``_RESIZE_HOLD_MAX`` seconds, so output never freezes for- the whole drag. A signal that leaves the width alone holds nothing.+ paints and redraws until its recovery; while a drag keeps signalling, a recovery still+ runs on the first width change after ``_RESIZE_HOLD_MAX`` seconds of holding, so output+ never freezes for the whole drag. A signal that leaves the width alone holds nothing."""try:lock = getattr(self, "_resize_recovery_lock", None)@@ -405,9 +445,19 @@ 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_hold_since = 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:+ self._resize_hold_since = now+ self._resize_narrowest = None_hold_paints()- delay = max(0.0, min(delay, self._resize_hold_since + _RESIZE_HOLD_MAX - now))+ if isinstance(width, int) and width > 0: # truncated rows at the narrowest+ self._resize_narrowest = min(width, getattr(self, "_resize_narrowest", None) or width)+ if now - self._resize_hold_since >= _RESIZE_HOLD_MAX:+ # Right after a width change, not on a timer: the next one of a drag is+ # then furthest away, and landing mid-recovery would truncate rows its+ # replay scrolls into scrollback.+ delay = 0.0self._restart_debounce_timer("_resize_recovery_timer", delay, _timer_fired)except Exception:self._resize_recovery_pending = False@@ -432,16 +482,40 @@ class CLITerminalMixin:breakself._last_resize_width = widthoriginal_on_resize = app._on_resize+ self._resize_original_on_resize = original_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_resizing+ # A render before the recovery lands at the new width from the old geometry and strands+ # chrome rows; the recovery repaints everything anyway (#95375). The final render at+ # exit is never held.+ original_redraw = app._redraw++ def _redraw_unless_resizing(render_as_done: bool = False) -> None:+ if render_as_done or not self._output_waits_for_resize(app):+ floor = _chrome_floor()+ if floor: # what CPR would tell prompt_toolkit: the rows down to the bottom+ renderer = app.renderer+ renderer._min_available_height = max(renderer._min_available_height, floor)+ original_redraw(render_as_done=render_as_done)++ app._redraw = _redraw_unless_resizing+ _set_paint_gate(app, lambda: self._output_waits_for_resize(app))++ def _output_waits_for_resize(self, app) -> bool:+ """Whether output must wait for a resize recovery: one is pending, or the terminal's+ width no longer matches the one the app last settled at — its SIGWINCH is not handled+ yet, and a paint or chrome render now would land in geometry that no recovery accounts+ for: on a terminal that does not reflow it scrolls rows the resize truncated into+ scrollback before any refill (#95375). Noticing that schedules the recovery."""+ if getattr(self, "_resize_recovery_pending", False):+ return True+ try:+ width = app.output.get_size().columns+ except Exception:+ return False+ if width == getattr(self, "_last_resize_width", None):+ return False+ self._schedule_resize_recovery(app, self._resize_original_on_resize)+ return bool(getattr(self, "_resize_recovery_pending", False))def _try_attach_clipboard_image(self) -> bool:"""Save a clipboard image to ~/.hermes/images/ and attach it; True if attached."""diff --git a/tests/hermes_cli/test_cli_force_redraw.py b/tests/hermes_cli/test_cli_force_redraw.pyindex 8a3f6b25168..4da9f6309d4 100644--- a/tests/hermes_cli/test_cli_force_redraw.py+++ b/tests/hermes_cli/test_cli_force_redraw.py@@ -59,14 +59,19 @@ class TestForceFullRedraw:- @pytest.mark.parametrize("reflows,new_width", [(True, 90), (False, 90), (None, 90), (None, 250)])- def test_resize_never_loses_or_reprints_a_row(self, bare_cli, monkeypatch, reflows, new_width):+ @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):"""#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 onlyaimed at the chrome's re-wrapped top. A terminal that does not reflow (or may not)keeps every visible row in place, truncated: the viewport is erased row by row (no- CSI 2J, no 3J) and refilled with what it held, counted at the width it was painted- at, before prompt_toolkit repaints. A widen truncates nothing and is left alone."""+ CSI 2J, no 3J) and refilled from its top row with what it held, counted at the width it+ was painted at, before prompt_toolkit repaints. When the viewport holds the whole+ history, 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."""+ from collections import deque+from prompt_toolkit.layout.screen import Charapp = _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 three@@ -75,15 +80,19 @@ class TestForceFullRedraw:events = []out.erase_end_of_line.side_effect = lambda: events.append("erase_row")out.erase_screen.side_effect = lambda: events.append("clear")- out.write_raw.side_effect = lambda *_: events.append("scrollback_wipe")+ out.erase_down.side_effect = lambda: events.append("erase_down")+ out.cursor_up.side_effect = lambda n: events.append(("up", n))+ out.write_raw.side_effect = lambda raw: events.append(("raw", raw))bare_cli._status_bar_suppressed_after_resize = Falsebare_cli._last_resize_width = 200monkeypatch.setattr(bare_cli, "_get_tui_terminal_width", lambda: new_width)monkeypatch.setattr(bare_cli, "_schedule_status_bar_unsuppress", lambda *_: None)+ monkeypatch.setattr(cli_mod, "_OUTPUT_HISTORY", deque("x" * 180 for _ in range(history_lines)))monkeypatch.setattr(cli_mod, "_replay_output_history", lambda *a: events.append(("replay", *a)))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)bare_cli._recover_after_resize(app, lambda: events.append(("original_resize", app.renderer._cursor_pos.y)))@@ -92,8 +101,11 @@ class TestForceFullRedraw:assert events == [("original_resize", 4)]elif reflows:assert events == [("original_resize", 1 + 3 + 1 + 3)]+ elif history_lines == 2: # 2 lines x 2 rows, right above the chrome+ assert events[:4] == [("raw", "\r"), ("up", 4 + 4), "erase_down", ("replay", (25, 90, True, None), out)]+ assert events[4][0] == "original_resize" and len(events) == 5else:- assert events[:31] == ["erase_row"] * 30 + [("replay", (25, 90, True), out)]+ assert events[:31] == ["erase_row"] * 30 + [("replay", (25, 90, True, 0), out)]assert events[31][0] == "original_resize" and len(events) == 32assert bare_cli._last_resize_width == new_widthassert bare_cli._status_bar_suppressed_after_resize is True@@ -346,6 +358,7 @@ class TestFirstSigwinchBaseline: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")+ app.renderer.output.erase_down.side_effect = lambda: events.append("erase")original_on_resize = lambda: events.append("original_resize")bare_cli._status_bar_suppressed_after_resize = False