cli_tui_mixin.py 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311
  1. # health: allow FILE_LINES -- usage-window plans: /model picker hooks only (a multi-row hint, Large/Free row labels); the logic lives in hermes_cli/model_picker_usage.py
  2. """prompt_toolkit TUI construction, key-binding handlers, and overlay display fragments for the
  3. interactive CLI. Mixin bound onto ``HermesCLI`` via the MRO; cli.py-internal symbols are imported
  4. LAZILY inside each method (``from cli import ...``) — never at module load (import cycle)."""
  5. from __future__ import annotations
  6. import errno
  7. import json
  8. import os
  9. import queue
  10. import shutil
  11. import string
  12. import sys
  13. import threading
  14. import time
  15. from agent.i18n import t
  16. from agent.interrupt_compat import request_hard_interrupt
  17. from hermes_cli.commands_completion import SlashCommandAutoSuggest, cli_slash_completer
  18. from pathlib import Path
  19. from prompt_toolkit.filters import Condition
  20. from prompt_toolkit.history import FileHistory
  21. from prompt_toolkit.key_binding import KeyBindings
  22. from prompt_toolkit.layout import (
  23. ConditionalContainer,
  24. FormattedTextControl,
  25. Layout,
  26. Window,
  27. WindowAlign)
  28. from prompt_toolkit.layout.dimension import Dimension
  29. from prompt_toolkit.layout.menus import CompletionsMenu
  30. from prompt_toolkit.layout.processors import (
  31. ConditionalProcessor,
  32. PasswordProcessor,
  33. Processor,
  34. Transformation)
  35. from prompt_toolkit.styles import Style as PTStyle
  36. from prompt_toolkit.widgets import TextArea
  37. from typing import Optional
  38. from hermes_cli import cli_enter_burst as _enter_burst
  39. from hermes_cli.cli_enter_burst import RAPID_INPUT_ENTER_WINDOW_S as _RAPID_INPUT_ENTER_WINDOW_S
  40. from hermes_cli.cli_footer_split import FooterSplit
  41. from hermes_cli.cli_panel import _Panel
  42. from hermes_cli.cli_tui_wrap import _prefix_wrapped_rows, _wrap_rows
  43. # Rows below an overlay panel taken by spinner/tool-progress, status bar, input, separators and
  44. # prompt symbol (measured ~6 during live PTY approval prompts) — shared by every panel budget.
  45. _PANEL_RESERVED_BELOW = 6
  46. _TYPING_CHARS = string.digits + string.ascii_letters + "-_.:/ "
  47. # Approval-choice identifiers (protocol tokens, never translated) → catalog keys for their labels.
  48. _APPROVAL_CHOICE_KEYS = {
  49. "once": "cli.tui.approval_once",
  50. "session": "cli.tui.approval_session",
  51. "always": "cli.tui.approval_always",
  52. "deny": "cli.tui.approval_deny",
  53. "view": "cli.tui.approval_view"}
  54. def _approval_choice_label(choice: str) -> str:
  55. """Localized label for an approval choice id; unknown ids render verbatim."""
  56. key = _APPROVAL_CHOICE_KEYS.get(choice)
  57. return t(key) if key else choice
  58. def _agent_name() -> str:
  59. try:
  60. from hermes_cli.skin_engine import get_active_skin
  61. return get_active_skin().get_branding("agent_name", "Hermes")
  62. except Exception:
  63. return "Hermes"
  64. def _tn(key: str, count: int, **kwargs) -> str:
  65. """Plural-aware lookup: ``<key>_one`` for exactly one, ``<key>_other`` otherwise."""
  66. return t(f"{key}_one" if count == 1 else f"{key}_other", count=count, **kwargs)
  67. def _num_prefix(i: int) -> str:
  68. """Quick-select key label: 1-9 for items 1-9, 0 for the 10th, blank beyond."""
  69. return str(i + 1) if i < 9 else ("0" if i == 9 else " ")
  70. def _term_rows() -> int:
  71. return shutil.get_terminal_size((100, 24)).lines
  72. class CLITuiMixin:
  73. """prompt_toolkit TUI construction, key-binding handlers, and overlay display fragments."""
  74. def _tui_input_rule_height(self, position: str, width: Optional[int] = None) -> int:
  75. """Visible height for the top/bottom input separator rules."""
  76. if position not in {"top", "bottom"}:
  77. raise ValueError(f"Unknown input rule position: {position}")
  78. if getattr(self, "_status_bar_suppressed_after_resize", False):
  79. return 0
  80. if position == "top":
  81. return 1
  82. return 0 if self._use_minimal_tui_chrome(width=width) else 1
  83. def _get_slash_confirm_display_fragments(self):
  84. """Render the /new-/clear-style confirmation panel."""
  85. from cli import _panel_box_width, _wrap_panel_text_keep_ws
  86. state = self._slash_confirm_state
  87. if not state:
  88. return []
  89. wrap = _wrap_panel_text_keep_ws
  90. title = state.get("title") or t("cli.tui.confirm_title")
  91. detail = state.get("detail") or ""
  92. choices = state.get("choices") or []
  93. selected = state.get("selected", 0)
  94. footer = t("cli.tui.confirm_footer")
  95. choice_labels = [
  96. f"{'❯' if idx == selected else ' '} [{idx + 1}] {label} — {desc}"
  97. for idx, (_value, label, desc) in enumerate(choices)]
  98. preview_lines = [w for line in detail.splitlines() for w in wrap(line, 72)]
  99. preview_lines.extend(w for _i, w in _wrap_rows(wrap, choice_labels, 72, " "))
  100. preview_lines.append(footer)
  101. box_width = _panel_box_width(title, preview_lines, min_width=56, max_width=86)
  102. inner_text_width = max(8, box_width - 2)
  103. detail_wrapped = [w for line in detail.splitlines() for w in wrap(line, inner_text_width)]
  104. choice_wrapped = _wrap_rows(wrap, choice_labels, inner_text_width, " ")
  105. chrome_full = 6
  106. available = max(0, _term_rows() - _PANEL_RESERVED_BELOW)
  107. max_detail_rows = min(8, max(1, available - chrome_full - len(choice_wrapped)))
  108. if len(detail_wrapped) > max_detail_rows:
  109. detail_wrapped = detail_wrapped[:max(1, max_detail_rows - 1)] + [t("cli.tui.detail_truncated")]
  110. panel = _Panel('class:approval-border', box_width)
  111. panel.row('class:approval-title', title)
  112. panel.blank()
  113. for wrapped in detail_wrapped:
  114. panel.row('class:approval-desc', wrapped)
  115. panel.blank()
  116. for idx, wrapped in choice_wrapped:
  117. style = 'class:approval-selected' if idx == selected else 'class:approval-choice'
  118. panel.row(style, wrapped)
  119. panel.blank()
  120. panel.row('class:approval-cmd', footer)
  121. return panel.close()
  122. def _get_approval_display_fragments(self):
  123. """Render the dangerous-command approval panel.
  124. Layout priority: title + command + choices must always render, even in a short terminal
  125. or with a long multi-paragraph description. The description sits at the bottom
  126. and is truncated to the remaining row budget, so HSplit never clips approve/deny off-screen.
  127. """
  128. from cli import _panel_box_width, _wrap_panel_text_keep_ws
  129. state = self._approval_state
  130. if not state:
  131. return []
  132. wrap = _wrap_panel_text_keep_ws
  133. command = state["command"]
  134. description = state["description"]
  135. choices = state["choices"]
  136. selected = state.get("selected", 0)
  137. show_full = state.get("show_full", False)
  138. title = t("cli.tui.approval_title")
  139. preview_lines = wrap(description, 60)
  140. preview_lines.extend(wrap(command, 60))
  141. for i, choice in enumerate(choices):
  142. prefix = '❯ ' if i == selected else ' '
  143. label = _approval_choice_label(choice)
  144. preview_lines.extend(wrap(f"{prefix}{label}", 60, subsequent_indent=" "))
  145. box_width = _panel_box_width(title, preview_lines)
  146. inner_text_width = max(8, box_width - 2)
  147. # Pre-wrap the mandatory content — command + choices must always render.
  148. cmd_wrapped = wrap(command, inner_text_width)
  149. if not show_full and "view" in choices and len(cmd_wrapped) > 4:
  150. cmd_wrapped = cmd_wrapped[:3] + wrap(
  151. t("cli.tui.approval_choose_full", label=t("cli.tui.approval_view")), inner_text_width)
  152. choice_labels = [
  153. f"{'❯' if i == selected else ' '} {_num_prefix(i)}. {_approval_choice_label(choice)}"
  154. for i, choice in enumerate(choices)]
  155. choice_wrapped = _wrap_rows(wrap, choice_labels, inner_text_width, " ")
  156. # Row budget so HSplit never clips the command or choices. Full chrome = top border +
  157. # title + blank + blank-between-cmd/choices + bottom border (5); when that doesn't fit,
  158. # drop the separator blanks (3) so every choice stays on-screen in compact terminals.
  159. available = max(0, _term_rows() - _PANEL_RESERVED_BELOW)
  160. use_compact_chrome = 5 + len(cmd_wrapped) + len(choice_wrapped) > available
  161. chrome_rows = 3 if use_compact_chrome else 5
  162. # A command too long to leave room for the choices (e.g. "view" on a multi-hundred-char
  163. # command) is truncated so approve/deny still render; keep at least 1 command row.
  164. max_cmd_rows = max(1, available - chrome_rows - len(choice_wrapped))
  165. if len(cmd_wrapped) > max_cmd_rows:
  166. keep = max(1, max_cmd_rows - 1) if max_cmd_rows > 1 else 1
  167. cmd_wrapped = cmd_wrapped[:keep] + wrap(
  168. t("cli.tui.approval_command_truncated"), inner_text_width)
  169. # Remaining rows go to the description (minus the blank separator in full mode), capped
  170. # at 10 so the panel stays compact even on huge terminals.
  171. mandatory_no_desc = chrome_rows + len(cmd_wrapped) + len(choice_wrapped)
  172. available_for_desc = available - mandatory_no_desc - (0 if use_compact_chrome else 1)
  173. available_for_desc = max(0, min(available_for_desc, 10))
  174. desc_wrapped = wrap(description, inner_text_width) if description else []
  175. if available_for_desc < 1 or not desc_wrapped:
  176. desc_wrapped = []
  177. elif len(desc_wrapped) > available_for_desc:
  178. desc_wrapped = desc_wrapped[:max(1, available_for_desc - 1)] + [t("cli.tui.approval_description_truncated")]
  179. # Render title → command → choices → description; description last so any overflow
  180. # clips the least-critical content, never the command or choices.
  181. panel = _Panel('class:approval-border', box_width)
  182. panel.row('class:approval-title', title)
  183. if not use_compact_chrome:
  184. panel.blank()
  185. for wrapped in cmd_wrapped:
  186. panel.row('class:approval-cmd', wrapped)
  187. if not use_compact_chrome:
  188. panel.blank()
  189. for i, wrapped in choice_wrapped:
  190. style = 'class:approval-selected' if i == selected else 'class:approval-choice'
  191. panel.row(style, wrapped)
  192. if desc_wrapped:
  193. if not use_compact_chrome:
  194. panel.blank()
  195. for wrapped in desc_wrapped:
  196. panel.row('class:approval-desc', wrapped)
  197. return panel.close()
  198. def _get_tui_prompt_symbols(self) -> tuple[str, str]:
  199. """Return ``(normal_prompt, state_suffix)`` for the active skin.
  200. ``state_suffix`` is what special states (sudo/secret/approval/agent) render after their
  201. leading icon. A non-default profile name is prepended (``coder ❯``).
  202. """
  203. try:
  204. from hermes_cli.skin_engine import get_active_prompt_symbol
  205. symbol = get_active_prompt_symbol("❯ ")
  206. except Exception:
  207. symbol = "❯ "
  208. symbol = (symbol or "❯ ").rstrip() + " "
  209. try:
  210. from hermes_cli.profiles import get_active_profile_name
  211. profile = get_active_profile_name()
  212. if profile not in {"default", "custom"}:
  213. symbol = f"{profile} {symbol}"
  214. except Exception:
  215. pass
  216. stripped = symbol.rstrip()
  217. if not stripped:
  218. return "❯ ", "❯ "
  219. parts = stripped.split()
  220. candidate = parts[-1] if parts else ""
  221. if any(ch in candidate for ch in ("❯", ">", "$", "#", "›", "»", "→")):
  222. return symbol, candidate.rstrip() + " "
  223. # Icon-only custom prompts should still remain visible in special states.
  224. return symbol, symbol
  225. def _audio_level_bar(self) -> str:
  226. """One-char audio level indicator from the recorder's current RMS."""
  227. rec = getattr(self, "_voice_recorder", None)
  228. if rec is None:
  229. return ""
  230. # RMS 0-32767 → index 0-7; typical speech is 500-5000, display caps at ~8000.
  231. return " ▁▂▃▄▅▆▇"[min(rec.current_rms, 8000) * 7 // 8000]
  232. def _get_tui_prompt_fragments(self):
  233. """prompt_toolkit fragments for the current interactive state."""
  234. symbol, state_suffix = self._get_tui_prompt_symbols()
  235. compact = self._use_minimal_tui_chrome(width=self._get_tui_terminal_width())
  236. def _state_fragment(style: str, icon: str, extra: str = ""):
  237. if compact:
  238. text = icon
  239. if extra:
  240. text = f"{text} {extra.strip()}".rstrip()
  241. return [(style, text + " ")]
  242. if extra:
  243. return [(style, f"{icon} {extra} {state_suffix}")]
  244. return [(style, f"{icon} {state_suffix}")]
  245. if self._voice_recording:
  246. return _state_fragment("class:voice-recording", "●", self._audio_level_bar())
  247. if self._voice_processing:
  248. return _state_fragment("class:voice-processing", "◉")
  249. if self._sudo_state:
  250. return _state_fragment("class:sudo-prompt", "🔐")
  251. if self._secret_state:
  252. return _state_fragment("class:sudo-prompt", "🔑")
  253. if self._connection_state:
  254. return _state_fragment("class:prompt-working", "⚙")
  255. if self._approval_state or getattr(self, "_slash_confirm_state", None):
  256. return _state_fragment("class:prompt-working", "⚠")
  257. if self._clarify_freetext:
  258. return _state_fragment("class:clarify-selected", "✎")
  259. if self._clarify_state:
  260. return _state_fragment("class:prompt-working", "?")
  261. if self._command_running:
  262. return _state_fragment("class:prompt-working", self._command_spinner_frame())
  263. if self._agent_running:
  264. return _state_fragment("class:prompt-working", "☤")
  265. if self._voice_mode:
  266. return _state_fragment("class:voice-prompt", "🎤")
  267. return [("class:prompt", symbol)]
  268. def _get_tui_prompt_text(self) -> str:
  269. """Visible prompt text for width calculations."""
  270. return "".join(text for _, text in self._get_tui_prompt_fragments())
  271. def _build_tui_style_dict(self) -> dict[str, str]:
  272. """Layer the active skin's prompt_toolkit colors over the base TUI style.
  273. On a light terminal, hex tokens in each style string are rewritten through the light-mode
  274. remap so the chrome stays readable on cream Terminal.app backgrounds. CRITICAL: a style
  275. that paints its own ``bg:`` (status bar, completion menu) is left alone — its fg was tuned
  276. for that dark bg and remapping would give dark-on-dark; the terminal's mode is irrelevant.
  277. """
  278. from cli import _detect_light_mode, _maybe_remap_for_light_mode
  279. style_dict = dict(getattr(self, "_tui_style_base", {}) or {})
  280. try:
  281. from hermes_cli.skin_engine import get_prompt_toolkit_style_overrides
  282. style_dict.update(get_prompt_toolkit_style_overrides())
  283. except Exception:
  284. pass
  285. try:
  286. if _detect_light_mode():
  287. def _remap_value(v: str) -> str:
  288. if not v:
  289. return v
  290. tokens = v.split()
  291. if any(t.startswith("bg:") for t in tokens):
  292. return v
  293. return " ".join(_maybe_remap_for_light_mode(t) if t.startswith("#") else t for t in tokens)
  294. style_dict = {k: _remap_value(v or "") for k, v in style_dict.items()}
  295. except Exception:
  296. pass
  297. return style_dict
  298. def _apply_tui_skin_style(self) -> bool:
  299. """Refresh prompt_toolkit styling for a running interactive TUI."""
  300. if not getattr(self, "_app", None) or not getattr(self, "_tui_style_base", None):
  301. return False
  302. self._app.style = PTStyle.from_dict(self._build_tui_style_dict())
  303. self._invalidate(min_interval=0.0)
  304. return True
  305. def _get_extra_tui_widgets(self) -> list:
  306. """Extension hook: wrapper CLIs return widgets inserted between the spacer and status bar."""
  307. return []
  308. def _register_extra_tui_keybindings(self, kb, *, input_area) -> None:
  309. """Extension hook: wrapper CLIs add bindings to ``kb`` (``input_area`` is the main TextArea)."""
  310. def _build_tui_layout_children(
  311. self,
  312. *,
  313. sudo_widget,
  314. secret_widget,
  315. connection_widget=None,
  316. approval_widget,
  317. slash_confirm_widget=None,
  318. clarify_widget,
  319. model_picker_widget=None,
  320. command_palette_widget=None,
  321. spinner_widget=None,
  322. spacer,
  323. status_bar,
  324. input_rule_top,
  325. image_bar,
  326. input_area,
  327. input_rule_bot,
  328. voice_status_bar,
  329. completions_menu) -> list:
  330. """Ordered children of the root ``HSplit``; override only for full control over ordering
  331. (wrappers normally override ``_get_extra_tui_widgets`` instead)."""
  332. ordered = [
  333. Window(height=0),
  334. sudo_widget,
  335. secret_widget,
  336. connection_widget,
  337. approval_widget,
  338. slash_confirm_widget,
  339. clarify_widget,
  340. model_picker_widget,
  341. command_palette_widget,
  342. spinner_widget,
  343. spacer,
  344. *self._get_extra_tui_widgets(),
  345. getattr(self, "_pet_widget", None),
  346. getattr(self, "_stash_panel_widget", None),
  347. getattr(self, "_subagent_dock_widget", None),
  348. status_bar,
  349. input_rule_top,
  350. image_bar,
  351. input_area,
  352. input_rule_bot,
  353. voice_status_bar,
  354. completions_menu]
  355. if getattr(self, "_modern_layout", False): # footer under the composer and its completions
  356. ordered.append(ordered.pop(ordered.index(status_bar)))
  357. return [item for item in ordered if item is not None]
  358. def _tui_spinner_loop(self):
  359. while not self._should_exit:
  360. if not self._app:
  361. time.sleep(0.1)
  362. continue
  363. monitor = getattr(self, "_subagent_monitor", None)
  364. if monitor is not None:
  365. monitor.tick()
  366. if self._command_running:
  367. self._invalidate(min_interval=0.1)
  368. time.sleep(0.1)
  369. else:
  370. # Never repaint the idle prompt on a timer: in non-full-screen mode background
  371. # redraws fight tmux/Ghostty/cmux viewport restoration after focus changes and
  372. # visually move the input area. Input/agent events invalidate explicitly.
  373. time.sleep(0.2)
  374. def _get_clarify_display_fragments(self):
  375. """Batch (multi-question) clarify panel: "N questions" header, one status line per question
  376. (✓ answered → answer / ▸ active / · pending), and the active question's numbered choices
  377. (+ Other) expanded beneath its status line."""
  378. from cli import _panel_box_width, _wrap_panel_text
  379. state = self._clarify_state
  380. if not state:
  381. return []
  382. questions_list = state.get("questions") or []
  383. answers = state.get("answers") or {}
  384. answer_meta = state.get("answer_meta") or {}
  385. active = state.get("active", 0)
  386. choices = state.get("choices") or []
  387. selected = state.get("selected", 0)
  388. multi_select = state.get("multi_select", False)
  389. selected_indices = state.get("selected_indices", set()) if multi_select else set()
  390. freetext = self._clarify_freetext
  391. title = t("cli.tui.clarify_title", agent_name=_agent_name())
  392. header = _tn("cli.tui.clarify_question_count", len(questions_list))
  393. def _status_rows(width):
  394. rows = []
  395. # End of the active question block and the row span of its selected choice.
  396. focus = {}
  397. for idx, entry in enumerate(questions_list):
  398. answered = entry["qid"] in answers
  399. marker = "✓" if answered else ("▸" if idx == active else "·")
  400. row_style = 'class:clarify-selected' if idx == active else 'class:clarify-choice'
  401. for wrapped in _wrap_panel_text(f"{marker} {entry['question']}", width, subsequent_indent=" "):
  402. rows.append((row_style, wrapped))
  403. if answered:
  404. # Locked answer on its own line/color so it stays readable while Tab-walking.
  405. locked = answers[entry['qid']]
  406. answer = f" {'—' if locked is None else locked}"
  407. for wrapped in _wrap_panel_text(answer, width, subsequent_indent=" "):
  408. rows.append(('class:clarify-answer', wrapped))
  409. if idx != active:
  410. continue
  411. for i, choice in enumerate(choices):
  412. cursor = "❯" if i == selected and not freetext else " "
  413. cb = ("[x] " if i in selected_indices else "[ ] ") if multi_select else ""
  414. style = 'class:clarify-selected' if i == selected and not freetext else 'class:clarify-choice'
  415. label = f" {cursor} {cb}{_num_prefix(i)}. {choice}"
  416. first = len(rows)
  417. for wrapped in _wrap_panel_text(label, width, subsequent_indent=" "):
  418. rows.append((style, wrapped))
  419. if i == selected and not freetext:
  420. focus["selected"] = (first, len(rows))
  421. if choices:
  422. other_idx = len(choices)
  423. mid = _num_prefix(other_idx)
  424. if multi_select:
  425. mid = f"{'[x]' if other_idx in selected_indices else '[ ]'} {mid}"
  426. # An earlier typed answer stays visible next to Other; Enter on it edits
  427. # (the composer is prefilled).
  428. other_text = (answer_meta.get(entry["qid"]) or {}).get("other_text") or ""
  429. other_suffix = t("cli.tui.clarify_other_answer", text=other_text) if other_text else None
  430. if freetext:
  431. other_label = f" ❯ {mid}. " + (other_suffix or t("cli.tui.clarify_other_type_below"))
  432. other_style = 'class:clarify-active-other'
  433. elif selected == other_idx:
  434. other_label = f" ❯ {mid}. " + (other_suffix or t("cli.tui.clarify_other_type_answer"))
  435. other_style = 'class:clarify-selected'
  436. else:
  437. other_label = f" {mid}. " + (other_suffix or t("cli.tui.clarify_other_type_answer"))
  438. other_style = 'class:clarify-choice'
  439. first = len(rows)
  440. for wrapped in _wrap_panel_text(other_label, width, subsequent_indent=" "):
  441. rows.append((other_style, wrapped))
  442. if freetext or selected == other_idx:
  443. focus["selected"] = (first, len(rows))
  444. elif freetext:
  445. guidance = " " + t("cli.tui.clarify_guidance")
  446. for wrapped in _wrap_panel_text(guidance, width):
  447. rows.append(('class:clarify-active-other', wrapped))
  448. focus["end"] = len(rows)
  449. return rows, focus
  450. preview_rows, _ = _status_rows(60)
  451. box_width = _panel_box_width(title, [header] + [text for _, text in preview_rows])
  452. rows, focus = _status_rows(max(8, box_width - 2))
  453. # The panel is an unsized Window, so rows past the viewport are clipped from the
  454. # bottom, which is where the active question's choices sit. When the body does not
  455. # fit, show the slice that ends with those choices and always holds the selected one.
  456. # Top rule, header and bottom rule take three rows.
  457. budget = max(1, _term_rows() - _PANEL_RESERVED_BELOW - 3)
  458. if len(rows) > budget and "end" in focus:
  459. sel_start, _sel_end = focus.get("selected", (focus["end"] - 1, focus["end"]))
  460. first = min(sel_start, focus["end"] - budget)
  461. first = max(0, min(first, len(rows) - budget))
  462. rows = rows[first:first + budget]
  463. panel = _Panel('class:clarify-border', box_width, title, 'class:clarify-title')
  464. panel.row('class:clarify-question', header)
  465. for style, text in rows:
  466. panel.row(style, text)
  467. return panel.close()
  468. def _render_scroll_list_panel(self, state, title, hint, labels, *, min_width, max_width, indent):
  469. """Titled panel with a hint row and a scrolling selectable list (model picker, palette).
  470. The panel renders into a Window with no max height, so the visible slice is limited to
  471. the terminal rows or the bottom border and trailing items get clipped on long lists
  472. (e.g. Ollama Cloud's 36+ models). ``state["_scroll_offset"]`` is updated in place.
  473. """
  474. from cli import HermesCLI, _panel_box_width, _wrap_panel_text
  475. # ``hint`` may be several rows (a window plan's limit line above the usual hint).
  476. hints = list(hint) if isinstance(hint, (list, tuple)) else [hint]
  477. box_width = _panel_box_width(title, hints + labels, min_width=min_width, max_width=max_width)
  478. # ``_Panel.row`` pads every row to ``box_width - 2``, so that is the real
  479. # body width. Keep the wrap budget in sync with it and reserve the
  480. # leading cell for the cursor/indent applied below, rather than the old
  481. # blanket ``- 6`` which wrapped long labels two columns early.
  482. inner_text_width = max(8, box_width - 2)
  483. label_width = max(8, inner_text_width - max(2, len(indent)))
  484. selected = state.get("selected", 0)
  485. try:
  486. from prompt_toolkit.application import get_app
  487. term_rows = get_app().output.get_size().rows
  488. except Exception:
  489. term_rows = _term_rows()
  490. scroll_offset, visible = HermesCLI._compute_model_picker_viewport(
  491. selected, state.get("_scroll_offset", 0), len(labels), term_rows,
  492. panel_chrome=5 + len(hints))
  493. state["_scroll_offset"] = scroll_offset
  494. panel = _Panel('class:clarify-border', box_width, title, 'class:clarify-title')
  495. panel.blank()
  496. for line in hints:
  497. panel.row('class:clarify-hint', line)
  498. panel.blank()
  499. for idx in range(scroll_offset, min(scroll_offset + visible, len(labels))):
  500. style = 'class:clarify-selected' if idx == selected else 'class:clarify-choice'
  501. # The cursor cell is always two columns wide, so unselected rows get two spaces
  502. # regardless of ``indent`` (the palette's continuation indent is four) — otherwise
  503. # the selected label starts two columns left of its neighbours.
  504. lead = '❯ ' if idx == selected else ' '
  505. for wrapped in _prefix_wrapped_rows(
  506. _wrap_panel_text, labels[idx], label_width, lead, indent
  507. ):
  508. panel.row(style, wrapped)
  509. panel.blank()
  510. return panel.close()
  511. def _get_model_picker_display_fragments(self):
  512. state = self._model_picker_state
  513. if not state:
  514. return []
  515. if state.get("stage", "provider") == "provider":
  516. title = t("cli.tui.picker_title_provider")
  517. choices = []
  518. _providers = state.get("providers")
  519. for p in _providers if isinstance(_providers, list) else []:
  520. count = p.get("total_models", len(p.get("models", [])))
  521. label = _tn("cli.tui.picker_provider_row", count, name=p['name'])
  522. if p.get("is_current"):
  523. label += t("cli.tui.picker_current_marker")
  524. choices.append(label)
  525. choices.append(t("cli.shared.cancel"))
  526. _unknown = t("cli.shared.unknown")
  527. hint = t("cli.tui.picker_current_hint",
  528. model=state.get('current_model', _unknown),
  529. provider=state.get('current_provider', _unknown))
  530. elif state.get("stage") == "reasoning":
  531. from hermes_cli.cli_model_switch_mixin import _picker_reasoning_rows
  532. result = state.get("switch_result")
  533. picked = getattr(result, "new_model", "") or t("cli.shared.noun_model")
  534. title = t("cli.tui.picker_title_effort", model=picked)
  535. rc = self.reasoning_config
  536. current = ("none" if isinstance(rc, dict) and rc.get("enabled") is False
  537. else (rc or {}).get("effort", "medium") if isinstance(rc, dict) else "medium")
  538. choices = [t("cli.tui.picker_current_labeled", label=label) if value == current else label
  539. for value, label in _picker_reasoning_rows()]
  540. choices += [t("cli.shared.back"), t("cli.shared.cancel")]
  541. hint = t("cli.tui.picker_effort_hint")
  542. else:
  543. provider_data = state.get("provider_data") or {}
  544. model_list = state.get("model_list") or []
  545. title = t("cli.tui.picker_title_models", provider=provider_data.get(
  546. 'name', provider_data.get('slug', t("cli.tui.picker_provider_fallback"))))
  547. # Fuzzy filter narrows the concrete list; selection still resolves to a real entry via
  548. # the filtered_pairs index mapping, so this never makes model resolution ambiguous.
  549. _query = state.get("filter", "") or ""
  550. filtered_pairs = self._filter_model_picker_entries(model_list, _query)
  551. state["_filtered_pairs"] = filtered_pairs
  552. model_labels = [e for (_i, e) in filtered_pairs]
  553. from hermes_cli.model_picker_usage import annotate_window_plan_rows
  554. row_labels, limit_line = annotate_window_plan_rows(provider_data, model_labels)
  555. choices = row_labels + [t("cli.shared.back"), t("cli.shared.cancel")]
  556. if _query:
  557. hint = t("cli.tui.picker_filter_hint", query=_query, shown=len(model_labels), total=len(model_list))
  558. elif model_list:
  559. hint = t("cli.tui.picker_select_hint", count=len(model_list))
  560. else:
  561. hint = t("cli.tui.picker_empty")
  562. # Window plan past an allowance: say once what happens next (pay as you go or wait), above the hint.
  563. if limit_line:
  564. hint = [limit_line, hint]
  565. return self._render_scroll_list_panel(
  566. state, title, hint, choices, min_width=46, max_width=84, indent=' ')
  567. def _get_command_palette_display_fragments(self):
  568. state = self._command_palette_state
  569. if not state:
  570. return []
  571. rows = self._command_palette_visible_entries()
  572. state["_visible_count"] = len(rows)
  573. _query = state.get("filter", "") or ""
  574. total = len(state.get("entries") or [])
  575. if _query:
  576. hint = t("cli.tui.palette_filter_hint", query=_query, shown=len(rows), total=total)
  577. else:
  578. hint = t("cli.tui.palette_hint", total=total)
  579. labels = [f"{c} — {d}" if d else c for (c, _cat, d) in rows] or [t("cli.tui.palette_empty")]
  580. return self._render_scroll_list_panel(
  581. state, t("cli.tui.palette_title"), hint, labels, min_width=50, max_width=90, indent=' ')
  582. def _render_sudo_style_panel(
  583. self, title: str, body_lines: list[str], row_styles: list[str] | None = None
  584. ):
  585. """Bordered ``sudo-*`` panel: blank, each body line, blank, body-final line, blank."""
  586. from cli import _panel_box_width
  587. box_width = _panel_box_width(title, body_lines)
  588. panel = _Panel('class:sudo-border', box_width, title, 'class:sudo-title')
  589. panel.blank()
  590. for i, text in enumerate(body_lines):
  591. if i == len(body_lines) - 1 and i > 0:
  592. panel.blank()
  593. style = row_styles[i] if row_styles and i < len(row_styles) else 'class:sudo-text'
  594. panel.row(style, text)
  595. panel.blank()
  596. return panel.close()
  597. def _get_sudo_display_fragments(self):
  598. if not self._sudo_state:
  599. return []
  600. # Panel bodies are one catalog value per panel (multi-line prose), split into rows here.
  601. if code := self._sudo_state.get("vault_code"):
  602. return self._render_sudo_style_panel(
  603. t("cli.tui.vault_code_title", site=code["site"]),
  604. t("cli.tui.vault_code_body", site=code["site"], agent_name=_agent_name()).split("\n"))
  605. if save := self._sudo_state.get("vault_save"):
  606. if save["step"] == "identifier":
  607. return self._render_sudo_style_panel(
  608. t("cli.tui.vault_save_title", site=save["site"]),
  609. t("cli.tui.vault_save_body").split("\n"))
  610. return self._render_sudo_style_panel(
  611. t("cli.tui.vault_save_title", site=save["site"]),
  612. t("cli.tui.vault_save_pw_body", origin=save["origin"]).split("\n"))
  613. if backend := self._sudo_state.get("vault_backend"):
  614. return self._render_sudo_style_panel(
  615. t("cli.tui.vault_unlock_title", backend=backend),
  616. t("cli.tui.vault_unlock_body", backend=backend).split("\n"))
  617. return self._render_sudo_style_panel(t("cli.tui.sudo_title"), [t("cli.tui.sudo_body")])
  618. def _get_secret_display_fragments(self):
  619. state = self._secret_state
  620. if not state:
  621. return []
  622. prompt = state.get("prompt") or t(
  623. "cli.tui.secret_prompt", var_name=state.get('var_name', t("cli.tui.secret_fallback_name")))
  624. help_text = (state.get("metadata") or {}).get("help")
  625. content_lines = [prompt, t("cli.tui.secret_body")]
  626. if help_text:
  627. content_lines.insert(1, str(help_text))
  628. return self._render_sudo_style_panel(t("cli.tui.secret_title"), content_lines)
  629. def _get_connection_display_fragments(self):
  630. state = self._connection_state
  631. lines = self._connection_render_lines()
  632. if not state or not lines:
  633. return []
  634. body_lines = lines[1:]
  635. styles = ['class:sudo-text'] * len(body_lines)
  636. phase = state.get("phase")
  637. fields = state.get("fields") or []
  638. instructions_offset = 1 if state.get("target", {}).get("instructions") else 0
  639. if phase in {"form", "failed"}:
  640. field_offset = instructions_offset + (1 if phase == "failed" else 0)
  641. field_index = state.get("field_index", 0)
  642. if 0 <= field_index < len(fields):
  643. styles[field_offset + field_index] = 'class:clarify-selected'
  644. elif body_lines:
  645. action_index = len(body_lines) - 1
  646. styles[action_index] = 'class:clarify-selected'
  647. choices = [t("cli.tui.connection_connect"), t("cli.shared.cancel")]
  648. selected = min(1, max(0, state.get("selected", 0)))
  649. body_lines[action_index] = " ".join(
  650. f"▸ {choice}" if i == selected else choice for i, choice in enumerate(choices)
  651. )
  652. elif phase == "authorized" and body_lines:
  653. styles[-1] = 'class:clarify-selected'
  654. body_lines[-1] = "▸ " + t("cli.tui.connection_continue")
  655. return self._render_sudo_style_panel(lines[0], body_lines, styles)
  656. # (state attr, deadline attr, hint catalog key) for the modal prompts with a countdown hint
  657. # row. Keys, not text: the label is looked up at render time so a language switch applies.
  658. _TUI_MODAL_HINTS = (
  659. ("_sudo_state", "_sudo_deadline", "cli.tui.hint_sudo"),
  660. ("_secret_state", "_secret_deadline", "cli.tui.hint_secret"),
  661. ("_approval_state", "_approval_deadline", "cli.tui.hint_approval"),
  662. ("_slash_confirm_state", "_slash_confirm_deadline", "cli.tui.hint_slash_confirm"),
  663. )
  664. # Connection-setup phase (protocol id) → hint catalog key.
  665. _TUI_CONNECTION_HINT_KEYS = {
  666. "form": "cli.tui.hint_connection_form",
  667. "failed": "cli.tui.hint_connection_form",
  668. "url": "cli.tui.hint_connection_url",
  669. "authorized": "cli.tui.hint_connection_authorized",
  670. "waiting": "cli.tui.hint_connection_waiting",
  671. }
  672. def _tui_hint_text(self):
  673. if self._connection_state:
  674. phase = self._connection_state.get("phase")
  675. hint = " " + t(self._TUI_CONNECTION_HINT_KEYS.get(phase, "cli.tui.hint_connection_default"))
  676. deadline = float(self._connection_state.get("payload", {}).get("deadline_at") or 0)
  677. countdown = f" ({max(0, int(deadline - time.time()))}s)" if deadline else ""
  678. return [('class:hint', hint), ('class:clarify-countdown', countdown)]
  679. for state_attr, deadline_attr, hint_key in self._TUI_MODAL_HINTS:
  680. if getattr(self, state_attr):
  681. if state_attr == "_sudo_state" and ((self._sudo_state.get("vault_save") or {}).get("step") == "identifier"
  682. or self._sudo_state.get("vault_code")):
  683. hint_key = "cli.tui.hint_vault_username"
  684. hint = " " + t(hint_key)
  685. remaining = max(0, int(getattr(self, deadline_attr) - time.monotonic()))
  686. return [('class:hint', hint), ('class:clarify-countdown', f' ({remaining}s)')]
  687. if self._clarify_state:
  688. # None deadline = unlimited wait → hide the countdown entirely.
  689. if self._clarify_deadline is None:
  690. countdown = ''
  691. else:
  692. countdown = f' ({max(0, int(self._clarify_deadline - time.monotonic()))}s)'
  693. if self._clarify_freetext:
  694. hint = " " + t("cli.tui.hint_clarify_freetext")
  695. else:
  696. hint = " " + t("cli.tui.hint_clarify_batch")
  697. return [('class:hint', hint), ('class:clarify-countdown', countdown)]
  698. if self._command_running:
  699. frame = self._command_spinner_frame()
  700. if self._command_blocks_input:
  701. detail = t("cli.tui.hint_input_disabled")
  702. else:
  703. detail = t("cli.tui.hint_input_queues")
  704. return [('class:hint', " " + t("cli.tui.hint_command_running", frame=frame, detail=detail))]
  705. return []
  706. def _tui_placeholder_text(self):
  707. if self._voice_recording: # live STT partial text (stt.streaming) replaces the hint
  708. return self._voice_live_text or t("cli.tui.placeholder_recording", shortcut=self._voice_record_key_label())
  709. if self._voice_processing:
  710. return self._voice_live_text or t("cli.tui.placeholder_transcribing")
  711. if self._sudo_state:
  712. if (self._sudo_state.get("vault_save") or {}).get("step") == "identifier":
  713. return t("cli.tui.placeholder_vault_username")
  714. if self._sudo_state.get("vault_code"):
  715. return t("cli.tui.placeholder_vault_code")
  716. return t("cli.tui.placeholder_password")
  717. if self._secret_state:
  718. return t("cli.tui.placeholder_secret")
  719. if self._approval_state:
  720. return ""
  721. if self._slash_confirm_state:
  722. return t("cli.tui.placeholder_choice")
  723. if self._clarify_freetext:
  724. return t("cli.tui.placeholder_answer")
  725. if self._clarify_state:
  726. return ""
  727. if self._command_running:
  728. return f"{self._command_spinner_frame()} {self._command_status or t('cli.tui.placeholder_processing_command')}"
  729. if self._agent_running:
  730. if getattr(self, "_modern_layout", False):
  731. return t(f"cli.modern.placeholder_busy_{self.busy_input_mode}")
  732. return t("cli.tui.placeholder_busy")
  733. if self._voice_mode:
  734. return t("cli.tui.placeholder_voice_idle", shortcut=self._voice_record_key_label())
  735. # Advertise a parked draft so the stash can never be silently forgotten.
  736. try:
  737. _stash_hint = self._prompt_stash.placeholder_hint()
  738. except Exception:
  739. _stash_hint = ""
  740. if _stash_hint:
  741. return _stash_hint
  742. # Idle + empty composer: a task-oriented example chosen once per session
  743. # (self._composer_placeholder) so it stays stable while being read, not flickering.
  744. return getattr(self, "_composer_placeholder", "") or ""
  745. def _get_stash_panel_display_fragments(self):
  746. try:
  747. _stash = self._prompt_stash
  748. return self._render_stash_panel(
  749. _stash.panel_rows(), _stash.panel_cursor, self._get_tui_terminal_width())
  750. except Exception:
  751. return []
  752. def _tui_handle_voice_record(self, event):
  753. """Toggle voice recording when voice mode is active.
  754. Runs on prompt_toolkit's event-loop thread: any blocking call here (locks, sd.wait,
  755. disk I/O) freezes the whole UI, so all heavy work goes to daemon threads.
  756. """
  757. from cli import _DIM, _RST, _cprint, logger
  758. if not self._voice_mode:
  759. return
  760. if self._voice_recording:
  761. # Always allow STOPPING (even while the agent runs); manual stop ends continuous
  762. # mode. Flag clearing happens atomically inside _voice_stop_and_transcribe.
  763. with self._voice_lock:
  764. self._voice_continuous = False
  765. event.app.invalidate()
  766. threading.Thread(target=self._voice_stop_and_transcribe, daemon=True).start()
  767. return
  768. # Allow disarming continuous mode while the agent runs or transcribes — otherwise the
  769. # user is stuck in an auto-restart loop until /voice off.
  770. if self._agent_running or self._voice_processing:
  771. with self._voice_lock:
  772. self._voice_continuous = False
  773. event.app.invalidate()
  774. return
  775. # Don't START recording during interactive prompts.
  776. if (self._clarify_state or self._sudo_state or self._approval_state
  777. or self._slash_confirm_state or self._connection_state):
  778. return
  779. # Cut TTS so the user can start talking: stop_playback() just terminates a subprocess;
  780. # the stop event drains the streaming pipeline if one is live.
  781. if not self._voice_tts_done.is_set():
  782. try:
  783. logger.info("TTS CUT: record key handler cutting TTS")
  784. from tools.tts_streaming import mark_speech_interrupted
  785. mark_speech_interrupted()
  786. if self._voice_tts_stop is not None:
  787. self._voice_tts_stop.set()
  788. from tools.voice_mode import stop_playback
  789. stop_playback()
  790. self._voice_tts_done.set()
  791. except Exception:
  792. pass
  793. with self._voice_lock:
  794. self._voice_continuous = True
  795. # play_beep(sd.wait), AudioRecorder.start(lock) and config I/O must never block the loop.
  796. def _start_recording():
  797. try:
  798. self._voice_start_recording()
  799. if hasattr(self, '_app') and self._app:
  800. self._app.invalidate()
  801. except Exception as e:
  802. _cprint(f"\n{_DIM}{t('cli.tui.voice_recording_failed', error=e)}{_RST}")
  803. threading.Thread(target=_start_recording, daemon=True).start()
  804. event.app.invalidate()
  805. def _tui_cancel_voice_recording(self, event) -> bool:
  806. """Cancel an active recording; True when one was cancelled (caller stops there)."""
  807. from cli import _DIM, _RST, _cprint
  808. _recorder_ref = None
  809. with self._voice_lock:
  810. if self._voice_recording and self._voice_recorder:
  811. _recorder_ref = self._voice_recorder
  812. self._voice_recording = False
  813. self._voice_continuous = False
  814. if _recorder_ref is None:
  815. return False
  816. _cprint(f"\n{_DIM}{t('cli.tui.recording_cancelled')}{_RST}")
  817. # cancel() may block on AudioRecorder._lock / CoreAudio — keep it off the event loop.
  818. threading.Thread(target=_recorder_ref.cancel, daemon=True).start()
  819. event.app.invalidate()
  820. return True
  821. def _tui_cancel_foreground_ui(self, event, *, closers) -> bool:
  822. """Close the first active foreground UI (slash-confirm / picker / palette); True if any."""
  823. for state_attr, close in closers:
  824. if getattr(self, state_attr, None):
  825. close()
  826. event.app.current_buffer.reset()
  827. event.app.invalidate()
  828. return True
  829. return False
  830. def _tui_clear_blocking_overlays(self, event) -> bool:
  831. """Clear every agent-blocking overlay (approval/clarify/sudo/secret) in one shot.
  832. Callers must NOT return on True alone: they fall through so a stale/orphaned overlay
  833. (left by an earlier interrupt) can't swallow the press before the agent-interrupt
  834. branch, leaving the chat frozen (#14026).
  835. """
  836. if not (self._sudo_state or self._secret_state or self._approval_state
  837. or self._clarify_state or self._connection_state):
  838. return False
  839. self._clear_active_overlays_for_interrupt()
  840. event.app.current_buffer.reset()
  841. event.app.invalidate()
  842. return True
  843. def _tui_clear_or_exit(self, event) -> None:
  844. """Clear text/images like bash; exit when everything is already empty."""
  845. if event.app.current_buffer.text or self._attached_images:
  846. event.app.current_buffer.reset()
  847. self._attached_images.clear()
  848. event.app.invalidate()
  849. else:
  850. self._should_exit = True
  851. event.app.exit()
  852. def _tui_handle_ctrl_c(self, event):
  853. """Ctrl+C priority: cancel voice recording → cancel foreground UI/overlay prompt or the wait for a
  854. command on its own gateway socket (a plugin command, /cron) → clear a typed draft, even mid-run (a correction must never kill the turn)
  855. → interrupt the running agent → force exit (second press within 2s) → when idle and empty, exit."""
  856. now = time.time()
  857. if self._tui_cancel_voice_recording(event):
  858. return
  859. if self._tui_cancel_foreground_ui(event, closers=(
  860. ("_slash_confirm_state", lambda: self._submit_slash_confirm_response("cancel")),
  861. ("_model_picker_state", self._close_model_picker), ("_command_palette_state", self._close_command_palette),
  862. ("_gateway_command_wait", lambda: self._gateway_command_wait.set()))):
  863. return
  864. overlay_cleared = self._tui_clear_blocking_overlays(event)
  865. if overlay_cleared and not (self._agent_running and self.agent):
  866. return
  867. if self._agent_running and self.agent and not (event.app.current_buffer.text or self._attached_images):
  868. if now - self._last_ctrl_c_time < 2.0:
  869. print("\n" + t("cli.tui.force_exiting"))
  870. self._should_exit = True
  871. event.app.exit()
  872. return
  873. self._last_ctrl_c_time = now
  874. print("\n" + t("cli.tui.interrupting_again_hint"))
  875. request_hard_interrupt(self.agent)
  876. else:
  877. self._tui_clear_or_exit(event)
  878. def _tui_handle_ctrl_q(self, event):
  879. """Ctrl+Q: like Ctrl+C minus the double-press force exit (and it leaves the palette)."""
  880. if self._tui_cancel_voice_recording(event):
  881. return
  882. if self._tui_cancel_foreground_ui(event, closers=(
  883. ("_slash_confirm_state", lambda: self._submit_slash_confirm_response("cancel")),
  884. ("_model_picker_state", self._close_model_picker))):
  885. return
  886. overlay_cleared = self._tui_clear_blocking_overlays(event)
  887. if overlay_cleared and not (self._agent_running and self.agent):
  888. return
  889. if self._agent_running and self.agent and not (event.app.current_buffer.text or self._attached_images):
  890. print("\n" + t("cli.tui.interrupting"))
  891. request_hard_interrupt(self.agent)
  892. else:
  893. self._tui_clear_or_exit(event)
  894. def _tui_make_clarify_number_handler(self, idx):
  895. def handler(event):
  896. state = self._clarify_state
  897. if not state or self._clarify_freetext:
  898. return
  899. choices = state.get("choices") or []
  900. if idx > len(choices):
  901. return
  902. # Multi-select: number keys toggle checkboxes (incl. "Other") instead of submitting.
  903. if state.get("multi_select"):
  904. indices = state.get("selected_indices", set())
  905. indices.symmetric_difference_update({idx})
  906. event.app.invalidate()
  907. return
  908. if idx == len(choices):
  909. # "Other" → freetext
  910. self._clarify_freetext = True
  911. else:
  912. # Lock the numbered choice for the active question only.
  913. self._clarify_batch_lock(state, choices[idx])
  914. event.app.invalidate()
  915. return handler
  916. def _tui_restore_stash_payload(self, event, payload) -> None:
  917. """Put a popped (text, images) payload back into the composer."""
  918. if not payload:
  919. return
  920. text, images = payload
  921. buf = event.app.current_buffer
  922. buf.text = text
  923. buf.cursor_position = len(text)
  924. # Extend rather than replace attachments: the user may have attached something new since
  925. # the stash was taken and dropping it silently would be data loss.
  926. for img in images or ():
  927. if img not in self._attached_images:
  928. self._attached_images.append(img)
  929. def _tui_handle_stash_panel_up(self, event):
  930. self._prompt_stash.move_cursor(-1)
  931. event.app.invalidate()
  932. def _tui_handle_stash_panel_down(self, event):
  933. self._prompt_stash.move_cursor(1)
  934. event.app.invalidate()
  935. def _tui_handle_stash_panel_delete(self, event):
  936. """D in the browse panel discards the highlighted draft."""
  937. self._prompt_stash.delete_at_cursor()
  938. event.app.invalidate()
  939. def _tui_handle_stash_panel_close(self, event):
  940. self._prompt_stash.close_panel()
  941. event.app.invalidate()
  942. def _tui_handle_tab(self, event):
  943. """Tab: accept the open completion, else the ghost auto-suggestion, else start completions.
  944. After accepting a provider like 'anthropic:' the menu closes and complete_while_typing
  945. doesn't fire (no keystroke); re-triggering here makes stage-2 models appear immediately.
  946. """
  947. buf = event.current_buffer
  948. if buf.complete_state:
  949. completion = buf.complete_state.current_completion
  950. if completion is None:
  951. # Menu open but nothing selected — select first then grab it
  952. buf.go_to_completion(0)
  953. completion = buf.complete_state and buf.complete_state.current_completion
  954. if completion is None:
  955. return
  956. buf.apply_completion(completion)
  957. elif buf.suggestion and buf.suggestion.text:
  958. buf.insert_text(buf.suggestion.text)
  959. else:
  960. buf.start_completion()
  961. def _tui_handle_double_escape(self, event):
  962. """Double ESC discards the draft and attached images (Claude Code / Gemini CLI gesture).
  963. Works while the agent streams — the gap Ctrl+C leaves (it interrupts the turn and only
  964. clears the draft when idle). The draft is appended to history first so Up recalls it,
  965. which is what makes a reflex key safe. Single ESC is the Alt-sequence prefix
  966. (escape+enter/g/v) so the escape-timeout keeps those distinct; modal prompts bind ESC
  967. eagerly and are excluded so cancel still wins.
  968. """
  969. buf = event.app.current_buffer
  970. if not (buf.text or self._attached_images):
  971. return
  972. buf.reset(append_to_history=bool(buf.text))
  973. self._attached_images.clear()
  974. event.app.invalidate()
  975. def _tui_handle_ignored_terminal_sequence(self, event):
  976. """Consume parser-level ignored terminal sequences before self-insert.
  977. hermes_cli.pt_input_extras registers focus reports (CSI I / CSI O) as Keys.Ignore at the
  978. VT100 parser; without this no-op binding the default self-insert would still land the
  979. bytes in the buffer. Focus-in additionally schedules a rate-limited full repaint: while
  980. hidden, the emulator may have coalesced output or repainted, so prompt_toolkit's
  981. incremental diff would stack a fresh prompt chrome on the stale one (#60920, #25337).
  982. """
  983. try:
  984. for press in getattr(event, "key_sequence", None) or ():
  985. if getattr(press, "data", None) == "\x1b[I":
  986. self._schedule_focus_regain_redraw()
  987. break
  988. except Exception:
  989. pass
  990. def _tui_handle_escape_modal(self, event):
  991. """ESC cancels active secret/sudo/connection/slash-confirm prompts."""
  992. if self._connection_state:
  993. self._connection_cancel()
  994. event.app.current_buffer.reset()
  995. event.app.invalidate()
  996. elif self._secret_state:
  997. self._cancel_secret_capture()
  998. event.app.current_buffer.reset()
  999. event.app.invalidate()
  1000. elif self._sudo_state:
  1001. self._sudo_state["response_queue"].put("")
  1002. self._sudo_state = None
  1003. event.app.invalidate()
  1004. elif self._slash_confirm_state:
  1005. self._submit_slash_confirm_response("cancel")
  1006. event.app.current_buffer.reset()
  1007. event.app.invalidate()
  1008. def _tui_handle_ctrl_z(self, event):
  1009. """Ctrl+Z suspends the process (Unix only)."""
  1010. from cli import _DIM, _RST, _cprint
  1011. if sys.platform == 'win32':
  1012. _cprint(f"\n{_DIM}{t('cli.tui.suspend_unsupported')}{_RST}")
  1013. event.app.invalidate()
  1014. return
  1015. import signal as _sig
  1016. from prompt_toolkit.application import run_in_terminal
  1017. from hermes_cli.skin_engine import get_active_skin
  1018. agent_name = get_active_skin().get_branding("agent_name", "Hermes Agent")
  1019. msg = "\n" + t("cli.tui.suspended", agent_name=agent_name)
  1020. def _suspend():
  1021. os.write(1, msg.encode())
  1022. os.kill(0, _sig.SIGTSTP)
  1023. run_in_terminal(_suspend)
  1024. def _tui_handle_ctrl_d(self, event):
  1025. """Ctrl+D deletes under the cursor (readline); exits only on empty input (pending images count),
  1026. like bash/zsh. Mid-turn it detaches: the gateway finishes the turn, Ctrl+C stops it (LC-6b)."""
  1027. buf = event.app.current_buffer
  1028. if buf.text:
  1029. buf.delete()
  1030. elif not self._attached_images:
  1031. self._should_exit, self._detach_on_exit = True, bool(self._agent_running)
  1032. event.app.exit()
  1033. def _tui_recall_without_recollapse(self, buf, move):
  1034. """Run a history move with paste-collapse suppressed.
  1035. Recalled history can hold the full text of a paste collapsed at submit time; loading it
  1036. back looks like a fresh large paste to ``_on_text_changed``. If the move didn't change the
  1037. text (plain cursor movement) the flag is cleared so a later real paste still collapses.
  1038. """
  1039. before = buf.text
  1040. self._skip_paste_collapse = True
  1041. move()
  1042. if buf.text == before:
  1043. self._skip_paste_collapse = False
  1044. def _tui_handle_alt_v(self, event):
  1045. """Alt+V pastes an image from the clipboard. Alt combos pass through every terminal
  1046. (ESC + key), unlike Ctrl+V which terminals intercept — reliable on WSL2/VSCode/SSH.
  1047. Silent when no image (avoid noise on accidental press)."""
  1048. if self._try_attach_clipboard_image():
  1049. event.app.invalidate()
  1050. def _tui_handle_ctrl_v(self, event):
  1051. """Image paste for terminals without bracketed paste: GNOME Terminal/Konsole send raw
  1052. 0x16. Terminals that intercept Ctrl+V (macOS Terminal, iTerm2, VSCode, Windows Terminal)
  1053. fire the bracketed-paste handler instead and never reach this."""
  1054. if self._try_attach_clipboard_image():
  1055. event.app.invalidate()
  1056. def _tui_handle_ctrl_l(self, event):
  1057. """Ctrl+L forces a clean repaint after terminal buffer drift (tmux/cmux tab switches,
  1058. ``clear`` from a subshell, SSH restores) that prompt_toolkit can't detect."""
  1059. self._force_full_redraw()
  1060. def _tui_insert_newline(self, event):
  1061. """Newline for multi-line input (Alt+Enter; Ctrl+J/Ctrl+Enter with multiline shortcuts).
  1062. Windows Terminal intercepts Alt+Enter (fullscreen) and delivers Ctrl+Enter as c-j."""
  1063. event.current_buffer.insert_text('\n')
  1064. def _tui_handle_open_in_editor(self, event):
  1065. """Ctrl+G (or Alt+G in VSCode/Cursor) opens the draft in an external editor."""
  1066. self._open_external_editor(event.current_buffer)
  1067. def _tui_connection_move(self, event, delta: int) -> None:
  1068. state = self._connection_state
  1069. if not state:
  1070. return
  1071. phase = state.get("phase")
  1072. if phase in {"form", "failed"}:
  1073. fields = state.get("fields") or []
  1074. current = state.get("field_index", 0)
  1075. if current < len(fields):
  1076. field = fields[current]
  1077. target_name = state.get("target", {}).get("name", "")
  1078. state["drafts"][target_name][field.get("name")] = event.app.current_buffer.text
  1079. state["field_index"] = min(len(fields), max(0, current + delta))
  1080. elif delta < 0 and fields:
  1081. state["field_index"] = len(fields) - 1
  1082. else:
  1083. state["selected"] = (state.get("selected", 0) + delta) % 2
  1084. self._connection_sync_input_buffer()
  1085. elif phase == "authorized":
  1086. state["selected"] = (state.get("selected", 0) + delta) % 2
  1087. self._paint_now()
  1088. event.app.invalidate()
  1089. def _tui_connection_up(self, event):
  1090. self._tui_connection_move(event, -1)
  1091. def _tui_connection_down(self, event):
  1092. self._tui_connection_move(event, 1)
  1093. def _tui_connection_side(self, event):
  1094. state = self._connection_state
  1095. if not state:
  1096. return
  1097. fields = state.get("fields") or []
  1098. if state.get("phase") == "authorized" or (
  1099. state.get("phase") in {"form", "failed"}
  1100. and state.get("field_index", 0) >= len(fields)
  1101. ):
  1102. state["selected"] = 1 - min(1, max(0, state.get("selected", 0)))
  1103. self._paint_now()
  1104. event.app.invalidate()
  1105. def _tui_model_picker_down(self, event):
  1106. state = self._model_picker_state
  1107. if not state:
  1108. return
  1109. if state.get("stage") == "provider":
  1110. max_idx = len(state.get("providers") or [])
  1111. elif state.get("stage") == "reasoning":
  1112. from hermes_cli.cli_model_switch_mixin import _picker_reasoning_rows
  1113. max_idx = len(_picker_reasoning_rows()) + 1 # + Back + Cancel
  1114. else:
  1115. # +1 for "← Back" and Cancel over the filtered visible rows.
  1116. _fp = state.get("_filtered_pairs")
  1117. max_idx = (len(_fp) if _fp is not None else len(state.get("model_list") or [])) + 1
  1118. state["selected"] = min(max_idx, state.get("selected", 0) + 1)
  1119. event.app.invalidate()
  1120. def _tui_model_picker_up(self, event):
  1121. if self._model_picker_state:
  1122. self._model_picker_state["selected"] = max(0, self._model_picker_state.get("selected", 0) - 1)
  1123. event.app.invalidate()
  1124. @staticmethod
  1125. def _tui_set_filter(st, value: str) -> None:
  1126. """Replace a picker/palette filter and rewind the selection + viewport."""
  1127. st["filter"] = value
  1128. st["selected"] = 0
  1129. st["_scroll_offset"] = 0
  1130. def _tui_model_picker_escape(self, event):
  1131. """ESC clears an active filter first, else steps back from the effort stage, else closes."""
  1132. st = self._model_picker_state
  1133. if st and st.get("stage") == "model" and (st.get("filter") or ""):
  1134. self._tui_set_filter(st, "")
  1135. event.app.invalidate()
  1136. return
  1137. if st and st.get("stage") == "reasoning":
  1138. st.update(stage="model", selected=0, _scroll_offset=0, switch_result=None)
  1139. event.app.invalidate()
  1140. return
  1141. self._close_model_picker()
  1142. event.app.current_buffer.reset()
  1143. event.app.invalidate()
  1144. def _tui_model_picker_filter_backspace(self, event):
  1145. st = self._model_picker_state
  1146. if st:
  1147. self._tui_set_filter(st, (st.get("filter", "") or "")[:-1])
  1148. event.app.invalidate()
  1149. def _tui_make_model_filter_char_handler(self, ch: str):
  1150. def handler(event):
  1151. st = self._model_picker_state
  1152. if not st or st.get("stage") != "model":
  1153. return
  1154. self._tui_set_filter(st, (st.get("filter", "") or "") + ch)
  1155. event.app.invalidate()
  1156. return handler
  1157. def _tui_make_palette_char_handler(self, ch: str):
  1158. def handler(event):
  1159. st = self._command_palette_state
  1160. if st:
  1161. self._tui_set_filter(st, (st.get("filter", "") or "") + ch)
  1162. event.app.invalidate()
  1163. return handler
  1164. def _tui_make_approval_number_handler(self, idx):
  1165. def handler(event):
  1166. if self._approval_state and idx < len(self._approval_state["choices"]):
  1167. self._approval_state["selected"] = idx
  1168. self._handle_approval_selection()
  1169. event.app.invalidate()
  1170. return handler
  1171. def _tui_make_slash_confirm_number_handler(self, idx):
  1172. def handler(event):
  1173. if self._slash_confirm_state and idx < len(self._slash_confirm_state.get("choices") or []):
  1174. self._submit_slash_confirm_response(self._slash_confirm_state["choices"][idx][0])
  1175. event.app.current_buffer.reset()
  1176. event.app.invalidate()
  1177. return handler
  1178. def _tui_clarify_toggle(self, event):
  1179. if self._clarify_state:
  1180. indices = self._clarify_state.get("selected_indices", set())
  1181. indices.symmetric_difference_update({self._clarify_state["selected"]})
  1182. event.app.invalidate()
  1183. def _tui_clarify_down(self, event):
  1184. if self._clarify_state:
  1185. max_idx = len(self._clarify_state.get("choices") or []) # last index is "Other"
  1186. self._clarify_state["selected"] = min(max_idx, self._clarify_state["selected"] + 1)
  1187. event.app.invalidate()
  1188. def _tui_clarify_up(self, event):
  1189. if self._clarify_state:
  1190. self._clarify_state["selected"] = max(0, self._clarify_state["selected"] - 1)
  1191. event.app.invalidate()
  1192. def _tui_clarify_batch_step(self, event, delta: int):
  1193. state = self._clarify_state
  1194. if state:
  1195. self._clarify_batch_set_active(state, (state["active"] + delta) % len(state["questions"]))
  1196. event.app.invalidate()
  1197. def _tui_clarify_batch_tab(self, event):
  1198. self._tui_clarify_batch_step(event, 1)
  1199. def _tui_clarify_batch_backtab(self, event):
  1200. self._tui_clarify_batch_step(event, -1)
  1201. def _tui_command_palette_backspace(self, event):
  1202. st = self._command_palette_state
  1203. if st:
  1204. self._tui_set_filter(st, (st.get("filter", "") or "")[:-1])
  1205. event.app.invalidate()
  1206. def _tui_command_palette_down(self, event):
  1207. st = self._command_palette_state
  1208. if st:
  1209. n = st.get("_visible_count", len(self._command_palette_visible_entries()))
  1210. st["selected"] = min(max(0, n - 1), st.get("selected", 0) + 1)
  1211. event.app.invalidate()
  1212. def _tui_command_palette_up(self, event):
  1213. st = self._command_palette_state
  1214. if st:
  1215. st["selected"] = max(0, st.get("selected", 0) - 1)
  1216. event.app.invalidate()
  1217. def _tui_command_palette_enter(self, event):
  1218. self._handle_command_palette_selection()
  1219. event.app.invalidate()
  1220. def _tui_command_palette_escape(self, event):
  1221. self._close_command_palette()
  1222. event.app.invalidate()
  1223. def _tui_open_command_palette(self, event):
  1224. self._open_command_palette()
  1225. event.app.invalidate()
  1226. def _tui_slash_confirm_down(self, event):
  1227. st = self._slash_confirm_state
  1228. if st:
  1229. st["selected"] = min(len(st.get("choices") or []) - 1, st.get("selected", 0) + 1)
  1230. event.app.invalidate()
  1231. def _tui_slash_confirm_up(self, event):
  1232. st = self._slash_confirm_state
  1233. if st:
  1234. st["selected"] = max(0, st.get("selected", 0) - 1)
  1235. event.app.invalidate()
  1236. def _tui_approval_down(self, event):
  1237. st = self._approval_state
  1238. if st:
  1239. st["selected"] = min(len(st["choices"]) - 1, st["selected"] + 1)
  1240. event.app.invalidate()
  1241. def _tui_approval_up(self, event):
  1242. st = self._approval_state
  1243. if st:
  1244. st["selected"] = max(0, st["selected"] - 1)
  1245. event.app.invalidate()
  1246. def _tui_wake_startup(self):
  1247. from cli import logger
  1248. try:
  1249. self._maybe_start_wake_word()
  1250. except Exception as e:
  1251. logger.debug("wake-word startup skipped: %s", e)
  1252. def _tui_suppress_closed_loop_errors(self, loop, context):
  1253. exc = context.get("exception")
  1254. if isinstance(exc, RuntimeError) and "Event loop is closed" in str(exc):
  1255. return
  1256. if isinstance(exc, KeyError) and "is not registered" in str(exc):
  1257. return # selector registration failures (#6393)
  1258. if isinstance(exc, OSError) and getattr(exc, "errno", None) == errno.EIO:
  1259. return # broken stdout on interrupt (#13710)
  1260. loop.default_exception_handler(context)
  1261. def _tui_handle_enter(self, event):
  1262. """Enter: submit input.
  1263. Modal overlays (sudo/secret/approval/slash-confirm/picker/clarify) are answered first via
  1264. ``_tui_enter_overlay``. Otherwise: agent running → busy_input_mode routing (steer /
  1265. redirect / interrupt queue / next-turn queue); idle → ``_pending_input``. Slash and bang
  1266. commands always take the local-dispatch path (never steer/interrupt text to the model).
  1267. """
  1268. from cli import _apply_backslash_line_continuation, _is_backslash_line_continuation
  1269. if self._tui_enter_overlay(event):
  1270. return
  1271. buf = event.app.current_buffer
  1272. raw_text = buf.text
  1273. # Explicit `\` + Enter continuation runs first so its backslash is consumed identically
  1274. # whether the Enter was typed or arrived inside a paste.
  1275. if (
  1276. self._tui_multiline_shortcuts
  1277. and buf.cursor_position == len(raw_text)
  1278. and _is_backslash_line_continuation(raw_text)):
  1279. continued = _apply_backslash_line_continuation(raw_text)
  1280. buf.text = continued
  1281. buf.cursor_position = len(continued)
  1282. event.app.invalidate()
  1283. return
  1284. # Enter mid-burst: a pasted newline (#10994), or the end of a scripted `text`+Enter write.
  1285. from hermes_cli.cli_enter_burst import handle_burst_enter
  1286. if not handle_burst_enter(self, event, buf):
  1287. self._tui_submit_buffer(event, buf)
  1288. def _tui_submit_buffer(self, event, buf):
  1289. """Submit the composer: inline commands, busy routing or ``_pending_input``."""
  1290. from cli import _looks_like_slash_command
  1291. text = buf.text.strip()
  1292. has_images = bool(self._attached_images)
  1293. if not (text or has_images):
  1294. return
  1295. if self._tui_enter_inline_command(event, text, has_images):
  1296. return
  1297. # Snapshot and clear attached images; bundle text + images as a tuple when present.
  1298. images = list(self._attached_images)
  1299. self._attached_images.clear()
  1300. event.app.invalidate()
  1301. payload = (text, images) if images else text
  1302. # A bang command is treated like a slash command while the agent is busy: it must never
  1303. # be routed into steer/redirect (injecting `!git status` into the model's context as a
  1304. # prompt). It queues and runs locally once the loop drains.
  1305. _is_local_dispatch = bool(text) and (_looks_like_slash_command(text) or text.strip().startswith("!"))
  1306. if self._agent_running and not _is_local_dispatch:
  1307. self._tui_enter_while_busy(text, images, payload)
  1308. else:
  1309. self._pending_input.put(payload)
  1310. # History stores real pasted content, not the placeholder, so up-arrow recall restores it.
  1311. self._inline_pastes(buf)
  1312. buf.reset(append_to_history=True)
  1313. def _tui_enter_inline_command(self, event, text: str, has_images: bool) -> bool:
  1314. """Run /model, /steer, /bg, /btw directly on the UI thread; True when handled.
  1315. /model needs the prompt_toolkit terminal-handoff helpers of the interactive pickers.
  1316. /steer, /bg and /btw while the agent runs must not queue through _pending_input: the
  1317. process loop is blocked inside self.chat(), so they would only run after the foreground
  1318. turn — turning /steer into a next-turn message (defeating mid-run injection, #34569) and
  1319. starting the /bg side task after the turn it should run alongside (#75221). The
  1320. foreground turn is left alone: no interrupt, no steer. agent.steer() is thread-safe.
  1321. Every branch invalidates after reset: process_command() prints through patch_stdout
  1322. and never invalidates the app, so the just-cleared input area would keep showing the
  1323. submitted text (looking unsent, inviting a re-submit) until some unrelated redraw.
  1324. """
  1325. if self._should_handle_model_command_inline(text, has_images=has_images):
  1326. if not self.process_command(text):
  1327. self._should_exit = True
  1328. if event.app.is_running:
  1329. event.app.exit()
  1330. elif (self._should_handle_steer_command_inline(text, has_images=has_images)
  1331. or self._should_handle_background_command_inline(text, has_images=has_images)
  1332. or self._should_handle_stop_command_inline(text, has_images=has_images)):
  1333. self.process_command(text)
  1334. else:
  1335. return False
  1336. event.app.current_buffer.reset(append_to_history=True)
  1337. event.app.invalidate()
  1338. return True
  1339. def _tui_enter_while_busy(self, text: str, images: list, payload, mode: str | None = None) -> None:
  1340. """Route a submission typed while the agent runs, per ``busy_input_mode``.
  1341. steer → agent.steer(text) mid-run (images can't ride along; a missing/rejecting steer() falls back
  1342. to queue). interrupt → agent.redirect() when supported, else the legacy interrupt queue. queue →
  1343. next turn: text-only on the gateway's session is a ``/queue`` FIFO admission (#134889 N5)."""
  1344. from cli import CLI_CONFIG, _ACCENT, _DIM, _RST, _cprint, _hermes_home
  1345. _effective_mode = mode or self.busy_input_mode
  1346. redirected = False
  1347. if _effective_mode == "steer":
  1348. if images or not text:
  1349. _effective_mode = "queue"
  1350. else:
  1351. accepted = False
  1352. try:
  1353. if self.agent is not None and hasattr(self.agent, "steer"):
  1354. accepted = self.agent.steer(text)
  1355. except Exception as exc:
  1356. _cprint(f" {_DIM}{t('cli.tui.steer_failed_queued', error=exc)}{_RST}")
  1357. accepted = False
  1358. if accepted == "voice_stopped": # TUI-26: consumed as a voice stop; nothing to queue
  1359. return
  1360. if accepted:
  1361. preview = text[:80] + ("..." if len(text) > 80 else "")
  1362. _cprint(f" {_ACCENT}{t('cli.tui.steered', preview=preview)}{_RST}")
  1363. else:
  1364. _effective_mode = "queue"
  1365. if _effective_mode == "queue" and text and not images and self._gateway_queue_store() is not None:
  1366. self._queue_enqueue(text)
  1367. elif _effective_mode == "queue":
  1368. self._pending_input.put(payload)
  1369. preview = text if text else _tn("cli.tui.images_attached_preview", len(images))
  1370. preview = preview[:80] + ('...' if len(preview) > 80 else '')
  1371. _cprint(" " + t("cli.tui.queued_next_turn", preview=preview))
  1372. elif _effective_mode == "interrupt":
  1373. if not images and text:
  1374. try:
  1375. if (
  1376. self.agent is not None
  1377. and getattr(self.agent, "_supports_active_turn_redirect", False) is True
  1378. and hasattr(self.agent, "redirect")):
  1379. redirected = self.agent.redirect(text)
  1380. except Exception:
  1381. redirected = False
  1382. if redirected == "voice_stopped": # TUI-26: consumed as a voice stop; nothing to queue
  1383. return
  1384. if redirected:
  1385. preview = text[:80] + ("..." if len(text) > 80 else "")
  1386. _cprint(f" {_ACCENT}{t('cli.tui.redirected_turn', preview=preview)}{_RST}")
  1387. else:
  1388. self._interrupt_queue.put(payload)
  1389. try:
  1390. with open(_hermes_home / "interrupt_debug.log", "a", encoding="utf-8") as _f:
  1391. _f.write(
  1392. f"{time.strftime('%H:%M:%S')} ENTER: queued interrupt msg={str(payload)[:60]!r}, "
  1393. f"agent_running={self._agent_running}\n")
  1394. except Exception:
  1395. pass
  1396. # First-touch onboarding: one-line tip about the /busy knob on the first busy-while-
  1397. # running event for this install; the flag persists to config.yaml. Guarded so
  1398. # onboarding can never break the input loop.
  1399. try:
  1400. from agent.onboarding import BUSY_INPUT_FLAG, busy_input_hint_cli, is_seen, mark_seen
  1401. if not is_seen(CLI_CONFIG, BUSY_INPUT_FLAG):
  1402. _hint_mode = "redirect" if redirected else _effective_mode
  1403. _cprint(f" {_DIM}{busy_input_hint_cli(_hint_mode)}{_RST}")
  1404. mark_seen(_hermes_home / "config.yaml", BUSY_INPUT_FLAG)
  1405. CLI_CONFIG.setdefault("onboarding", {}).setdefault("seen", {})[BUSY_INPUT_FLAG] = True
  1406. except Exception:
  1407. pass
  1408. def _tui_enter_overlay(self, event) -> bool:
  1409. """Enter while a modal overlay is up: submit it. True when handled."""
  1410. from cli import _cprint
  1411. buf = event.app.current_buffer
  1412. if self._connection_state:
  1413. state = self._connection_state
  1414. fields = state.get("fields") or []
  1415. if state.get("phase") in {"form", "failed"} and state.get("field_index", 0) < len(fields):
  1416. value = buf.text
  1417. buf.reset()
  1418. self._connection_set_field(value)
  1419. else:
  1420. self._connection_submit()
  1421. event.app.invalidate()
  1422. return True
  1423. if self._sudo_state:
  1424. self._sudo_state["response_queue"].put(buf.text)
  1425. self._sudo_state = None
  1426. event.app.invalidate()
  1427. return True
  1428. if self._secret_state:
  1429. value = buf.text
  1430. buf.reset()
  1431. self._submit_secret_response(value)
  1432. event.app.invalidate()
  1433. return True
  1434. if self._approval_state:
  1435. self._handle_approval_selection()
  1436. event.app.invalidate()
  1437. return True
  1438. if self._slash_confirm_state:
  1439. # Typed choice wins over the highlighted one.
  1440. text = buf.text.strip()
  1441. choices = self._slash_confirm_state.get("choices") or []
  1442. choice = self._normalize_slash_confirm_choice(text, choices) if text else None
  1443. if choice is None:
  1444. selected = self._slash_confirm_state.get("selected", 0)
  1445. if 0 <= selected < len(choices):
  1446. choice = choices[selected][0]
  1447. self._submit_slash_confirm_response(choice or "cancel")
  1448. buf.reset()
  1449. event.app.invalidate()
  1450. return True
  1451. if self._model_picker_state:
  1452. try:
  1453. # Picker selections follow the same session-scoped default as /model <name>
  1454. # (model.persist_switch_by_default).
  1455. from hermes_cli.model_switch import resolve_persist_behavior
  1456. self._handle_model_picker_selection(persist_global=resolve_persist_behavior(False, False))
  1457. except Exception as _exc:
  1458. _cprint(" " + t("cli.tui.model_selection_failed", error=_exc))
  1459. self._close_model_picker()
  1460. buf.reset()
  1461. event.app.invalidate()
  1462. return True
  1463. if self._clarify_state and self._clarify_freetext:
  1464. self._tui_enter_clarify_freetext(event)
  1465. return True
  1466. if self._clarify_state:
  1467. self._tui_enter_clarify_choice(event)
  1468. return True
  1469. return False
  1470. def _tui_enter_clarify_freetext(self, event) -> None:
  1471. """Clarify "Other": lock the typed answer; empty input skips the question."""
  1472. buf = event.app.current_buffer
  1473. text = buf.text.strip()
  1474. state = self._clarify_state
  1475. base = getattr(self, '_clarify_multi_base', None)
  1476. if not text:
  1477. self._clarify_freetext = False
  1478. self._clarify_prefill = ""
  1479. self._clarify_multi_base = None
  1480. if base:
  1481. self._clarify_batch_lock(state, json.dumps(base, ensure_ascii=False),
  1482. meta={"kind": "multi", "choices": list(base), "other_text": ""})
  1483. else:
  1484. self._clarify_batch_lock(state, None, meta={"kind": "skipped"})
  1485. buf.reset()
  1486. event.app.invalidate()
  1487. return
  1488. # Multi-select "Other" appends the typed answer to the checked labels as a JSON array string.
  1489. if base is not None:
  1490. answer = json.dumps(base + [text], ensure_ascii=False)
  1491. meta = {"kind": "multi", "choices": list(base), "other_text": text}
  1492. self._clarify_multi_base = None
  1493. else:
  1494. answer = text
  1495. meta = {"kind": "other", "other_text": text}
  1496. self._clarify_freetext = False
  1497. self._clarify_prefill = ""
  1498. self._clarify_batch_lock(state, answer, meta=meta)
  1499. buf.reset()
  1500. event.app.invalidate()
  1501. def _tui_enter_clarify_choice(self, event) -> None:
  1502. """Clarify choice mode: lock the active question's answer and advance to the next
  1503. unanswered."""
  1504. self._clarify_batch_enter(self._clarify_state)
  1505. # Editing an earlier "Other" answer: prefill the composer with the previous text.
  1506. if self._clarify_freetext and self._clarify_prefill:
  1507. event.app.current_buffer.text = self._clarify_prefill
  1508. event.app.current_buffer.cursor_position = len(self._clarify_prefill)
  1509. self._clarify_prefill = ""
  1510. event.app.invalidate()
  1511. def _tui_collapse_paste(self, text: str, line_count: int, *, fallback: bool) -> str:
  1512. """Save a large paste under ~/.hermes/pastes and return the placeholder for the buffer."""
  1513. from cli import _hermes_home, datetime, logger
  1514. self._tui_paste_counter += 1
  1515. paste_dir = _hermes_home / "pastes"
  1516. paste_dir.mkdir(parents=True, exist_ok=True)
  1517. paste_file = paste_dir / f"paste_{self._tui_paste_counter}_{datetime.now().strftime('%H%M%S')}.txt"
  1518. paste_file.write_text(text, encoding="utf-8")
  1519. logger.info(
  1520. "Collapsed paste #%d: %d lines, %d chars -> %s" + (" (fallback)" if fallback else ""),
  1521. self._tui_paste_counter, line_count + 1, len(text), paste_file)
  1522. self._tui_paste_just_collapsed = True
  1523. return f"[Pasted text #{self._tui_paste_counter}: {line_count + 1} lines \u2192 {paste_file}]"
  1524. def _tui_paste_over_threshold(self, text: str, line_count: int, threshold_key: str) -> bool:
  1525. threshold = self.config.get(threshold_key, 5)
  1526. char_threshold = self.config.get("paste_collapse_char_threshold", 2000)
  1527. lines_hit = threshold > 0 and line_count >= threshold
  1528. chars_hit = char_threshold > 0 and len(text) >= char_threshold
  1529. return lines_hit or chars_hit
  1530. def _tui_handle_paste(self, event):
  1531. """Bracketed paste: strip leaked terminal responses, auto-attach a clipboard image only
  1532. for image-only/empty gestures (so text pastes and dictation never attach stale images),
  1533. and collapse large pastes to a file-reference placeholder, preserving existing text."""
  1534. from cli import (
  1535. _should_auto_attach_clipboard_image_on_paste,
  1536. _strip_leaked_bracketed_paste_wrappers,
  1537. _strip_leaked_terminal_responses_with_meta,
  1538. logger)
  1539. # Diagnostic canary: log when the handler blocks the event loop >500ms so recurring
  1540. # "CLI freezes on paste" reports (#16263, macOS Tahoe + iTerm2/Ghostty) arrive with data.
  1541. _paste_handler_start = time.perf_counter()
  1542. _paste_raw_size = len(event.data or "")
  1543. # Normalise line endings so the collapse threshold and display are consistent.
  1544. pasted_text = (event.data or "").replace('\r\n', '\n').replace('\r', '\n')
  1545. pasted_text = _strip_leaked_bracketed_paste_wrappers(pasted_text)
  1546. pasted_text, _had_mouse_reports = _strip_leaked_terminal_responses_with_meta(pasted_text)
  1547. if _had_mouse_reports:
  1548. self._recover_terminal_input_modes(reason="mouse reports leaked into bracketed paste payload")
  1549. if _should_auto_attach_clipboard_image_on_paste(pasted_text) and self._try_attach_clipboard_image():
  1550. event.app.invalidate()
  1551. if pasted_text:
  1552. # Sanitize surrogates (Word/Google Docs paste) before writing.
  1553. from agent.message_sanitization import _sanitize_surrogates
  1554. pasted_text = _sanitize_surrogates(pasted_text)
  1555. line_count = pasted_text.count('\n')
  1556. buf = event.current_buffer
  1557. if (
  1558. self._tui_paste_over_threshold(pasted_text, line_count, "paste_collapse_threshold")
  1559. and not buf.text.strip().startswith('/')):
  1560. placeholder = self._tui_collapse_paste(pasted_text, line_count, fallback=False)
  1561. prefix = "\n" if buf.cursor_position > 0 and buf.text[buf.cursor_position - 1] != '\n' else ""
  1562. buf.insert_text(prefix + placeholder)
  1563. else:
  1564. buf.insert_text(pasted_text)
  1565. _paste_handler_elapsed_ms = (time.perf_counter() - _paste_handler_start) * 1000.0
  1566. if _paste_handler_elapsed_ms > 500.0:
  1567. logger.warning(
  1568. "Slow bracketed-paste handler: %.1fms to process %d bytes "
  1569. "(%d lines) on %s. If the input becomes unresponsive after "
  1570. "this, attach this log line to the bug report.",
  1571. _paste_handler_elapsed_ms,
  1572. _paste_raw_size,
  1573. pasted_text.count('\n') + 1 if pasted_text else 0,
  1574. sys.platform)
  1575. def _tui_on_text_changed(self, buf):
  1576. """Fallback paste collapse for terminals without bracketed paste.
  1577. Either heuristic triggers: many characters added in one event (paste delivered in one
  1578. tick), or the newline count jumped by 4+ (terminals that feed characters individually
  1579. but batch newlines; Alt+Enter adds 1 newline per event so never trips it).
  1580. """
  1581. self._tui_last_text_change = _enter_burst.note_text_change(self)
  1582. from cli import _strip_leaked_bracketed_paste_wrappers, _strip_leaked_terminal_responses_with_meta
  1583. text = _strip_leaked_bracketed_paste_wrappers(buf.text)
  1584. text, _had_mouse_reports = _strip_leaked_terminal_responses_with_meta(text)
  1585. if _had_mouse_reports:
  1586. self._recover_terminal_input_modes(reason="mouse reports leaked into prompt buffer")
  1587. if text != buf.text:
  1588. cursor = min(buf.cursor_position, len(text))
  1589. self._tui_paste_just_collapsed = True
  1590. buf.text = text
  1591. buf.cursor_position = cursor
  1592. self._tui_prev_text_len = len(text)
  1593. self._tui_prev_newline_count = text.count('\n')
  1594. return
  1595. chars_added = len(text) - self._tui_prev_text_len
  1596. self._tui_prev_text_len = len(text)
  1597. if self._tui_paste_just_collapsed or self._skip_paste_collapse:
  1598. self._tui_paste_just_collapsed = False
  1599. self._skip_paste_collapse = False
  1600. self._tui_prev_newline_count = text.count('\n')
  1601. return
  1602. line_count = text.count('\n')
  1603. newlines_added = line_count - self._tui_prev_newline_count
  1604. self._tui_prev_newline_count = line_count
  1605. is_paste = chars_added > 1 or newlines_added >= 4
  1606. if (
  1607. self._tui_paste_over_threshold(text, line_count, "paste_collapse_threshold_fallback")
  1608. and is_paste
  1609. and not text.startswith('/')):
  1610. buf.text = self._tui_collapse_paste(text, line_count, fallback=True)
  1611. buf.cursor_position = len(buf.text)
  1612. def _tui_handle_prompt_stash(self, event):
  1613. """Ctrl+S: composer has content → push onto the stash and clear; empty + one stashed →
  1614. pop it back; empty + several → open the browse panel; panel open → close it.
  1615. A stack (not a single slot) is what makes repeated Ctrl+S safe: a second stash never
  1616. silently overwrites the first, both stay reachable in the panel.
  1617. """
  1618. from hermes_cli.prompt_stash import ACTION_RESTORED, ACTION_STASHED, resolve_ctrl_s
  1619. buf = event.app.current_buffer
  1620. action, payload = resolve_ctrl_s(self._prompt_stash, buf.text, self._attached_images)
  1621. if action == ACTION_STASHED:
  1622. # reset() (not `text = ""`) also clears completion state, selection and the undo stack.
  1623. buf.reset()
  1624. self._attached_images.clear()
  1625. elif action == ACTION_RESTORED:
  1626. self._tui_restore_stash_payload(event, payload)
  1627. # ACTION_OPEN_PANEL: resolve_ctrl_s already flipped panel_open.
  1628. event.app.invalidate()
  1629. def _tui_handle_stash_panel_restore(self, event):
  1630. """Enter in the browse panel restores the highlighted draft."""
  1631. self._tui_restore_stash_payload(event, self._prompt_stash.restore_at_cursor())
  1632. event.app.invalidate()
  1633. def _tui_history_up(self, event):
  1634. """Up: browse history when on the first line, else move the cursor up."""
  1635. buf = event.app.current_buffer
  1636. self._tui_recall_without_recollapse(buf, lambda: buf.auto_up(count=event.arg))
  1637. def _tui_history_down(self, event):
  1638. buf = event.app.current_buffer
  1639. self._tui_recall_without_recollapse(buf, lambda: buf.auto_down(count=event.arg))
  1640. def _tui_image_bar_fragments(self):
  1641. from cli import _format_image_attachment_badges
  1642. if not self._attached_images:
  1643. return []
  1644. badges = _format_image_attachment_badges(self._attached_images, self._image_counter)
  1645. return [("class:image-badge", f" {badges} ")]
  1646. def _tui_voice_status_fragments(self):
  1647. return self._get_voice_status_fragments()
  1648. def _tui_spinner_text(self):
  1649. spinner_line = self._render_spinner_text()
  1650. return [('class:hint', spinner_line)] if spinner_line else []
  1651. def _tui_spinner_height(self):
  1652. return self._spinner_widget_height()
  1653. def _tui_hint_height(self):
  1654. if (
  1655. self._sudo_state or self._secret_state or self._approval_state or self._connection_state
  1656. or self._slash_confirm_state or self._clarify_state or self._command_running):
  1657. return 1
  1658. # Keep a spacer while the agent runs on roomy terminals; reclaim the row on narrow screens.
  1659. return self._agent_spacer_height()
  1660. def _tui_init_run_state(self):
  1661. """Reset the per-run REPL state (queues, modal states, voice state, config watcher)."""
  1662. from hermes_cli.config_backend import config_version_or_none
  1663. self._agent_running = False
  1664. self._pending_input = queue.Queue() # normal input (commands + new queries)
  1665. self._interrupt_queue = queue.Queue() # messages typed while the agent is running
  1666. # Seeded -q handoff: main() can't put directly into _pending_input (this reinit would
  1667. # discard it), so the seeded first message rides in on an attribute and is enqueued here.
  1668. _seed_msg = getattr(self, "_seeded_first_message", None)
  1669. if _seed_msg is not None:
  1670. self._seeded_first_message = None
  1671. self._pending_input.put(_seed_msg)
  1672. # See constructor note; mirrored for the run() path that skips the earlier __init__ branch.
  1673. self._last_turn_interrupted = False
  1674. self._should_exit = False
  1675. self._last_ctrl_c_time = 0 # double Ctrl+C force-exit tracking
  1676. # No PluginManager._cli_ref: plugins load in the gateway, not here (PLG-7).
  1677. # Config file watcher — detect mcp_servers changes and auto-reload.
  1678. from hermes_cli.config import get_config_path as _get_config_path
  1679. _cfg_path = _get_config_path()
  1680. self._config_sig: tuple | None = config_version_or_none(_cfg_path)
  1681. self._config_mcp_servers: dict = self.config.get("mcp_servers") or {}
  1682. self._last_config_check: float = 0.0 # monotonic time of last check
  1683. # Modal overlay states: each is a dict (with a response_queue) while active, else None.
  1684. # The prompt_toolkit UI switches to the matching selection/input mode.
  1685. self._clarify_state = None
  1686. self._clarify_freetext = False # True when the user chose "Other" and is typing
  1687. self._clarify_deadline = 0 # monotonic timeout
  1688. self._sudo_state = None
  1689. self._sudo_deadline = 0
  1690. self._modal_input_snapshot = None
  1691. self._approval_state = None
  1692. self._approval_deadline = 0
  1693. self._approval_lock = threading.Lock() # serialize concurrent approval prompts (delegation race)
  1694. # Destructive slash-command confirmations (/new, /clear, /undo) are answered through the
  1695. # composer, not raw input(), so the labels stay visible and Enter can't EOF the app.
  1696. self._slash_confirm_state = None
  1697. self._slash_confirm_deadline = 0
  1698. self._command_running = False
  1699. self._command_blocks_input = False
  1700. self._command_status = ""
  1701. self._secret_state = None # skill-setup secret capture
  1702. self._secret_deadline = 0
  1703. self._connection_state = None
  1704. self._attached_images: list[Path] = [] # clipboard image attachments
  1705. self._image_counter = 0
  1706. # Voice mode state (protected by _voice_lock for cross-thread access).
  1707. self._voice_lock = threading.Lock()
  1708. self._voice_mode = False
  1709. self._voice_tts = False
  1710. self._voice_recorder = None # AudioRecorder (lazy init)
  1711. self._voice_recording = False
  1712. self._voice_processing, self._voice_live_text = False, "" # STT in progress; live partial text
  1713. self._voice_continuous = False # auto-restart after the agent responds
  1714. self._voice_tts_done = threading.Event() # TTS playback finished
  1715. self._voice_tts_done.set() # initially "done" (no TTS pending)
  1716. self._voice_tts_stop = None # active streaming pipeline's stop event
  1717. self._voice_barge_capture = threading.Event() # barge monitor is capturing the interruption
  1718. self._voice_last_tts_text = "" # most recently spoken TTS text (echo guard, #75780)
  1719. self._voice_barge_phase = None # "generation" or "playback" phase of the last barge trip
  1720. if os.environ.get("HERMES_DEFER_AGENT_STARTUP") != "1":
  1721. self._install_tool_callbacks()
  1722. def _tui_build_key_bindings(self):
  1723. """Build the prompt_toolkit KeyBindings for the REPL input area.
  1724. Registration ORDER matters: for the same key, prompt_toolkit picks the last matching
  1725. binding, so the generic handlers (Tab, history Up/Down) are registered before or after
  1726. their filtered modal overrides deliberately.
  1727. """
  1728. from cli import (
  1729. CLI_CONFIG,
  1730. _bind_prompt_submit_keys,
  1731. _cli_multiline_shortcuts_enabled,
  1732. _preserve_ctrl_enter_newline)
  1733. from prompt_toolkit.keys import Keys
  1734. kb = KeyBindings()
  1735. _multiline_shortcuts_enabled = _cli_multiline_shortcuts_enabled(self.config or CLI_CONFIG)
  1736. self._tui_multiline_shortcuts = _multiline_shortcuts_enabled
  1737. kb.add(Keys.Ignore, eager=True)(self._tui_handle_ignored_terminal_sequence)
  1738. _bind_prompt_submit_keys(
  1739. kb, self._tui_handle_enter, multiline_shortcuts_enabled=_multiline_shortcuts_enabled)
  1740. kb.add('escape', 'enter')(self._tui_insert_newline)
  1741. # Ctrl+J inserts a newline (Claude Code / Codex / OpenCode). Windows Terminal delivers
  1742. # Ctrl+Enter as the same c-j code. display.cli_multiline_shortcuts: false restores legacy
  1743. # c-j submit on unusual POSIX PTYs where Enter is LF.
  1744. if _multiline_shortcuts_enabled or _preserve_ctrl_enter_newline():
  1745. kb.add('c-j')(self._tui_insert_newline)
  1746. self._tui_bind_editor_and_stash(kb)
  1747. self._tui_bind_overlay_navigation(kb)
  1748. # History: the TextArea is multiline so Up/Down alone only move the cursor;
  1749. # Buffer.auto_up/auto_down browse history when on the first/last line.
  1750. _normal_input = Condition(
  1751. lambda: not self._clarify_state and not self._approval_state and not self._slash_confirm_state
  1752. and not self._sudo_state and not self._secret_state and not self._connection_state
  1753. and not self._model_picker_state and not self._command_palette_state)
  1754. kb.add('up', filter=_normal_input)(self._tui_history_up)
  1755. kb.add('down', filter=_normal_input)(self._tui_history_down)
  1756. kb.add('c-l')(self._tui_handle_ctrl_l)
  1757. kb.add('c-c')(self._tui_handle_ctrl_c)
  1758. # No Ctrl+Shift+C binding: terminal emulators intercept it before stdin, and
  1759. # prompt_toolkit's key parser doesn't recognise 'c-S-c' anyway (#19884/#19895).
  1760. kb.add('c-q')(self._tui_handle_ctrl_q)
  1761. kb.add('c-d')(self._tui_handle_ctrl_d)
  1762. _modal_prompt_active = Condition(
  1763. lambda: bool(self._secret_state or self._sudo_state or self._slash_confirm_state
  1764. or self._connection_state))
  1765. kb.add('escape', filter=_modal_prompt_active, eager=True)(self._tui_handle_escape_modal)
  1766. kb.add('escape', 'escape', filter=~_modal_prompt_active)(self._tui_handle_double_escape)
  1767. kb.add('c-z')(self._tui_handle_ctrl_z)
  1768. kb.add(*self._tui_voice_record_key_sequence())(self._tui_handle_voice_record)
  1769. kb.add(Keys.BracketedPaste, eager=True)(self._tui_handle_paste)
  1770. kb.add('c-v')(self._tui_handle_ctrl_v)
  1771. kb.add('escape', 'v')(self._tui_handle_alt_v)
  1772. from hermes_cli.cli_subagent_monitor import modal_prompt_active, open_monitor, toggle_dock
  1773. for key in ('c-t', 'f6'):
  1774. kb.add(key, filter=Condition(lambda: not modal_prompt_active(self)))(
  1775. lambda event: open_monitor(self))
  1776. # F7 is retained for terminals that forward the function-key sequence;
  1777. # Ctrl+R is the portable fallback because macOS often reserves F7 for
  1778. # a hardware control unless Fn/globe is held.
  1779. kb.add('c-r', filter=Condition(lambda: not modal_prompt_active(self)))(
  1780. lambda event: toggle_dock(self))
  1781. kb.add('f7', filter=Condition(lambda: not modal_prompt_active(self)))(
  1782. lambda event: toggle_dock(self))
  1783. return kb
  1784. def _tui_bind_editor_and_stash(self, kb) -> None:
  1785. # VSCode/Cursor bind Ctrl+G to "Find Next" so it never reaches the terminal; Alt+G is
  1786. # unbound there and arrives as ('escape', 'g') — register it as a fallback.
  1787. _editor_filter = Condition(
  1788. lambda: not self._clarify_state and not self._approval_state
  1789. and not self._sudo_state and not self._secret_state and not self._connection_state)
  1790. kb.add('c-g', filter=_editor_filter)(
  1791. kb.add('escape', 'g', filter=_editor_filter)(self._tui_handle_open_in_editor))
  1792. # Ctrl+S prompt stash: park a draft, send something else, bring it back. Suppressed while
  1793. # a modal prompt owns the composer so Ctrl+S can't stash a password.
  1794. _stash_filter = Condition(
  1795. lambda: not self._clarify_state and not self._approval_state and not self._sudo_state
  1796. and not self._secret_state and not self._connection_state and not self._slash_confirm_state
  1797. and not self._model_picker_state
  1798. )
  1799. _stash_panel_filter = Condition(lambda: self._prompt_stash.panel_open and bool(len(self._prompt_stash)))
  1800. kb.add('c-s', filter=_stash_filter)(self._tui_handle_prompt_stash)
  1801. kb.add('up', filter=_stash_panel_filter, eager=True)(self._tui_handle_stash_panel_up)
  1802. kb.add('down', filter=_stash_panel_filter, eager=True)(self._tui_handle_stash_panel_down)
  1803. kb.add('enter', filter=_stash_panel_filter, eager=True)(self._tui_handle_stash_panel_restore)
  1804. kb.add('d', filter=_stash_panel_filter, eager=True)(
  1805. kb.add('D', filter=_stash_panel_filter, eager=True)(self._tui_handle_stash_panel_delete)
  1806. )
  1807. kb.add('escape', filter=_stash_panel_filter, eager=True)(self._tui_handle_stash_panel_close)
  1808. kb.add('tab', eager=True)(self._tui_handle_tab)
  1809. def _tui_bind_overlay_navigation(self, kb) -> None:
  1810. """Clarify / approval / slash-confirm / model picker / command palette navigation keys."""
  1811. _clarify_nav = Condition(lambda: bool(self._clarify_state) and not self._clarify_freetext)
  1812. kb.add('up', filter=_clarify_nav)(self._tui_clarify_up)
  1813. kb.add('down', filter=_clarify_nav)(self._tui_clarify_down)
  1814. _connection_nav = Condition(lambda: bool(self._connection_state))
  1815. kb.add('up', filter=_connection_nav)(self._tui_connection_up)
  1816. kb.add('down', filter=_connection_nav)(self._tui_connection_down)
  1817. kb.add('left', filter=_connection_nav)(self._tui_connection_side)
  1818. kb.add('right', filter=_connection_nav)(self._tui_connection_side)
  1819. # Multi-select: Space toggles the checkbox under the cursor.
  1820. kb.add('space', filter=Condition(
  1821. lambda: bool(self._clarify_state) and not self._clarify_freetext
  1822. and self._clarify_state.get("multi_select")
  1823. ))(self._tui_clarify_toggle)
  1824. # Batch clarify: Tab / Shift-Tab cycle the active question (any-order answering; moving
  1825. # onto an answered question lets the user re-answer it). Registered after the generic
  1826. # tab handler so this filtered binding wins while the batch panel is open.
  1827. kb.add('tab', filter=_clarify_nav, eager=True)(self._tui_clarify_batch_tab)
  1828. kb.add('s-tab', filter=_clarify_nav, eager=True)(self._tui_clarify_batch_backtab)
  1829. # Number keys: 1-9 select items 0-8, 0 selects item 9 (10th).
  1830. for _num in range(10):
  1831. _idx = 9 if _num == 0 else _num - 1
  1832. kb.add(str(_num), filter=_clarify_nav)(self._tui_make_clarify_number_handler(_idx))
  1833. _approval = Condition(lambda: bool(self._approval_state))
  1834. _slash_confirm = Condition(lambda: bool(self._slash_confirm_state))
  1835. _picker = Condition(lambda: bool(self._model_picker_state))
  1836. kb.add('up', filter=_approval)(self._tui_approval_up)
  1837. kb.add('down', filter=_approval)(self._tui_approval_down)
  1838. kb.add('up', filter=_slash_confirm)(self._tui_slash_confirm_up)
  1839. kb.add('down', filter=_slash_confirm)(self._tui_slash_confirm_down)
  1840. kb.add('up', filter=_picker)(self._tui_model_picker_up)
  1841. kb.add('down', filter=_picker)(self._tui_model_picker_down)
  1842. def _model_picker_typing_active() -> bool:
  1843. # Type-to-filter is only live on the model stage (concrete list).
  1844. st = self._model_picker_state
  1845. return bool(st) and st.get("stage") == "model"
  1846. _picker_typing = Condition(_model_picker_typing_active)
  1847. for _ch in _TYPING_CHARS:
  1848. kb.add(_ch, filter=_picker_typing)(self._tui_make_model_filter_char_handler(_ch))
  1849. kb.add('backspace', filter=_picker_typing)(self._tui_model_picker_filter_backspace)
  1850. kb.add('escape', filter=_picker, eager=True)(self._tui_model_picker_escape)
  1851. _palette = Condition(lambda: bool(self._command_palette_state))
  1852. kb.add('c-p', filter=Condition(
  1853. lambda: not self._command_palette_state and not self._model_picker_state and not self._clarify_state
  1854. and not self._approval_state and not self._slash_confirm_state and not self._sudo_state
  1855. and not self._secret_state and not self._connection_state
  1856. ))(self._tui_open_command_palette)
  1857. kb.add('up', filter=_palette)(self._tui_command_palette_up)
  1858. kb.add('down', filter=_palette)(self._tui_command_palette_down)
  1859. kb.add('enter', filter=_palette)(self._tui_command_palette_enter)
  1860. kb.add('backspace', filter=_palette)(self._tui_command_palette_backspace)
  1861. kb.add('escape', filter=_palette, eager=True)(self._tui_command_palette_escape)
  1862. for _pch in _TYPING_CHARS:
  1863. kb.add(_pch, filter=_palette)(self._tui_make_palette_char_handler(_pch))
  1864. for _num in range(10):
  1865. _idx = 9 if _num == 0 else _num - 1
  1866. kb.add(str(_num), filter=_approval)(self._tui_make_approval_number_handler(_idx))
  1867. for _num in range(10):
  1868. _idx = 9 if _num == 0 else _num - 1
  1869. kb.add(str(_num), filter=_slash_confirm)(self._tui_make_slash_confirm_number_handler(_idx))
  1870. def _tui_voice_record_key_sequence(self) -> tuple:
  1871. """Resolve the push-to-talk key (voice.record_key, default Ctrl+B) to a prompt_toolkit
  1872. key sequence and cache the UI label.
  1873. Config spellings (ctrl/control/alt/option/opt) are normalized to c-x / a-x so the same
  1874. value binds identically in TUI and CLI. super/win/windows silently fall back to the
  1875. default (prompt_toolkit has no super modifier) — warn so users notice the split. The
  1876. label cache uses the same ``_raw_key`` that drives the binding, so status/placeholder/
  1877. recording-hint renders can never drift from the live key even if the config is edited
  1878. mid-session.
  1879. """
  1880. from cli import logger
  1881. # Voice push-to-talk key: configurable via config.yaml (voice.record_key) Default: Ctrl+B (avoids
  1882. # conflict with Ctrl+R readline reverse-search). Config spellings (ctrl/control/alt/option/opt) are
  1883. # normalized to prompt_toolkit's c-x / a-x format via
  1884. # ``normalize_voice_record_key_for_prompt_toolkit`` so the same config value binds identically in
  1885. # the TUI and CLI (review round-9 on #19835). ``super``/``win``/``windows`` configs silently
  1886. # fall back to the default here since prompt_toolkit has no super modifier — log a warning so users
  1887. # notice the TUI/CLI split instead of a silent mismatch (round-11).
  1888. _raw_key: object = "ctrl+b"
  1889. try:
  1890. from hermes_cli.config import load_config
  1891. from hermes_cli.voice import (
  1892. normalize_voice_record_key_for_prompt_toolkit,
  1893. pt_key_to_sequence,
  1894. voice_record_key_from_config)
  1895. _raw_key = voice_record_key_from_config(load_config())
  1896. _voice_key = normalize_voice_record_key_for_prompt_toolkit(_raw_key)
  1897. if (
  1898. isinstance(_raw_key, str)
  1899. and _raw_key.strip().lower().split("+", 1)[0].strip() in {"super", "win", "windows"}
  1900. and _voice_key == "c-b"):
  1901. logger.warning(
  1902. "voice.record_key %r uses a TUI-only modifier (super/win); "
  1903. "CLI fell back to Ctrl+B. Use ctrl+<key> or alt+<key> for "
  1904. "cross-runtime parity.",
  1905. _raw_key)
  1906. except Exception:
  1907. _voice_key = "c-b"
  1908. # Cache the UI label here — same ``_raw_key`` that drives the prompt_toolkit binding below. Every
  1909. # status / placeholder / recording-hint render reads this cached value so display can never drift
  1910. # from the live keybinding even if the user edits voice.record_key mid-session (review round-13 on
  1911. # #19835).
  1912. self.set_voice_record_key_cache(_raw_key)
  1913. return pt_key_to_sequence(_voice_key)
  1914. def _tui_overlay_widget(self, fragments_fn, state_attr: str):
  1915. """Wrapped, auto-sized panel shown while ``self.<state_attr>`` is not None."""
  1916. return ConditionalContainer(
  1917. Window(FormattedTextControl(fragments_fn), wrap_lines=True),
  1918. filter=Condition(lambda: getattr(self, state_attr) is not None))
  1919. def _tui_build_layout(self, kb):
  1920. """Build the TUI widgets, Layout and Style; registers wrapper keybindings on ``kb``."""
  1921. cli_ref = self
  1922. from hermes_cli.cli_subagent_monitor import install_dock
  1923. install_dock(self)
  1924. input_area = self._tui_build_input_area()
  1925. spinner_widget = Window(
  1926. content=FormattedTextControl(self._tui_spinner_text),
  1927. height=self._tui_spinner_height,
  1928. wrap_lines=True)
  1929. # Petdex mascot — right-aligned Kitty placeholder or half-block sprite above the prompt;
  1930. # height 0 when no pet is enabled. The animation thread queues virtual Kitty frames;
  1931. # after_render writes them out-of-band while prompt_toolkit owns the placeholder grid.
  1932. self._pet_widget = Window(
  1933. content=FormattedTextControl(self._pet_fragments),
  1934. height=self._pet_widget_height,
  1935. align=WindowAlign.RIGHT)
  1936. # Hint line above the input: only for interactive prompts that need extra instructions
  1937. # (sudo countdown, approval navigation, clarify); the agent-running hint is the placeholder.
  1938. spacer = Window(content=FormattedTextControl(self._tui_hint_text), height=self._tui_hint_height)
  1939. clarify_widget = self._tui_overlay_widget(self._get_clarify_display_fragments, "_clarify_state")
  1940. sudo_widget = self._tui_overlay_widget(self._get_sudo_display_fragments, "_sudo_state")
  1941. secret_widget = self._tui_overlay_widget(self._get_secret_display_fragments, "_secret_state")
  1942. connection_widget = self._tui_overlay_widget(
  1943. self._get_connection_display_fragments, "_connection_state")
  1944. approval_widget = self._tui_overlay_widget(self._get_approval_display_fragments, "_approval_state")
  1945. slash_confirm_widget = self._tui_overlay_widget(
  1946. self._get_slash_confirm_display_fragments, "_slash_confirm_state")
  1947. model_picker_widget = self._tui_overlay_widget(
  1948. self._get_model_picker_display_fragments, "_model_picker_state")
  1949. command_palette_widget = self._tui_overlay_widget(
  1950. self._get_command_palette_display_fragments, "_command_palette_state")
  1951. # Rules above/below the input; narrow terminals hide the bottom one to recover a row.
  1952. input_rule_top = Window(
  1953. char='─', height=lambda: cli_ref._tui_input_rule_height("top"), style='class:input-rule',
  1954. )
  1955. input_rule_bot = Window(
  1956. char='─', height=lambda: cli_ref._tui_input_rule_height("bottom"), style='class:input-rule',
  1957. )
  1958. if getattr(self, "_modern_layout", False):
  1959. from hermes_cli.cli_modern_layout import modern_input_rules
  1960. input_rule_top, input_rule_bot = modern_input_rules(self, kb)
  1961. image_bar = Window(
  1962. content=FormattedTextControl(self._tui_image_bar_fragments),
  1963. height=Condition(lambda: bool(cli_ref._attached_images)))
  1964. voice_status_bar = ConditionalContainer(
  1965. Window(FormattedTextControl(self._tui_voice_status_fragments), height=1),
  1966. filter=Condition(lambda: cli_ref._voice_mode))
  1967. status_bar = ConditionalContainer(
  1968. Window(
  1969. content=FormattedTextControl(lambda: cli_ref._get_status_bar_fragments()),
  1970. height=1,
  1971. # wrap_lines=False: fragments overflowing the width must never wrap onto a second
  1972. # row (looked like a duplicated status bar on long SSH sessions with stale
  1973. # shutil sizes). _get_status_bar_fragments reads prompt_toolkit's own width, so
  1974. # this is the belt-and-suspenders guard.
  1975. wrap_lines=False),
  1976. filter=Condition(
  1977. lambda: cli_ref._status_bar_visible
  1978. and not getattr(cli_ref, "_status_bar_suppressed_after_resize", False)))
  1979. # Stash browse panel — just above the status bar, Ctrl+S on an empty composer with 2+ drafts.
  1980. self._stash_panel_widget = ConditionalContainer(
  1981. Window(FormattedTextControl(self._get_stash_panel_display_fragments), wrap_lines=False),
  1982. filter=Condition(lambda: cli_ref._prompt_stash.panel_open and bool(len(cli_ref._prompt_stash))),
  1983. )
  1984. self._register_extra_tui_keybindings(kb, input_area=input_area)
  1985. layout = Layout(FooterSplit(self._build_tui_layout_children(
  1986. sudo_widget=sudo_widget,
  1987. secret_widget=secret_widget,
  1988. connection_widget=connection_widget,
  1989. approval_widget=approval_widget,
  1990. slash_confirm_widget=slash_confirm_widget,
  1991. clarify_widget=clarify_widget,
  1992. model_picker_widget=model_picker_widget,
  1993. command_palette_widget=command_palette_widget,
  1994. spinner_widget=spinner_widget,
  1995. spacer=spacer,
  1996. status_bar=status_bar,
  1997. input_rule_top=input_rule_top,
  1998. image_bar=image_bar,
  1999. input_area=input_area,
  2000. input_rule_bot=input_rule_bot,
  2001. voice_status_bar=voice_status_bar,
  2002. completions_menu=CompletionsMenu(max_height=12, scroll_offset=1))))
  2003. self._tui_set_base_style()
  2004. return layout, PTStyle.from_dict(self._build_tui_style_dict())
  2005. def _tui_build_input_area(self):
  2006. """Multi-line prompt TextArea with slash completion, paste-collapse tracking and
  2007. placeholder/password processors."""
  2008. from cli import _estimate_tui_input_height
  2009. from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
  2010. from prompt_toolkit.completion import ThreadedCompleter
  2011. cli_ref = self
  2012. def get_prompt():
  2013. return cli_ref._get_tui_prompt_fragments()
  2014. _completer = cli_slash_completer(self)
  2015. input_area = TextArea(
  2016. height=Dimension(min=1, max=8, preferred=1),
  2017. prompt=get_prompt,
  2018. style='class:input-area',
  2019. multiline=True,
  2020. wrap_lines=True,
  2021. read_only=Condition(lambda: bool(cli_ref._command_blocks_input)),
  2022. history=FileHistory(str(self._history_file)),
  2023. # The completer does blocking work (fuzzy @-file indexing shells out to rg/fd with a 2s timeout;
  2024. # path completion hits os.listdir/stat), so complete_while_typing inline would stall the render
  2025. # loop per keystroke (WSL2/slow FS). ThreadedCompleter moves it off the UI event loop.
  2026. completer=ThreadedCompleter(_completer),
  2027. complete_while_typing=True,
  2028. auto_suggest=SlashCommandAutoSuggest(history_suggest=AutoSuggestFromHistory(), completer=_completer),
  2029. )
  2030. # Keep prompt_toolkit on its simple tempfile path: buffer.tempfile = "prompt.md" takes
  2031. # the complex-tempfile branch that re-mkdir()s the mkdtemp() dir and raises EEXIST.
  2032. input_area.buffer.tempfile_suffix = '.md'
  2033. def _input_height():
  2034. # Accounts for explicit newlines AND visual wrapping so the area fits its content.
  2035. try:
  2036. from prompt_toolkit.application import get_app
  2037. doc = input_area.buffer.document
  2038. try:
  2039. terminal_columns = get_app().output.get_size().columns
  2040. except Exception:
  2041. terminal_columns = shutil.get_terminal_size((80, 24)).columns
  2042. return _estimate_tui_input_height(doc.lines, self._get_tui_prompt_text(), terminal_columns)
  2043. except Exception:
  2044. return 1
  2045. input_area.window.height = _input_height
  2046. # Paste collapsing state (large pastes are saved to a file and replaced by a placeholder).
  2047. self._tui_paste_counter = 0
  2048. self._tui_prev_text_len = 0
  2049. self._tui_prev_newline_count = 0
  2050. self._tui_paste_just_collapsed = False
  2051. self._skip_paste_collapse = False
  2052. input_area.buffer.on_text_changed += self._tui_on_text_changed
  2053. # Mask input with '*' while a sudo/secret prompt is active.
  2054. input_area.control.input_processors.append(ConditionalProcessor(
  2055. PasswordProcessor(),
  2056. filter=Condition(lambda: (bool(cli_ref._sudo_state)
  2057. and (cli_ref._sudo_state.get("vault_save") or {}).get("step") != "identifier"
  2058. and not cli_ref._sudo_state.get("vault_code"))
  2059. or bool(cli_ref._secret_state)
  2060. or (bool(cli_ref._connection_state)
  2061. and cli_ref._connection_active_field_is_secret()))))
  2062. class _PlaceholderProcessor(Processor):
  2063. """Render grayed-out placeholder text inside the input when empty."""
  2064. def __init__(self, get_text):
  2065. self._get_text = get_text
  2066. def apply_transformation(self, ti):
  2067. if not ti.document.text and ti.lineno == 0:
  2068. text = self._get_text()
  2069. if text:
  2070. # Append after existing fragments (preserves the ❯ prompt).
  2071. return Transformation(fragments=ti.fragments + [('class:placeholder', text)])
  2072. return Transformation(fragments=ti.fragments)
  2073. input_area.control.input_processors.append(_PlaceholderProcessor(self._tui_placeholder_text))
  2074. return input_area
  2075. def _tui_set_base_style(self):
  2076. """Populate ``self._tui_style_base`` (skin-aware defaults the style dict is built from)."""
  2077. self._tui_style_base = {
  2078. # Empty input/prompt styles inherit the terminal's own fg/bg so typed text is readable
  2079. # in both light and dark schemes (a hardcoded near-white was invisible on light).
  2080. 'input-area': '',
  2081. 'placeholder': '#888888 italic',
  2082. 'prompt': '',
  2083. 'prompt-working': '#888888 italic',
  2084. 'hint': '#888888 italic',
  2085. 'status-bar': 'bg:#1a1a2e #C0C0C0',
  2086. 'status-bar-strong': 'bg:#1a1a2e #FFD700 bold',
  2087. 'status-bar-dim': 'bg:#1a1a2e #8B8682',
  2088. 'status-bar-good': 'bg:#1a1a2e #8FBC8F bold',
  2089. 'status-bar-warn': 'bg:#1a1a2e #FFD700 bold',
  2090. 'status-bar-bad': 'bg:#1a1a2e #FF8C00 bold',
  2091. 'status-bar-critical': 'bg:#1a1a2e #FF6B6B bold',
  2092. 'status-bar-yolo': 'bg:#1a1a2e #FF4444 bold',
  2093. 'status-bar-session-title': 'bg:#FFD700 #1a1a2e bold',
  2094. 'input-rule': '#CD7F32',
  2095. 'image-badge': '#87CEEB bold',
  2096. 'completion-menu': 'bg:#1a1a2e #FFF8DC',
  2097. 'completion-menu.completion': 'bg:#1a1a2e #FFF8DC',
  2098. 'completion-menu.completion.current': 'bg:#333355 #FFD700',
  2099. 'completion-menu.meta.completion': 'bg:#1a1a2e #888888',
  2100. 'completion-menu.meta.completion.current': 'bg:#333355 #FFBF00',
  2101. 'clarify-border': '#CD7F32',
  2102. 'clarify-title': '#FFD700 bold',
  2103. 'clarify-question': '#FFF8DC bold',
  2104. 'clarify-choice': '#AAAAAA',
  2105. 'clarify-selected': '#FFD700 bold',
  2106. 'clarify-active-other': '#FFD700 italic',
  2107. 'clarify-answer': '#98FB98',
  2108. 'clarify-countdown': '#CD7F32',
  2109. 'sudo-prompt': '#FF6B6B bold',
  2110. 'sudo-border': '#CD7F32',
  2111. 'sudo-title': '#FF6B6B bold',
  2112. 'sudo-text': '#FFF8DC',
  2113. 'approval-border': '#CD7F32',
  2114. 'approval-title': '#FF8C00 bold',
  2115. 'approval-desc': '#FFF8DC bold',
  2116. 'approval-cmd': '#AAAAAA italic',
  2117. 'approval-choice': '#AAAAAA',
  2118. 'approval-selected': '#FFD700 bold',
  2119. 'voice-prompt': '#87CEEB',
  2120. 'voice-recording': '#FF4444 bold',
  2121. 'voice-processing': '#FFA500 italic',
  2122. 'voice-status': 'bg:#1a1a2e #87CEEB',
  2123. 'voice-status-recording': 'bg:#1a1a2e #FF4444 bold'}