cli_modern_layout.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. """Glyph-grammar transcript and bottom-anchored chrome for the classic CLI (``display.cli_layout``).
  2. Every row this module prints into scrollback is width-independent (a column-0 glyph, no boxes, no
  3. full-width rules), so resizing the terminal cannot re-wrap and garble what is already printed.
  4. Width-dependent chrome (the composer's top rule and the footer) lives only in prompt_toolkit's live
  5. region, which is redrawn on every resize. ``display.cli_layout: classic`` restores the boxed look.
  6. """
  7. from __future__ import annotations
  8. import logging
  9. import os
  10. import re
  11. import time
  12. from datetime import datetime
  13. from agent.i18n import t
  14. logger = logging.getLogger(__name__)
  15. _SPIN = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
  16. _RST, _BOLD, _DIM = "\x1b[0m", "\x1b[1m", "\x1b[2m"
  17. _RED = "\x1b[38;2;239;83;80m"
  18. def is_modern(cli) -> bool:
  19. return bool(getattr(cli, "_modern_layout", False))
  20. def layout_from_config(display: dict) -> bool:
  21. """True for the glyph layout (default); ``classic`` keeps the boxed transcript."""
  22. return str((display or {}).get("cli_layout", "modern") or "modern").strip().lower() != "classic"
  23. def busy_input_mode_from_config(display: dict) -> str:
  24. """``display.busy_input_mode``; unset interrupts in both layouts (Tab still queues in this one)."""
  25. return str((display or {}).get("busy_input_mode") or "interrupt").strip().lower()
  26. def _skin_hex(key: str, fallback: str) -> str:
  27. from hermes_cli.skin_engine import get_active_skin
  28. return get_active_skin().get_color(key, fallback) or fallback
  29. def _fg(hex_color: str, bold: bool = False) -> str:
  30. try:
  31. r, g, b = (int(hex_color.lstrip("#")[i:i + 2], 16) for i in (0, 2, 4))
  32. return f"\x1b[{'1;' if bold else ''}38;2;{r};{g};{b}m"
  33. except (ValueError, IndexError):
  34. return _BOLD if bold else ""
  35. def _brand_glyph() -> tuple[str, str]:
  36. """(glyph, name) from the skin's response label, e.g. ``" ☤ Hermes "`` → ("☤", "Hermes")."""
  37. from hermes_cli.skin_engine import get_active_skin
  38. label = get_active_skin().get_branding("response_label", " ☤ Hermes ")
  39. parts = label.split(None, 1)
  40. return (parts[0], parts[1].strip()) if len(parts) == 2 else ("☤", label.strip() or "Hermes")
  41. def prompt_glyph() -> str:
  42. from hermes_cli.skin_engine import get_active_skin
  43. return get_active_skin().get_branding("prompt_symbol", "❯").strip() or "❯"
  44. # ── transcript rows (printed into scrollback) ───────────────────────────────────────────────
  45. # Fixed width, not the terminal's: a 40-cell rule never re-wraps on resize (classic's user rule).
  46. _SEPARATOR_WIDTH = 40
  47. # Every block (user message, reasoning, answer) is framed the same way: blank line, bar, content,
  48. # bar, blank line. A closing bar leaves the blank line owed; whatever prints next (a tool row, the
  49. # turn footer) pays it, and an opening bar pays it with its own leading blank line.
  50. _GAP_PENDING = False
  51. def separator(accent: bool) -> str:
  52. """An opening bar: accent for user messages and answers, dim for reasoning. Every caller prints
  53. a blank line ahead of it, so it also settles a gap the previous block owes."""
  54. global _GAP_PENDING
  55. _GAP_PENDING = False
  56. color = _fg(_skin_hex("ui_accent", "#FFBF00")) if accent else _DIM
  57. return f"{color}{'─' * _SEPARATOR_WIDTH}{_RST}"
  58. def closing_separator(accent: bool) -> str:
  59. """The bar that closes a block; the blank line after it is owed to whatever prints next."""
  60. global _GAP_PENDING
  61. bar = separator(accent)
  62. _GAP_PENDING = True
  63. return bar
  64. def _take_gap() -> str:
  65. global _GAP_PENDING
  66. gap, _GAP_PENDING = ("\n" if _GAP_PENDING else ""), False
  67. return gap
  68. def user_echo_markup(text: str, accent_hex: str, ts_suffix: str = "") -> str:
  69. """Rich markup for a submitted single-line user message: ``❯ text``."""
  70. from rich.markup import escape
  71. return f"[bold {accent_hex}]{escape(prompt_glyph())}[/] [bold]{escape(text)}[/]{ts_suffix}"
  72. def answer_label(timestamp: str = "") -> str:
  73. """The rows that open an answer: the accent bar, then the skin's brand glyph + name."""
  74. glyph, name = _brand_glyph()
  75. stamp = f" {_DIM}{timestamp}{_RST}" if timestamp else ""
  76. return f"\n{separator(True)}\n{_fg(_skin_hex('ui_accent', '#FFBF00'), bold=True)}{glyph} {name}{_RST}{stamp}"
  77. def thought_line(seconds: float | None) -> str:
  78. """``∴ Thought for 3s`` (dim italic), closing a reasoning block. No title: the reasoning is
  79. printed right above, so any excerpt of it would repeat what the user just read."""
  80. took = t("cli.modern.thought_for", seconds=f"{max(seconds or 0.0, 0.0):.0f}") if seconds else t("cli.modern.thought")
  81. return f"\x1b[2;3m∴ {took}{_RST}"
  82. _REASONING_PREVIEW_LINES = 10 # classic's post-hoc reasoning box shows this many unless /reasoning full
  83. def reasoning_text_line(line: str) -> str:
  84. """One streamed reasoning line: dim, no frame (the dim bar above opens the block)."""
  85. return f"{_DIM}{line}{_RST}"
  86. def thought_rows(seconds: float | None, text: str, full: bool) -> list[str]:
  87. """A reasoning block printed after the fact (no live stream): dim bar, its text (first 10
  88. lines unless ``full``, as classic), then the ``∴ Thought for 3s`` summary."""
  89. lines = (text or "").strip().splitlines()
  90. shown = lines if full or len(lines) <= _REASONING_PREVIEW_LINES else lines[:_REASONING_PREVIEW_LINES]
  91. rows = ["", separator(False), *(reasoning_text_line(line) for line in shown)]
  92. if len(shown) < len(lines):
  93. rows.append(f"{_DIM} {t('cli.chat.reasoning_more_lines', count=len(lines) - len(shown))}{_RST}")
  94. return [*rows, thought_line(seconds), closing_separator(False)]
  95. def completed_tool_line(cli, function_name: str, args: dict | None, duration: float, result=None,
  96. is_error: bool = False) -> str:
  97. """The scrollback line for a finished tool call in the active layout."""
  98. if is_modern(cli):
  99. return _take_gap() + tool_row(function_name, args, duration, result, is_error)
  100. from agent.display import get_cute_tool_message
  101. return f" {get_cute_tool_message(function_name, args, duration, result=result)}"
  102. def tool_row(function_name: str, args: dict | None, duration: float, result=None, is_error: bool = False) -> str:
  103. """``📖 Read calc.py 0.2s`` / ``✗ $ pytest -q 0.4s [exit 1]`` — one row per completed call, led by
  104. the tool's emoji (the classic ``┊`` row's), or a red ``✗`` when that entry failed. A tool in
  105. ``NEUTRAL_FAILURE_TOOLS`` keeps its emoji and shows the reason dim."""
  106. from agent.display import get_tool_row_parts, is_neutral_failure
  107. rows = get_tool_row_parts(function_name, args or {}, result, is_error=bool(is_error))
  108. neutral = is_neutral_failure(function_name, result)
  109. out = []
  110. for index, (emoji, verb, detail, suffix) in enumerate(rows):
  111. verb = (verb or function_name).strip()
  112. mark = f"{_RED}✗{_RST}" if suffix is not None and not neutral else (emoji or "●")
  113. line = f"{mark} {_BOLD}{verb[:1].upper()}{verb[1:]}{_RST}"
  114. if detail:
  115. line += f" {detail}"
  116. if index == len(rows) - 1 and duration >= 0.1:
  117. line += f" {_DIM}{duration:.1f}s{_RST}"
  118. if suffix:
  119. line += f"{_DIM if neutral else _RED}{suffix}{_RST}"
  120. out.append(line)
  121. return "\n".join(out)
  122. _ACTIVE = False # one CLI per process; read by printers that get no CLI handle (gateway inline diffs)
  123. _ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
  124. _DIFF_FILE_RE = re.compile(r"^a/(.+?) → b/(.+)$")
  125. def set_active(enabled: bool) -> None:
  126. global _ACTIVE
  127. _ACTIVE = bool(enabled)
  128. def _display_path(path: str) -> str:
  129. path = path[1:] if path.startswith("//") else path
  130. cwd = os.getenv("TERMINAL_CWD") or os.getcwd()
  131. try:
  132. rel = os.path.relpath(path, cwd) if os.path.isabs(path) else path
  133. except ValueError:
  134. return path
  135. return path if rel.startswith("..") else rel
  136. def gutter_print(print_fn):
  137. """Wrap a line printer so a diff hangs under its tool row behind a dim ``│``: the ``review
  138. diff`` header is dropped and ``a/<abs> → b/<abs>`` collapses to one cwd-relative path."""
  139. header = _ANSI_RE.sub("", t("display.diff.review_header")).strip()
  140. def _print(text):
  141. for line in str(text).split("\n"):
  142. plain = _ANSI_RE.sub("", line).strip()
  143. if plain == header:
  144. continue
  145. match = _DIFF_FILE_RE.match(plain)
  146. if match:
  147. old, new = _display_path(match.group(1)), _display_path(match.group(2))
  148. line = f"{_BOLD}{new if old == new else f'{old} → {new}'}{_RST}"
  149. print_fn(f"{_DIM}│{_RST} {line}" if plain else f"{_DIM}│{_RST}")
  150. return _print
  151. def diff_printer(print_fn):
  152. """``print_fn`` with the gutter when the glyph layout is active in this process."""
  153. return gutter_print(print_fn) if _ACTIVE else print_fn
  154. def turn_footer(summary: str) -> str:
  155. """``─ 12.4s · read 3 files · edited 1 file +4 -0 · 7:02 AM`` closing each turn."""
  156. body = summary.lstrip("⋯ ").strip()
  157. clock = datetime.now().strftime("%-I:%M %p") if os.name != "nt" else datetime.now().strftime("%I:%M %p")
  158. return _take_gap() + (f"{_DIM}─ {body} · {clock}{_RST}" if body else f"{_DIM}─ {clock}{_RST}")
  159. # ── live region (prompt_toolkit fragments, redrawn every frame) ─────────────────────────────
  160. def _cwd_label() -> str:
  161. cwd = os.getenv("TERMINAL_CWD") or os.getcwd()
  162. home = os.path.expanduser("~")
  163. short = "~" + cwd[len(home):] if cwd == home or cwd.startswith(home + os.sep) else cwd
  164. from hermes_cli.status_bar_git import current_git_branch
  165. branch = current_git_branch(cwd)
  166. return f"{short} ({branch})" if branch else short
  167. def activity_text(cli) -> str:
  168. """What the agent is doing: the classic spinner's text (kaomoji face or tool emoji included)."""
  169. if getattr(cli, "_command_running", False):
  170. return str(getattr(cli, "_command_status", "") or "")
  171. text = str(getattr(cli, "_spinner_text", "") or "").strip()
  172. return text or (t("cli.modern.working") if getattr(cli, "_agent_running", False) else "")
  173. def _turn_elapsed(cli) -> str:
  174. started = getattr(cli, "_prompt_start_time", None)
  175. if started is None:
  176. return ""
  177. from cli import format_duration_compact
  178. return format_duration_compact(max(0.0, time.time() - float(started)))
  179. def rule_style() -> str:
  180. """Composer rules are quiet chrome: the skin's session border, not the accent."""
  181. return f"fg:{_skin_hex('session_border', '#8B8682')}"
  182. def _no_bg(frags: list) -> list:
  183. """The footer sits on the terminal background, not the classic status bar's fill."""
  184. return [(f"{style} bg:default".strip(), text) for style, text in frags]
  185. def _fit(cli, frags: list, width: int) -> list:
  186. used = sum(cli._status_bar_display_width(text) for _, text in frags)
  187. if used <= width:
  188. return frags
  189. plain = "".join(text for _, text in frags)
  190. return [(rule_style(), cli._trim_status_bar_text(plain, width))]
  191. def top_rule_fragments(cli) -> list:
  192. """``── ⠹ Running tests · 14s ─────────── calc helpers ─``: live status left, session title right."""
  193. width = max(10, cli._get_tui_terminal_width())
  194. rule, accent = rule_style(), f"fg:{_skin_hex('ui_accent', '#FFBF00')} bold"
  195. busy = getattr(cli, "_agent_running", False) or getattr(cli, "_command_running", False)
  196. left: list = []
  197. if busy:
  198. frame = _SPIN[int(time.monotonic() * 10) % len(_SPIN)]
  199. left = [(rule, "── "), (accent, frame + " "), ("", activity_text(cli))]
  200. # Classic's spinner suffix: turn time and the streamed-token count (``↓ 547 tok``).
  201. for extra in (_turn_elapsed(cli), cli._spinner_token_flow()):
  202. if extra:
  203. left.append(("class:status-bar-dim bg:default", f" · {extra}"))
  204. left.append((rule, " "))
  205. title = cli._get_status_bar_session_title()
  206. right = [(rule, " "), (f"fg:{_skin_hex('ui_label', '#DAA520')}", title), (rule, " ─")] if title else []
  207. used = sum(cli._status_bar_display_width(text) for _, text in left + right)
  208. if used >= width:
  209. right, used = [], sum(cli._status_bar_display_width(text) for _, text in left)
  210. return _fit(cli, left + [(rule, "─" * max(0, width - used))] + right, width)
  211. def hint_pairs(cli) -> list[tuple[str, str]]:
  212. """Keys that do something right now, for the footer's right half."""
  213. if any(getattr(cli, attr, None) for attr in (
  214. "_approval_state", "_clarify_state", "_sudo_state", "_secret_state", "_connection_state",
  215. "_slash_confirm_state", "_model_picker_state", "_command_palette_state")):
  216. return []
  217. if getattr(cli, "_agent_running", False):
  218. enter = {"steer": "steer", "queue": "queue"}.get(getattr(cli, "busy_input_mode", ""), "interrupt")
  219. pairs = [("enter", t(f"cli.modern.hint_{enter}"))]
  220. if enter != "queue":
  221. pairs.append(("tab", t("cli.modern.hint_queue")))
  222. return pairs + [("ctrl+c", t("cli.modern.hint_stop"))]
  223. return [("/", t("cli.modern.hint_commands")), ("@", t("cli.modern.hint_files")), ("!", t("cli.modern.hint_shell"))]
  224. def status_line_fragments(cli) -> list:
  225. """Footer under the composer: model · context gauge · cwd (branch) left, live key hints right.
  226. An explicit ``display.status_bar.fields`` list keeps the user's chosen segments on the left."""
  227. return _render_safely(_status_line_fragments, cli)
  228. def _render_safely(render, cli) -> list:
  229. """Boundary for prompt_toolkit render callbacks: a bad frame degrades to a bare line."""
  230. try:
  231. return render(cli)
  232. except Exception: # health: allow BLE001 -- a render callback must never take down the app frame
  233. logger.debug("%s failed", render.__name__, exc_info=True)
  234. return [("", f" {getattr(cli, 'model', '') or 'Hermes'}")]
  235. def _status_line_fragments(cli) -> list:
  236. """The classic bar's segments (same fields, same width tiers, same ``display.status_bar.fields``
  237. filter), then cwd (branch) and the live key hints when there is room."""
  238. width = max(10, cli._get_tui_terminal_width())
  239. dim, strong = "class:status-bar-dim", "class:status-bar-strong"
  240. snapshot = cli._get_status_bar_snapshot()
  241. field_set = cli._get_status_bar_field_set()
  242. def _on(name):
  243. return field_set is None or name in field_set
  244. left: list = []
  245. for seg in cli._status_bar_segments(snapshot, width, field_set, cli._is_session_yolo_active(), styled=True):
  246. if left:
  247. left.append((dim, " · "))
  248. left.extend(seg)
  249. stash = cli._prompt_stash.indicator() if _on("stash") and hasattr(cli, "_prompt_stash") else ""
  250. if stash: # a parked draft is never silently forgotten
  251. left += [(dim, " · "), (strong, stash)]
  252. battery = snapshot.get("battery_label") or "" # only set while /battery is on
  253. if battery and _on("battery"):
  254. left[0:0] = [("", " "), (cli._battery_status_style(snapshot.get("battery_category", "dim")), battery),
  255. (dim, " ·")]
  256. vim = cli._vim_mode_label()
  257. if vim:
  258. left += [(dim, " · "), (strong, vim)]
  259. right: list = []
  260. for key, text in hint_pairs(cli) if width >= 76 else []:
  261. if right:
  262. right.append((dim, " · "))
  263. right += [(strong, key), (dim, f" {text}")]
  264. used_left = sum(cli._status_bar_display_width(text) for _, text in left)
  265. used_right = sum(cli._status_bar_display_width(text) for _, text in right)
  266. room = width - used_left - used_right - 6
  267. if field_set is None and room >= 12: # cwd takes whatever the hints leave, trimmed from the left
  268. cwd = _cwd_label()
  269. cwd = cwd if len(cwd) <= room else "…" + cwd[-(room - 1):]
  270. left += [(dim, " · "), (dim, cwd)]
  271. used_left += 3 + cli._status_bar_display_width(cwd)
  272. if right and used_left + used_right + 2 > width:
  273. right, used_right = [], 0
  274. pad = [("", " " * max(1, width - used_left - used_right - 1))] if right else []
  275. return _no_bg(_fit(cli, left + pad + right + ([("", " ")] if right else []), width))
  276. def modern_input_rules(cli, kb):
  277. """The composer's rules for this layout (the top one carries live status), plus Tab-to-queue."""
  278. from prompt_toolkit.filters import Condition
  279. from prompt_toolkit.layout import FormattedTextControl, Window
  280. top = Window(FormattedTextControl(lambda: _render_safely(top_rule_fragments, cli)),
  281. height=lambda: cli._tui_input_rule_height("top"), wrap_lines=False)
  282. bottom = Window(char="─", height=lambda: cli._tui_input_rule_height("bottom"), style=rule_style)
  283. def _can_queue() -> bool:
  284. from prompt_toolkit.application import get_app
  285. from cli import _looks_like_slash_command
  286. from hermes_cli.cli_subagent_monitor import modal_prompt_active
  287. buf = get_app().current_buffer
  288. text = buf.text.strip()
  289. return bool(getattr(cli, "_agent_running", False) and text and buf.complete_state is None
  290. and not _looks_like_slash_command(text) and not text.startswith("!")
  291. and not modal_prompt_active(cli))
  292. @kb.add("tab", filter=Condition(_can_queue), eager=True)
  293. def _queue_while_busy(event):
  294. # Not _tui_handle_enter: its paste/continuation rules would turn this key into a newline.
  295. buf = event.app.current_buffer
  296. text, images = buf.text.strip(), list(cli._attached_images)
  297. cli._attached_images.clear()
  298. cli._tui_enter_while_busy(text, images, (text, images) if images else text, mode="queue")
  299. cli._inline_pastes(buf)
  300. buf.reset(append_to_history=True)
  301. event.app.invalidate()
  302. return top, bottom