cli_terminal_mixin.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. """Terminal repaint/resize recovery, input-mode healing, and clipboard helpers for the interactive
  2. CLI. Mixin on ``HermesCLI``; cli.py symbols are imported lazily inside methods (import cycle)."""
  3. from __future__ import annotations
  4. import base64
  5. import errno
  6. import os
  7. import shutil
  8. import sys
  9. import threading
  10. import time
  11. from agent.i18n import t
  12. from hermes_cli.cli_render import (
  13. _chrome_floor,
  14. _hold_paints,
  15. _output_history_rows,
  16. _release_paints,
  17. _set_chrome_floor,
  18. _set_paint_gate,
  19. _take_suspect_rows,
  20. )
  21. from hermes_constants import get_hermes_home
  22. # A replay ``fit`` with no room: nothing is replayed.
  23. _NO_REPLAY = (0, 0, False, None)
  24. # How long a resize drag holds output before its next width change runs a recovery anyway,
  25. # that long after the change (seconds): output freezes about their sum plus one signal interval.
  26. _RESIZE_HOLD_MAX = 0.7
  27. _RESIZE_SETTLE = 0.03
  28. # How long before a width change was first seen a chrome paint may still have reached the
  29. # terminal after it narrowed (seconds; a paint the width moved under is always suspect): the
  30. # signal lands a few ms after the multiplexer re-wraps, and it reads our output promptly — in
  31. # tmux, paints that ended up to 4 ms before the signal were re-wrapped, never clipped (#95375).
  32. _RESIZE_PAINT_MARGIN = 0.01
  33. def _is_eio(exc: BaseException) -> bool:
  34. return getattr(exc, "errno", None) == errno.EIO
  35. def _run_on_app_loop(app, fn) -> None:
  36. """Run *fn* on the app's asyncio loop when one exists, else inline (fail-open)."""
  37. try:
  38. loop = getattr(app, "loop", None)
  39. except Exception:
  40. loop = None
  41. if loop is not None:
  42. try:
  43. loop.call_soon_threadsafe(fn)
  44. return
  45. except Exception:
  46. pass
  47. fn()
  48. def _tmux_passthrough(seq: str) -> str:
  49. """*seq* in tmux's DCS passthrough wrapper: tmux forwards it to the outer terminal only with
  50. ``allow-passthrough on`` and swallows it otherwise."""
  51. return "\x1bPtmux;" + seq.replace("\x1b", "\x1b\x1b") + "\x1b\\"
  52. def _write_terminal_sequence(app, seq: str) -> None:
  53. """Write a raw escape *seq* via the app output (write_raw > write) or stdout."""
  54. output = getattr(app, "output", None) if app else None
  55. if output and hasattr(output, "write_raw"):
  56. output.write_raw(seq)
  57. output.flush()
  58. elif output and hasattr(output, "write"):
  59. output.write(seq)
  60. output.flush()
  61. else:
  62. sys.stdout.write(seq)
  63. sys.stdout.flush()
  64. class CLITerminalMixin:
  65. """Terminal repaint/resize recovery, input-mode healing, and clipboard helpers for the interactive CLI"""
  66. def _mark_terminal_io_broken(self, reason: str = "") -> None:
  67. """Stop UI paints after the PTY/stdout becomes unusable (#81521)."""
  68. from cli import logger
  69. if getattr(self, "_terminal_io_broken", False):
  70. return
  71. self._terminal_io_broken = True
  72. try:
  73. self._pet_stop_anim()
  74. except Exception:
  75. pass
  76. logger.warning(
  77. "Terminal I/O broken%s — freezing UI paints to avoid redraw storm (#81521)",
  78. f" ({reason})" if reason else "")
  79. def _app_invalidate(self, app, where: str, *, swallow: bool) -> None:
  80. """``app.invalidate()``: EIO freezes paints, other OSErrors re-raise, and any
  81. other exception re-raises unless *swallow*."""
  82. try:
  83. app.invalidate()
  84. except OSError as exc:
  85. if _is_eio(exc):
  86. self._mark_terminal_io_broken(where)
  87. return
  88. raise
  89. except Exception:
  90. if not swallow:
  91. raise
  92. def _invalidate(self, min_interval: float = 0.25) -> None:
  93. """Throttled UI repaint for high-frequency background updates (spinner frames,
  94. streaming flushes): the throttle prevents blinking on slow/SSH links and the
  95. resize-recovery guard keeps footer chrome out of scrollback mid-SIGWINCH.
  96. NOT for user-blocking modals (approval / clarify / sudo) — use ``_paint_now``: a
  97. throttled or resize-gated entry paint is silently dropped, so the prompt never
  98. renders and times out unseen (#41098).
  99. """
  100. if getattr(self, "_terminal_io_broken", False) or getattr(self, "_resize_recovery_pending", False):
  101. return
  102. now = time.monotonic()
  103. # None sentinel, not 0.0 — monotonic's epoch is arbitrary (boot on Linux), so on
  104. # a fresh VM ``now`` can be < min_interval and a 0.0 sentinel would swallow the
  105. # first repaint (same class as _schedule_focus_regain_redraw below).
  106. last = getattr(self, "_last_invalidate", None)
  107. if hasattr(self, "_app") and self._app and (last is None or now - last >= min_interval):
  108. self._last_invalidate = now
  109. self._app_invalidate(self._app, "invalidate", swallow=False)
  110. def _paint_now(self) -> None:
  111. """Unthrottled repaint for user-blocking modal prompts.
  112. Bypasses the ``_invalidate`` throttle — a modal the user is waiting on must never be
  113. dropped (#41098) — mirroring the direct ``event.app.invalidate()`` the modal key-binding
  114. handlers use. While a width change awaits its recovery the app's redraw is gated
  115. (``_install_resize_recovery``), so the paint waits for that recovery, which repaints the
  116. whole app about every ``_RESIZE_HOLD_MAX`` seconds even while a drag keeps signalling.
  117. """
  118. if getattr(self, "_terminal_io_broken", False):
  119. return
  120. monitor = getattr(self, "_subagent_monitor", None)
  121. if monitor is not None:
  122. monitor.invalidate()
  123. app = getattr(self, "_app", None)
  124. if app is not None:
  125. self._app_invalidate(app, "paint_now", swallow=True)
  126. def _force_full_redraw(self) -> None:
  127. """Force a clean full-screen repaint of the prompt_toolkit UI (Ctrl+L, ``/redraw``).
  128. Recovers from terminal buffer drift caused by external redraws we can't detect
  129. (cmux/tmux tab switches, ``clear`` from a subshell, SSH window restores): they
  130. repaint without SIGWINCH, so prompt_toolkit's tracked ``_cursor_pos`` is stale
  131. and the next incremental redraw stacks on old content (ghost status bars).
  132. """
  133. from cli import _replay_output_history
  134. if getattr(self, "_terminal_io_broken", False):
  135. return
  136. app = getattr(self, "_app", None)
  137. if not app:
  138. return
  139. fit = self._clear_prompt_toolkit_screen(app, rebuild_scrollback=self._redraw_rebuilds_scrollback())
  140. if getattr(self, "_terminal_io_broken", False):
  141. return
  142. # A viewport refill paints at once, before prompt_toolkit's next erase; after CSI 3J
  143. # the whole history goes through the usual print (the screen was cleared anyway).
  144. _replay_output_history(fit, None if fit is None else app.renderer.output)
  145. self._pet_queue_kitty_frame()
  146. self._app_invalidate(app, "force_full_redraw", swallow=True)
  147. def _schedule_focus_regain_redraw(self, min_interval: float = 1.0) -> None:
  148. """Repaint after a terminal focus-in report (``CSI I``), at most once per
  149. ``min_interval`` (rapid Alt+Tab / pane-hop bursts). Emulators with focus tracking
  150. (DECSET 1004) may coalesce hidden-tab output, so on regain the incremental diff
  151. stacks on stale content (#60920, #25337); terminals without it never emit ``CSI I``.
  152. """
  153. now = time.monotonic()
  154. # Sentinel is None, not 0.0: time.monotonic() counts from an arbitrary epoch
  155. # (boot on Linux). On a fresh VM (CI runners, containers) ``now`` can be smaller
  156. # than ``min_interval``, and ``now - 0.0 < min_interval`` would suppress the
  157. # FIRST redraw ever requested (CI run 32494557030: uptime < 60s made the
  158. # min_interval=60 rate-limit test fail both attempts).
  159. last = getattr(self, "_last_focus_regain_redraw", None)
  160. if last is not None and now - last < min_interval:
  161. return
  162. self._last_focus_regain_redraw = now
  163. self._force_full_redraw()
  164. @staticmethod
  165. def _redraw_rebuilds_scrollback() -> bool:
  166. """Whether redraw/resize recovery should also clear scrollback (CSI 3J).
  167. Some terminal/tmux stacks move prompt_toolkit's bottom chrome into scrollback on
  168. maximize/restore; CSI 2J cannot remove those rows, so affected users opt in to 3J
  169. followed by the bounded output-history replay.
  170. """
  171. from cli import CLI_CONFIG
  172. display_config = CLI_CONFIG.get("display") if isinstance(CLI_CONFIG, dict) else {}
  173. raw = (display_config.get("cli_rebuild_scrollback_on_redraw", False)
  174. if isinstance(display_config, dict) else False)
  175. if isinstance(raw, str):
  176. return raw.strip().lower() in {"1", "true", "yes", "on", "always"}
  177. return bool(raw)
  178. def _recover_terminal_after_interrupt(self) -> None:
  179. """Recover the terminal after an interrupted agent turn (#33271): an in-flight
  180. ``CSI 6n`` reply arriving after the input parser tore down leaks as literal text
  181. and can stall the VT100 parser mid-escape. Drain stdin, then full redraw; each step
  182. self-guards. A dead PTY (EIO) skips the redraw (#81521 redraw storm). Never clear
  183. output history here — the interruption marker is printed under
  184. ``_suspend_output_history``, so replay already excludes it (#60920).
  185. """
  186. if getattr(self, "_terminal_io_broken", False):
  187. return
  188. try:
  189. from hermes_cli.curses_ui import flush_stdin
  190. flush_stdin()
  191. except Exception:
  192. pass
  193. self._force_full_redraw()
  194. def _clear_prompt_toolkit_screen(self, app, *, rebuild_scrollback: bool = False, keep_above: bool = False):
  195. """Clear the terminal and reset prompt_toolkit renderer state.
  196. Returns the ``fit`` for the replay that follows (``_transcript_room`` plus where to
  197. paint it). ``None`` means replay the whole history (scrollback wiped by CSI 3J). Without
  198. 3J the older transcript stays in scrollback, so the replay may only repaint what the
  199. viewport held (#95375); the viewport is erased row by row because CSI 2J makes
  200. scroll-on-clear terminals (tmux, VTE) copy the whole screen into scrollback first,
  201. stacking a duplicate. With ``keep_above`` (a resize), on a terminal that keeps rows in
  202. place, and the whole history on screen, only its rows and the chrome are erased — what
  203. sits above them (the startup banner) was never recorded and a replay could not restore
  204. it. Counted as painted, the replay leaves the chrome's top at a known row: the chrome is
  205. drawn from there to the bottom (``_set_chrome_floor``), where the next count assumes it.
  206. A clear that fails replays nothing: the history is already on screen or in scrollback.
  207. """
  208. from cli import _terminal_reflows
  209. if getattr(self, "_terminal_io_broken", False):
  210. return _NO_REPLAY
  211. try:
  212. renderer = app.renderer
  213. out = renderer.output
  214. size = out.get_size()
  215. fit = None
  216. out.reset_attributes()
  217. if rebuild_scrollback:
  218. out.erase_screen()
  219. out.write_raw("\x1b[3J")
  220. out.cursor_goto(0, 0)
  221. _set_chrome_floor(None)
  222. else:
  223. room, columns, painted = self._transcript_room(app)
  224. room += _take_suspect_rows()
  225. # Only where rows stay in place: the erase below counts up from the cursor.
  226. keep_above = keep_above and _terminal_reflows() is False
  227. history_rows = _output_history_rows(room, columns, painted) if keep_above else None
  228. if keep_above and history_rows is not None:
  229. # Rows stay where prompt_toolkit's cursor has them: its oldest row is
  230. # ``history_rows`` above the chrome's top — row ``room`` once that is known.
  231. out.write_raw("\r")
  232. out.cursor_up(renderer._cursor_pos.y + history_rows)
  233. out.erase_down()
  234. known = painted and _chrome_floor() is not None
  235. fit = (room, columns, painted, room - history_rows if known else None)
  236. else:
  237. for row in range(1, size.rows + 1): # CUP rows count from 1
  238. out.cursor_goto(row, 0)
  239. out.erase_end_of_line()
  240. out.cursor_goto(0, 0)
  241. fit = (room, columns, painted, 0 if painted else None)
  242. out.flush()
  243. # Drop cached screen + cursor state so the next _redraw() starts from a
  244. # known (0, 0) origin and re-renders every cell instead of diffing stale.
  245. renderer.reset(leave_alternate_screen=False)
  246. return fit
  247. except OSError as exc:
  248. if _is_eio(exc):
  249. self._mark_terminal_io_broken("clear_screen")
  250. except Exception:
  251. pass
  252. return _NO_REPLAY
  253. @staticmethod
  254. def _transcript_room(app):
  255. """``(rows, columns, painted)``: the viewport rows the transcript fills above the
  256. prompt chrome, and how to count them — at the current ``columns``, or with ``painted``
  257. at the width each line was painted at, as a terminal that does not reflow keeps them.
  258. Unless the terminal is known to reflow, count as painted: that replays at least what
  259. the viewport held, never less.
  260. The chrome is the renderer's last paint: prompt_toolkit may draw the app taller than
  261. its preferred height (it fills the rows below the cursor it measured, or down to the
  262. bottom row once a refill left its top at a known row).
  263. """
  264. from cli import _terminal_reflows
  265. renderer = app.renderer
  266. size = renderer.output.get_size()
  267. screen = renderer._last_screen
  268. if screen is None:
  269. drawn = app.layout.container.preferred_height(size.columns, size.rows).preferred
  270. else:
  271. drawn = screen.height
  272. rows = max(0, size.rows - max(renderer._min_available_height, drawn, _chrome_floor() or 0))
  273. return rows, size.columns, _terminal_reflows() is not True
  274. @staticmethod
  275. def _painted_row_widths(renderer) -> list[int]:
  276. """Cells each row of the renderer's last paint reaches: prompt_toolkit writes a row up to
  277. its last cell that shows something (the blanks after it are erase-to-end-of-line)."""
  278. screen = renderer._last_screen
  279. if screen is None:
  280. return []
  281. has_style = renderer._style_string_has_style
  282. return [1 + max((x for x, ch in screen.data_buffer[y].items() if ch.char != " " or has_style[ch.style]),
  283. default=0) for y in range(screen.height)]
  284. def _note_chrome_paint(self, app, full: bool) -> None:
  285. """Remember when each row of the chrome prompt_toolkit just drew was written, and how
  286. wide — ``full``: the whole chrome was written anew (for ``_aim_erase_at_reflowed_chrome``).
  287. A row only changes height when its width does, so only those changes are kept."""
  288. renderer = app.renderer
  289. size = renderer._last_size
  290. try: # the width moved while it rendered: the terminal may have got the rows clipped
  291. suspect = size is None or app.output.get_size().columns != size.columns
  292. except Exception:
  293. suspect = True
  294. now = time.monotonic()
  295. previous = [] if full else getattr(self, "_chrome_paints", [])
  296. paints = []
  297. for y, width in enumerate(self._painted_row_widths(renderer)):
  298. history = previous[y] if y < len(previous) else []
  299. if not history or history[-1][1] != width:
  300. history = [*history[-3:], (now, width, suspect)]
  301. paints.append(history)
  302. self._chrome_paints = paints
  303. self._chrome_paints_screen = renderer._last_screen
  304. def _aim_erase_at_reflowed_chrome(self, app, columns: int) -> None:
  305. """Point prompt_toolkit's erase at the top of its last paint as a reflowing terminal
  306. re-wrapped it to ``columns`` (#95375).
  307. ``renderer.erase()`` moves up ``_cursor_pos.y`` rows — right where rows stay in place,
  308. short of the top on a reflowing terminal, whose re-wrapped chrome rows would stay
  309. above the new paint. A row's width, re-wrapped, is its height now — if the terminal got
  310. the row before it narrowed. prompt_toolkit writes rows with autowrap off, so one it got
  311. after narrowing (painted just before the width change was seen, the signal still on its
  312. way) was clipped to one row instead, and counting it as re-wrapped would erase
  313. transcript rows above the chrome. Rows painted within ``_RESIZE_PAINT_MARGIN`` of the
  314. width change, or unrecorded, count as one row: a stale chrome row left above the new
  315. paint is benign, an erased transcript row is lost for good.
  316. """
  317. renderer = app.renderer
  318. screen, cursor = renderer._last_screen, renderer._cursor_pos
  319. if screen is None or columns <= 0:
  320. return
  321. paints = getattr(self, "_chrome_paints", []) if getattr(self, "_chrome_paints_screen", None) is screen else []
  322. cutoff = (getattr(self, "_resize_seen_at", None) or time.monotonic()) - _RESIZE_PAINT_MARGIN
  323. rows = cursor.x // columns
  324. for y in range(cursor.y):
  325. history = paints[y] if y < len(paints) else []
  326. settled = [i for i, (at, _width, suspect) in enumerate(history) if at < cutoff and not suspect]
  327. if settled: # re-wrapped as it was then, or as a later, narrower paint reached it
  328. rows += -(-min(width for _at, width, _suspect in history[settled[-1]:]) // columns)
  329. else:
  330. rows += 1
  331. renderer._cursor_pos = cursor._replace(y=rows)
  332. def _recover_after_resize(self, app, original_on_resize) -> None:
  333. """Recover a resized classic CLI without desynchronizing cursor state.
  334. Never clears scrollback (the startup banner lives there and replay cannot rebuild
  335. it) and never resets the renderer before prompt_toolkit's own ``_on_resize``,
  336. which erases the chrome from the cached cursor position. The status bar / input
  337. rules are suppressed while the reflow settles: on column shrink the terminal reflows
  338. already-painted rows into scrollback first, so a fresh bar looks duplicated
  339. (#19280, #22976). On a column shrink a reflowing terminal has re-wrapped the old
  340. chrome into more rows than that cached cursor reaches, so the erase is aimed at the
  341. re-wrapped top instead; the transcript above is left exactly as the terminal
  342. re-wrapped it, never erased and replayed (a replay cannot know which rows the
  343. terminal kept on screen and which it pushed into scrollback, #95375). A terminal that
  344. does not reflow truncates every visible row at the new width instead and keeps it in
  345. place, out of scrollback: the viewport is refilled as Ctrl+L does — also after a drag
  346. that narrowed and widened back, which truncated rows all the same. When nothing says
  347. whether the terminal reflows it is refilled too: a reflowing terminal had already
  348. pushed some of those rows into scrollback and now shows them twice, which beats
  349. truncating them for good.
  350. With ``display.cli_rebuild_scrollback_on_redraw`` (3J + whole-history replay) every
  351. width change rebuilds.
  352. Same-width SIGWINCH (tmux attach, GNOME tab bar, focus) and the first signal
  353. without a seeded baseline are left alone — 2J+replay against preserved scrollback
  354. duplicates ``_OUTPUT_HISTORY`` (#65293). tmux-attach's stale previous_screen is
  355. handled by ``_hermes_call_output_screen_diff`` (#83874). Suppression is cleared by
  356. a debounced timer so the bar returns during idle; next-submit stays a fast path.
  357. """
  358. try:
  359. # A debounced composer resize can arrive after the alternate screen opens.
  360. # Its erase/replay belongs to the suspended composer, not the monitor.
  361. if getattr(getattr(self, '_subagent_monitor', None), 'opening', False):
  362. return
  363. from cli import _replay_output_history, _terminal_reflows
  364. self._status_bar_suppressed_after_resize = True
  365. try:
  366. new_width = self._get_tui_terminal_width()
  367. except Exception:
  368. new_width = None
  369. prev_width = getattr(self, "_last_resize_width", None)
  370. narrowest = min(filter(None, (new_width, getattr(self, "_resize_narrowest", None))), default=None)
  371. self._resize_narrowest = None
  372. width_changed = new_width is not None and prev_width is not None and new_width != prev_width
  373. narrowed = narrowest is not None and prev_width is not None and narrowest < prev_width
  374. reflows = _terminal_reflows()
  375. if width_changed and self._redraw_rebuilds_scrollback():
  376. _replay_output_history(self._clear_prompt_toolkit_screen(app, rebuild_scrollback=True))
  377. elif reflows and width_changed and new_width < prev_width:
  378. self._aim_erase_at_reflowed_chrome(app, new_width)
  379. elif not reflows and narrowed:
  380. fit = self._clear_prompt_toolkit_screen(app, keep_above=True)
  381. _replay_output_history(fit, app.renderer.output)
  382. if new_width is not None:
  383. self._last_resize_width = new_width
  384. if width_changed:
  385. self._pet_queue_kitty_frame()
  386. # Its redraw is skipped, and the next recovery scheduled, if the width moved again
  387. # since it was read above (``_output_waits_for_resize``).
  388. original_on_resize()
  389. self._schedule_status_bar_unsuppress(app)
  390. finally:
  391. # Output held since the signal paints now, against the settled screen — unless
  392. # another width change is already waiting for its own recovery.
  393. if not getattr(self, "_resize_recovery_pending", False):
  394. self._resize_hold_since = None
  395. _release_paints()
  396. def _restart_debounce_timer(self, attr: str, delay: float, fn) -> None:
  397. """Cancel the daemon Timer stored on ``self.<attr>`` (if any) and start a new one.
  398. ``fn`` receives the new Timer so it can detect being superseded."""
  399. old_timer = getattr(self, attr, None)
  400. if old_timer is not None:
  401. try:
  402. old_timer.cancel()
  403. except Exception:
  404. pass
  405. timer = threading.Timer(delay, lambda: fn(timer))
  406. timer.daemon = True
  407. setattr(self, attr, timer)
  408. timer.start()
  409. def _schedule_status_bar_unsuppress(self, app, delay: float = 0.35) -> None:
  410. """Clear the post-resize status-bar suppression after the reflow settles.
  411. Debounced: a fresh resize cancels the pending timer, so a resize storm repaints
  412. the bar only once it stops.
  413. """
  414. try:
  415. def _clear():
  416. self._status_bar_suppressed_after_resize = False
  417. try:
  418. app.invalidate()
  419. except Exception:
  420. pass
  421. self._restart_debounce_timer(
  422. "_status_bar_unsuppress_timer", delay, lambda _t: _run_on_app_loop(app, _clear))
  423. except Exception:
  424. # Fail open: never leave the bar stuck hidden.
  425. self._status_bar_suppressed_after_resize = False
  426. def _schedule_resize_recovery(self, app, original_on_resize, delay: float = 0.3) -> None:
  427. """Debounce resize redraws so footer chrome is not stamped into scrollback.
  428. The delay outwaits tmux, which re-wraps a pane on every resize but signals it at most
  429. every 250 ms, so mid-drag the width a recovery reads is stale — also over ssh from a
  430. tmux pane, where nothing says tmux is there (#95375). A width change also holds output
  431. paints and redraws until its recovery; while a drag keeps signalling, a recovery still
  432. runs ``_RESIZE_SETTLE`` after the first width change once output was held for
  433. ``_RESIZE_HOLD_MAX`` seconds, so output never freezes for the whole drag. A signal that
  434. leaves the width alone holds nothing.
  435. """
  436. try:
  437. lock = getattr(self, "_resize_recovery_lock", None)
  438. if lock is None:
  439. lock = threading.Lock()
  440. self._resize_recovery_lock = lock
  441. try:
  442. width = app.output.get_size().columns
  443. except Exception:
  444. width = None
  445. def _timer_fired(timer_ref):
  446. def _run_recovery():
  447. with lock:
  448. if getattr(self, "_resize_recovery_timer", None) is not timer_ref:
  449. return # superseded by a newer resize
  450. self._resize_recovery_timer = None
  451. self._resize_recovery_pending = False
  452. self._recover_after_resize(app, original_on_resize)
  453. _run_on_app_loop(app, _run_recovery)
  454. with lock:
  455. now = time.monotonic()
  456. pending = getattr(self, "_resize_recovery_pending", False)
  457. if pending or width is None or width != getattr(self, "_last_resize_width", None):
  458. if not pending:
  459. self._resize_recovery_pending = True
  460. self._resize_seen_at = now
  461. # A hold its last recovery could not release keeps its start: the
  462. # next recovery is due at once.
  463. if getattr(self, "_resize_hold_since", None) is None:
  464. self._resize_hold_since = now
  465. self._resize_narrowest = None
  466. _hold_paints()
  467. if isinstance(width, int) and width > 0: # truncated rows at the narrowest
  468. self._resize_narrowest = min(width, getattr(self, "_resize_narrowest", None) or width)
  469. if now - self._resize_hold_since >= _RESIZE_HOLD_MAX:
  470. # Shortly after a width change, not on a timer: between two of a drag,
  471. # once the terminal (a multiplexer re-wrapping its rows) has settled;
  472. # one landing mid-recovery would move rows under its erase and replay.
  473. delay = _RESIZE_SETTLE
  474. self._restart_debounce_timer("_resize_recovery_timer", delay, _timer_fired)
  475. except Exception:
  476. self._resize_recovery_pending = False
  477. self._recover_after_resize(app, original_on_resize)
  478. def _install_resize_recovery(self, app) -> None:
  479. """Route ``app._on_resize`` through the debounced ghost-clearing recovery
  480. (#5474/#49120) and seed the width baseline so the FIRST SIGWINCH can tell a benign
  481. signal from a real resize (#65293). Reads ``app.output`` directly, NOT
  482. ``_get_tui_terminal_width``: before ``app.run()`` the DummyApplication's output
  483. reports a hardcoded 80 columns, which would make the first real signal look like a
  484. width change. ``app.output`` is what the running resize handler measures.
  485. """
  486. width = None
  487. for probe in (lambda: app.output.get_size().columns,
  488. lambda: shutil.get_terminal_size((80, 24)).columns):
  489. try:
  490. width = probe()
  491. except Exception:
  492. width = None
  493. if width and width > 0:
  494. break
  495. self._last_resize_width = width
  496. original_on_resize = app._on_resize
  497. self._resize_original_on_resize = original_on_resize
  498. app._on_resize = lambda: self._schedule_resize_recovery(app, original_on_resize)
  499. # A render before the recovery lands at the new width from the old geometry and strands
  500. # chrome rows; the recovery repaints everything anyway (#95375). The final render at
  501. # exit is never held.
  502. original_redraw = app._redraw
  503. def _redraw_unless_resizing(render_as_done: bool = False) -> None:
  504. if render_as_done or not self._output_waits_for_resize(app):
  505. renderer = app.renderer
  506. floor = _chrome_floor()
  507. if floor: # what CPR would tell prompt_toolkit: the rows down to the bottom
  508. renderer._min_available_height = max(renderer._min_available_height, floor)
  509. before = renderer._last_screen, renderer._last_size
  510. original_redraw(render_as_done=render_as_done)
  511. # prompt_toolkit repaints every row when it has no previous paint or a new size
  512. self._note_chrome_paint(app, before[0] is None or renderer._last_size != before[1])
  513. app._redraw = _redraw_unless_resizing
  514. _set_paint_gate(app, lambda: self._output_waits_for_resize(app))
  515. def _output_waits_for_resize(self, app) -> bool:
  516. """Whether output must wait for a resize recovery: one is pending, or the terminal's
  517. width no longer matches the one the app last settled at — its SIGWINCH is not handled
  518. yet, and a paint or chrome render now would land in geometry that no recovery accounts
  519. for: on a terminal that does not reflow it scrolls rows the resize truncated into
  520. scrollback before any refill (#95375). Noticing that schedules the recovery."""
  521. if getattr(self, "_resize_recovery_pending", False):
  522. return True
  523. try:
  524. width = app.output.get_size().columns
  525. except Exception:
  526. return False
  527. if width == getattr(self, "_last_resize_width", None):
  528. return False
  529. self._schedule_resize_recovery(app, self._resize_original_on_resize)
  530. return bool(getattr(self, "_resize_recovery_pending", False))
  531. def _try_attach_clipboard_image(self) -> bool:
  532. """Save a clipboard image to ~/.hermes/images/ and attach it; True if attached."""
  533. from cli import datetime
  534. from hermes_cli.clipboard import save_clipboard_image
  535. self._image_counter += 1
  536. ts = datetime.now().strftime("%Y%m%d_%H%M%S")
  537. img_path = get_hermes_home() / "images" / f"clip_{ts}_{self._image_counter}.png"
  538. if save_clipboard_image(img_path):
  539. self._attached_images.append(img_path)
  540. return True
  541. self._image_counter -= 1
  542. return False
  543. def _write_osc52_clipboard(self, text: str) -> None:
  544. """Copy *text* to the terminal clipboard via OSC 52.
  545. Wrapped for tmux/screen passthrough (mirrors ui-tui/src/lib/osc52.ts) — without
  546. the DCS wrapper the multiplexer consumes the sequence and the copy is lost.
  547. """
  548. payload = base64.b64encode(text.encode("utf-8")).decode("ascii")
  549. seq = f"\x1b]52;c;{payload}\x07"
  550. if os.environ.get("TMUX"):
  551. seq = _tmux_passthrough(seq)
  552. elif os.environ.get("STY"):
  553. seq = "\x1bP" + seq + "\x1b\\"
  554. _write_terminal_sequence(getattr(self, "_app", None), seq)
  555. def _recover_terminal_input_modes(self, *, reason: str) -> None:
  556. """Best-effort reset when leaked mouse reports indicate mode drift."""
  557. from cli import (
  558. CLI_CONFIG, _DIM, _RST, _TERMINAL_INPUT_MODE_RESET_SEQ,
  559. _cli_multiline_shortcuts_enabled, _cprint, _enable_extended_enter_keys, logger)
  560. now = time.monotonic()
  561. # Rate-limit to avoid thrashing if a terminal floods reports. None = never
  562. # (monotonic epoch is arbitrary, see _invalidate).
  563. last = self._last_input_mode_recovery
  564. if last is not None and now - last < 0.5:
  565. return
  566. self._last_input_mode_recovery = now
  567. app = getattr(self, "_app", None)
  568. output = getattr(app, "output", None) if app else None
  569. try:
  570. _write_terminal_sequence(app, _TERMINAL_INPUT_MODE_RESET_SEQ)
  571. except Exception:
  572. return
  573. # The reset pops kitty keyboard mode and resets modifyOtherKeys too — re-request
  574. # extended keys so Shift+Enter isn't silently dead for the rest of the session.
  575. try:
  576. if _cli_multiline_shortcuts_enabled(self.config or CLI_CONFIG):
  577. _enable_extended_enter_keys(output)
  578. except Exception:
  579. pass
  580. logger.warning("Recovered terminal input modes after leak: %s", reason)
  581. if not self._input_mode_recovery_notice_shown:
  582. self._input_mode_recovery_notice_shown = True
  583. _cprint(f" {_DIM}{t('cli.terminal.recovered_mouse_modes')}{_RST}")
  584. def _check_termios_drift(self) -> None:
  585. """Idle watchdog: heal a tty that drifted back to cooked mode (a lost
  586. ``run_in_terminal`` cooked→raw restore leaves it line-buffering while prompt_toolkit
  587. believes it owns raw mode — CLI looks dead, process is healthy). Skipped while
  588. ``run_in_terminal`` legitimately holds cooked mode, while the agent runs
  589. (approval/sudo prompts touch the tty), and on Windows (no termios).
  590. """
  591. from cli import _DIM, _RST, _cprint, _heal_cooked_mode_drift, logger
  592. if os.name == "nt":
  593. return
  594. app = getattr(self, "_app", None)
  595. if app is None or not getattr(app, "_is_running", False):
  596. return
  597. if getattr(app, "_running_in_terminal", False):
  598. return
  599. now = time.monotonic()
  600. last = self._last_termios_drift_check # None = never (monotonic epoch is arbitrary)
  601. if last is not None and now - last < 1.0:
  602. return
  603. self._last_termios_drift_check = now
  604. try:
  605. if not sys.stdin.isatty():
  606. return
  607. fd = sys.stdin.fileno()
  608. except Exception:
  609. return
  610. if _heal_cooked_mode_drift(fd):
  611. logger.warning(
  612. "Healed cooked-mode termios drift on stdin — a "
  613. "run_in_terminal cooked→raw restore was lost.")
  614. try:
  615. self._invalidate() # so the prompt is visibly alive again
  616. except Exception:
  617. pass
  618. if not self._termios_drift_notice_shown:
  619. self._termios_drift_notice_shown = True
  620. _cprint(f" {_DIM}{t('cli.terminal.recovered_cooked_mode')}{_RST}")