Skip to content

The agent that grows with you

fix(cli): size the resize replay for how the terminal re-wraps

teknium138f97640c004
diff --git a/cli.py b/cli.py
index 6049f7b2b74..4e36e22b3c2 100644
--- a/cli.py
+++ b/cli.py
@@ -126,6 +126,7 @@ from hermes_cli.cli_render import ( # noqa: F401,E402
_strip_markdown_syntax,
_strip_reasoning_tags,
_terminal_columns,
+ _terminal_reflows,
_terminal_width_for_streaming,
_tty_wrap,
_wrap_panel_text,
@@ -652,8 +653,9 @@ def _suspend_output_history():
def _replay_output_history(fit=None) -> None:
"""Repaint recent output above the prompt after a full screen clear.
- ``fit=(rows, columns)`` replays only the newest lines whose wrapped height fits
- ``rows`` — the older ones are still in scrollback (#95375).
+ ``fit=(rows, columns, painted)`` replays only the newest lines whose wrapped height
+ fits ``rows`` (see ``_output_tail_fitting``) — the older ones are still in scrollback
+ (#95375).
"""
global _OUTPUT_HISTORY_REPLAYING
if not _OUTPUT_HISTORY_ENABLED or not _OUTPUT_HISTORY:
diff --git a/hermes_cli/cli_render.py b/hermes_cli/cli_render.py
index bd58d41b820..127f9ba885c 100644
--- a/hermes_cli/cli_render.py
+++ b/hermes_cli/cli_render.py
@@ -12,6 +12,7 @@ import re
import shutil
import sys
import textwrap
+import threading
import time
from contextlib import contextmanager, suppress
from hermes_cli.banner import format_banner_version_label
@@ -548,16 +549,32 @@ def _ansi_drop_cells(line: str, cells: int) -> str:
return "".join(out)
-def _output_tail_fitting(lines: list[str], max_rows: int, columns: int) -> list[str]:
- """Newest ``lines`` filling ``max_rows`` rows, each soft-wrapped at the width it was painted
- at (``columns`` when unknown). The oldest one may only partly fit: its bottom rows are
- kept, the rows above them are already in scrollback."""
+def _terminal_reflows() -> bool:
+ """Whether the terminal re-wraps the rows it shows when its width changes.
+
+ 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.
+ """
+ env = os.environ
+ if env.get("TMUX"):
+ return True
+ if env.get("STY") or env.get("XTERM_VERSION"):
+ return False
+ return env.get("TERM", "") != "linux"
+
+
+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 still
+ shows it. The oldest one may only partly fit: its bottom rows are kept, the rows above
+ them are already in scrollback."""
from prompt_toolkit.formatted_text import ANSI, fragment_list_width, to_formatted_text
kept, used = [], 0
for line in reversed(lines):
if used >= max_rows:
break
- cols = getattr(line, "width", None) or columns
+ cols = (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
if used + height > max_rows:
@@ -580,6 +597,41 @@ def _pt_print_ansi(text: str) -> None:
print(text)
+_HELD_PAINTS: list | None = None
+_HELD_PAINTS_LOCK = threading.Lock()
+
+
+def _hold_paints() -> None:
+ """Hold ``_cprint`` paints until ``_release_paints``, while a resize awaits its recovery.
+
+ A paint erases the prompt chrome from prompt_toolkit's cursor, which is stale once the
+ terminal 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).
+ """
+ global _HELD_PAINTS
+ with _HELD_PAINTS_LOCK:
+ if _HELD_PAINTS is None:
+ _HELD_PAINTS = []
+
+
+def _release_paints() -> None:
+ """Paint, in order, what ``_hold_paints`` held."""
+ global _HELD_PAINTS
+ with _HELD_PAINTS_LOCK:
+ held, _HELD_PAINTS = _HELD_PAINTS or [], None
+ for paint in held:
+ with suppress(Exception):
+ paint()
+
+
+def _paint_held(paint) -> bool:
+ with _HELD_PAINTS_LOCK:
+ if _HELD_PAINTS is None:
+ return False
+ _HELD_PAINTS.append(paint)
+ return True
+
+
def _cprint(text: str):
"""Print ANSI text through prompt_toolkit's renderer (patch_stdout swallows raw ANSI).
@@ -612,6 +664,7 @@ def _cprint(text: str):
app = None
if app is None or not getattr(app, "_is_running", False):
+ _release_paints()
paint_fallback()
return
@@ -630,13 +683,16 @@ def _cprint(text: str):
except Exception:
current_loop = None
if loop is None or (current_loop is loop and loop.is_running()):
- paint_pt()
+ if not _paint_held(paint_pt):
+ paint_pt()
return
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):
+ return
with suppress(Exception):
import inspect as _inspect
coro = run_in_terminal(paint_pt)
diff --git a/hermes_cli/cli_terminal_mixin.py b/hermes_cli/cli_terminal_mixin.py
index b5419771f49..577bb57ec6a 100644
--- a/hermes_cli/cli_terminal_mixin.py
+++ b/hermes_cli/cli_terminal_mixin.py
@@ -11,6 +11,7 @@ import sys
import threading
import time
+from hermes_cli.cli_render import _hold_paints, _release_paints
from hermes_constants import get_hermes_home
@@ -186,16 +187,15 @@ class CLITerminalMixin:
pass
self._force_full_redraw()
- def _clear_prompt_toolkit_screen(self, app, *, rebuild_scrollback: bool = False, painted_width=None):
+ def _clear_prompt_toolkit_screen(self, app, *, rebuild_scrollback: bool = False, reflowed: bool = False):
"""Clear the terminal and reset prompt_toolkit renderer state.
- Returns ``(rows, columns)`` for the replay that follows: the viewport rows above the
- prompt chrome and ``painted_width``, the width the transcript on screen was painted
- at (default: the current one). ``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.
+ 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.
"""
if getattr(self, "_terminal_io_broken", False):
return None
@@ -211,7 +211,7 @@ class CLITerminalMixin:
except Exception:
pass
else:
- fit = self._transcript_room(app, painted_width)
+ fit = self._transcript_room(app, reflowed=reflowed)
for row in range(out.get_size().rows):
out.cursor_goto(row, 0)
out.erase_end_of_line()
@@ -229,19 +229,32 @@ class CLITerminalMixin:
return None
@staticmethod
- def _transcript_room(app, columns=None):
- """``(rows, columns)``: viewport rows above the prompt chrome, measured at ``columns``
- (default: the current width).
-
- The chrome height 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).
+ def _transcript_room(app, *, reflowed: bool = False):
+ """``(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).
+
+ 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.
"""
+ from cli import _terminal_reflows
renderer = app.renderer
size = renderer.output.get_size()
screen = renderer._last_screen
- drawn = (screen.height if screen is not None
- else app.layout.container.preferred_height(size.columns, size.rows).preferred)
- return max(0, size.rows - max(renderer._min_available_height, drawn)), columns or size.columns
+ if screen is None:
+ drawn = app.layout.container.preferred_height(size.columns, size.rows).preferred
+ elif reflowed and size.columns > 0:
+ drawn = 0
+ for y in range(screen.height):
+ # Trailing default-style blanks are not written (erase-to-end-of-line instead).
+ cells = [x for x, ch in screen.data_buffer[y].items() if ch.char != " " or ch.style]
+ drawn += max(1, -(-(max(cells) + 1) // size.columns)) if cells else 1
+ else:
+ drawn = screen.height
+ rows = max(0, size.rows - max(renderer._min_available_height, drawn))
+ return rows, size.columns, not _terminal_reflows()
def _recover_after_resize(self, app, original_on_resize) -> None:
"""Recover a resized classic CLI without desynchronizing cursor state.
@@ -253,47 +266,48 @@ class CLITerminalMixin:
already-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 we wipe the viewport (banner-safe) and replay what it held
- first. A widen re-wraps nothing into extra rows, so the stale-cursor erase still
- covers the chrome and the transcript is left as the terminal shows it: a replay there
- duplicates rows on terminals that keep them in place (xterm) and cannot be sized
- right for both those and reflowing ones (#95375). With
- ``display.cli_rebuild_scrollback_on_redraw`` (3J + whole-history replay) every width
- change rebuilds.
+ 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.
Same-width SIGWINCH (tmux attach, GNOME tab bar, focus) and the first signal
without a seeded baseline are left alone — 2J+replay against preserved scrollback
duplicates ``_OUTPUT_HISTORY`` (#65293). tmux-attach's stale previous_screen is
handled by ``_hermes_call_output_screen_diff`` (#83874). Suppression is cleared by
a debounced timer so the bar returns during idle; next-submit stays a fast path.
"""
- # A debounced composer resize can arrive after the alternate screen opens.
- # Its erase/replay belongs to the suspended composer, not the monitor.
- if getattr(getattr(self, '_subagent_monitor', None), 'opening', False):
- return
- from cli import _replay_output_history
- self._status_bar_suppressed_after_resize = True
try:
- new_width = self._get_tui_terminal_width()
- except Exception:
- new_width = None
- prev_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):
+ # A debounced composer resize can arrive after the alternate screen opens.
+ # Its erase/replay belongs to the suspended composer, not the monitor.
+ if getattr(getattr(self, '_subagent_monitor', None), 'opening', False):
+ return
+ from cli import _replay_output_history, _terminal_reflows
+ self._status_bar_suppressed_after_resize = True
try:
- # Rows are counted at the width they were painted at (a terminal that does
- # not reflow still shows them, truncated); the OLD width sizes the rest.
- fit = self._clear_prompt_toolkit_screen(
- app, rebuild_scrollback=rebuild, painted_width=prev_width)
- _replay_output_history(fit)
+ new_width = self._get_tui_terminal_width()
except Exception:
- pass
- if new_width is not None:
- self._last_resize_width = new_width
- if width_changed:
- self._pet_queue_kitty_frame()
- original_on_resize()
- self._schedule_status_bar_unsuppress(app)
+ new_width = None
+ prev_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
+ if new_width is not None:
+ self._last_resize_width = new_width
+ if width_changed:
+ self._pet_queue_kitty_frame()
+ original_on_resize()
+ self._schedule_status_bar_unsuppress(app)
+ finally:
+ # Output held since the signal paints now, against the settled screen.
+ _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.
@@ -348,6 +362,7 @@ class CLITerminalMixin:
_run_on_app_loop(app, _run_recovery)
with lock:
self._resize_recovery_pending = True
+ _hold_paints()
self._restart_debounce_timer("_resize_recovery_timer", delay, _timer_fired)
except Exception:
self._resize_recovery_pending = False
diff --git a/tests/hermes_cli/test_cli_force_redraw.py b/tests/hermes_cli/test_cli_force_redraw.py
index 17b11e79557..5784b10f6ee 100644
--- a/tests/hermes_cli/test_cli_force_redraw.py
+++ b/tests/hermes_cli/test_cli_force_redraw.py
@@ -26,14 +26,20 @@ def bare_cli():
def _fake_app(*, rows, columns, chrome, painted=None):
"""MagicMock app whose output reports a real size and whose layout is ``chrome`` rows tall;
- ``painted`` is the height of the renderer's last paint (``None``: nothing painted yet)."""
- from types import SimpleNamespace
-
+ ``painted`` lists the row widths of the renderer's last paint (``None``: nothing yet)."""
from prompt_toolkit.data_structures import Size
+ from prompt_toolkit.layout.screen import Char, Screen
app = MagicMock()
app.renderer.output.get_size.return_value = Size(rows=rows, columns=columns)
- app.renderer._last_screen = None if painted is None else SimpleNamespace(height=painted)
+ screen = None
+ if painted is not None:
+ screen = Screen()
+ for y, width in enumerate(painted):
+ for x in range(width):
+ screen.data_buffer[y][x] = Char("─")
+ screen.height = len(painted)
+ app.renderer._last_screen = screen
app.renderer._min_available_height = 0
app.layout.container.preferred_height.return_value.preferred = chrome
return app
@@ -56,11 +62,11 @@ class TestForceFullRedraw:
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 had on screen: the terminal
- height minus the chrome as last painted (here taller than its preferred
- height), at the width those rows were painted at (#95375).
+ 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=7)
+ app = _fake_app(rows=30, columns=90, chrome=5, painted=[0, 200, 50, 200, 30, 200, 89])
events = []
fits = []
app.renderer.output.erase_end_of_line.side_effect = lambda: events.append("erase")
@@ -73,6 +79,7 @@ class TestForceFullRedraw:
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",
@@ -85,7 +92,7 @@ class TestForceFullRedraw:
assert "erase" in events
assert "replay" in events
assert events.index("erase") < events.index("original_resize")
- assert fits == [(30 - 7, 200)]
+ 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.
@@ -106,13 +113,16 @@ class TestForceFullRedraw:
{"display": {"cli_rebuild_scrollback_on_redraw": False}},
)
+ monkeypatch.setattr(cli_mod, "_terminal_reflows", lambda: False)
+
bare_cli._force_full_redraw()
out = app.renderer.output
out.erase_screen.assert_not_called()
out.write_raw.assert_not_called()
assert out.erase_end_of_line.call_count == 30
- assert fits == [(24, 100)]
+ # Rows kept where they were painted count at the width they were painted at.
+ assert fits == [(24, 100, True)]
def test_force_redraw_can_clear_scrollback_when_configured(self, bare_cli, monkeypatch):
app = MagicMock()
@@ -155,17 +165,26 @@ class TestForceFullRedraw:
assert events[:3] == ["erase", "scrollback_wipe", "replay"]
assert events.index("scrollback_wipe") < events.index("original_resize")
- def test_widen_leaves_the_transcript_in_place(self, bare_cli, monkeypatch):
- """#95375: a widen wraps nothing into extra rows, so prompt_toolkit's own erase still
- covers the chrome. A replay would print again rows the terminal still shows."""
- app = _fake_app(rows=24, columns=132, chrome=5, painted=5)
+ @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 = 116
- monkeypatch.setattr(bare_cli, "_get_tui_terminal_width", lambda: 132)
+ 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}})
@@ -173,7 +192,7 @@ class TestForceFullRedraw:
bare_cli._recover_after_resize(app, original_on_resize)
assert events == ["original_resize"]
- assert bare_cli._last_resize_width == 132
+ 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 not
diff --git a/tests/hermes_cli/test_cprint_bg_thread.py b/tests/hermes_cli/test_cprint_bg_thread.py
index d521c07e3ff..0db76c21872 100644
--- a/tests/hermes_cli/test_cprint_bg_thread.py
+++ b/tests/hermes_cli/test_cprint_bg_thread.py
@@ -176,6 +176,48 @@ def test_cprint_from_a_worker_is_recorded_when_painted(monkeypatch):
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."""
+ from hermes_cli import cli_render
+
+ 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)
+ monkeypatch.setattr(cli_render, "_HELD_PAINTS", None)
+
+ cli._cprint("before")
+ queued.pop()()
+ 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"]
+ assert list(cli._OUTPUT_HISTORY) == ["before", "during 1", "during 2"]
+
+
def test_replay_output_history_rerenders_callable_entries(monkeypatch):
cli._configure_output_history(True, 10)
widths_seen = []