cli_status_bar_mixin.py 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  1. """Status bar, spinner, turn-summary, pet pane, and prompt-stash rendering for the
  2. interactive CLI.
  3. Mixin bound onto ``HermesCLI`` via the MRO. cli.py-internal symbols are imported LAZILY
  4. inside each method (``from cli import ...``) — never at module load time (import cycle).
  5. """
  6. from __future__ import annotations
  7. import errno
  8. import shutil
  9. import threading
  10. import time
  11. from agent.i18n import t
  12. from agent import terminal_image
  13. from agent.pet import render as pet_render
  14. from hermes_cli.banner import _format_context_length
  15. from typing import Any, Dict, Optional
  16. _SB = "class:status-bar"
  17. _DIM = "class:status-bar-dim"
  18. _STRONG = "class:status-bar-strong"
  19. _AGENT_COUNTERS = (
  20. "session_input_tokens", "session_output_tokens", "session_cache_read_tokens",
  21. "session_cache_write_tokens", "session_prompt_tokens", "session_completion_tokens",
  22. "session_total_tokens", "session_api_calls")
  23. def _threshold_style(value, ladder, fallback: str) -> str:
  24. """First ``class:status-bar-<name>`` whose ``value >= bound`` in a descending ladder."""
  25. for bound, name in ladder:
  26. if value >= bound:
  27. return f"class:status-bar-{name}"
  28. return f"class:status-bar-{fallback}"
  29. def _finite(v):
  30. """Drop NaN / negative / absurd provider timings (e.g. -0.8s seen in logs)."""
  31. return None if v is None or v != v or v < 0 or v > 1e6 else v
  32. class CLIStatusBarMixin:
  33. """Status bar, spinner, turn-summary, pet pane, and prompt-stash rendering for the
  34. interactive CLI."""
  35. def _status_bar_context_style(self, percent_used: Optional[int]) -> str:
  36. if percent_used is None:
  37. return _DIM
  38. if percent_used >= 95:
  39. return "class:status-bar-critical"
  40. if percent_used > 80:
  41. return "class:status-bar-bad"
  42. return _threshold_style(percent_used, ((50, "warn"),), "good")
  43. def _cache_hit_rate(self, snapshot: dict, precision: int = 1) -> tuple[float, str] | None:
  44. """Return (cache_pct, label) or None without cache data. Prefers the baseline-delta pct
  45. from ``_get_status_bar_snapshot`` (resets on model switch / compression, so it reflects
  46. the *current* cache regime); falls back to the session-lifetime ratio."""
  47. delta_pct = snapshot.get("cache_hit_pct")
  48. if delta_pct is not None:
  49. return float(delta_pct), f"◎ {float(delta_pct):.{precision}f}%"
  50. cache_read = snapshot.get("session_cache_read_tokens", 0)
  51. prompt_total = snapshot.get("session_prompt_tokens", 0)
  52. if cache_read > 0 and prompt_total > 0:
  53. cache_pct = cache_read / prompt_total * 100
  54. return cache_pct, f"◎ {cache_pct:.{precision}f}%"
  55. return None
  56. def _cache_hit_rate_style(self, cache_pct: float) -> str:
  57. """Higher is better (opposite of context %)."""
  58. return _threshold_style(cache_pct, ((70, "good"), (40, "warn")), "bad")
  59. @staticmethod
  60. def _battery_status_style(category: str) -> str:
  61. return {
  62. "good": "class:status-bar-good",
  63. "warn": "class:status-bar-warn",
  64. "bad": "class:status-bar-bad",
  65. "critical": "class:status-bar-critical",
  66. }.get(category, _DIM)
  67. def _vim_mode_label(self) -> str:
  68. """Current vi editing mode as a short status-bar label; empty when vim mode is off
  69. or the application is not running yet."""
  70. if not getattr(self, "_vim_mode", False):
  71. return ""
  72. try:
  73. from prompt_toolkit.key_binding.vi_state import InputMode
  74. app = getattr(self, "_app", None)
  75. if app is None:
  76. return ""
  77. mode = app.vi_state.input_mode
  78. if mode in (InputMode.INSERT, InputMode.INSERT_MULTIPLE):
  79. return t("cli.status_bar.vim_insert")
  80. if mode == InputMode.REPLACE:
  81. return t("cli.status_bar.vim_replace")
  82. return t("cli.status_bar.vim_normal")
  83. except Exception:
  84. return ""
  85. def _handle_battery_command(self, cmd_original: str) -> None:
  86. """``/battery`` toggles, ``/battery on|off`` sets, ``/battery status`` reports the
  87. setting plus a live reading. Persisted to ``display.battery``."""
  88. from cli import save_config_value
  89. parts = (cmd_original or "").split()
  90. arg = parts[1].strip().lower() if len(parts) > 1 else ""
  91. try:
  92. from agent.battery import format_battery, read_battery
  93. reading = read_battery(use_cache=False)
  94. except Exception:
  95. reading = None
  96. def _detail(no_battery: str) -> str:
  97. if reading is None:
  98. return ""
  99. return f" — {format_battery(reading)}" if reading.available else f" — {no_battery}"
  100. if arg in ("status", "show"):
  101. state = t("cli.shared.label_on") if self._battery_visible else t("cli.shared.label_off")
  102. detail = _detail(t("cli.status_bar.battery_none"))
  103. if reading is not None and reading.available:
  104. detail = t("cli.status_bar.battery_currently", reading=format_battery(reading))
  105. self._console_print(f" {t('cli.status_bar.battery_state', state=state, detail=detail)}")
  106. return
  107. if arg in ("on", "true", "yes"):
  108. target = True
  109. elif arg in ("off", "false", "no"):
  110. target = False
  111. elif arg in ("", "toggle"):
  112. target = not self._battery_visible
  113. else:
  114. self._console_print(f" {t('cli.status_bar.battery_usage')}")
  115. return
  116. self._battery_visible = target
  117. save_config_value("display.battery", target)
  118. if target:
  119. self._console_print(
  120. f" {t('cli.status_bar.battery_on', detail=_detail(t('cli.status_bar.battery_none_nothing_shown')))}"
  121. )
  122. else:
  123. self._console_print(f" {t('cli.status_bar.battery_off')}")
  124. @staticmethod
  125. def _compression_count_style(count: int) -> str:
  126. return _threshold_style(count, ((10, "bad"), (5, "warn")), "dim")
  127. def _build_context_bar(self, percent_used: Optional[int], width: int = 10) -> str:
  128. safe_percent = max(0, min(100, percent_used or 0))
  129. filled = round((safe_percent / 100) * width)
  130. return f"[{('█' * filled) + ('░' * max(0, width - filled))}]"
  131. @staticmethod
  132. def _format_prompt_elapsed(
  133. prompt_start_time: Optional[float], prompt_duration: float, live: bool = False) -> str:
  134. """Per-prompt elapsed time. Always a string (``⏲ 0s`` on fresh start); seconds stay
  135. visible at every scale so it increments smoothly (``1m 59s → 2m → 2m 1s``). ⏱ while
  136. live, ⏲ frozen — width-1 glyphs (no variation selector) keep the bar aligned."""
  137. if prompt_start_time is None and prompt_duration == 0.0:
  138. return "⏲ 0s"
  139. if prompt_start_time is not None:
  140. elapsed = max(0.0, time.time() - prompt_start_time)
  141. else:
  142. elapsed = max(0.0, prompt_duration)
  143. days, remaining = divmod(elapsed, 86400)
  144. hours, remaining = divmod(remaining, 3600)
  145. minutes, seconds = int(remaining // 60), int(remaining % 60)
  146. days, hours = int(days), int(hours)
  147. if days > 0:
  148. time_str = t("cli.shared.duration_dhm", days=days, hours=hours, minutes=minutes)
  149. elif hours > 0:
  150. time_str = (t("cli.shared.duration_hms", hours=hours, minutes=minutes, seconds=seconds) if seconds
  151. else t("cli.shared.duration_hm", hours=hours, minutes=minutes))
  152. elif minutes > 0:
  153. time_str = (t("cli.shared.duration_ms", minutes=minutes, seconds=seconds) if seconds
  154. else t("cli.shared.duration_m", minutes=minutes))
  155. else:
  156. time_str = t("cli.shared.duration_s", seconds=int(elapsed))
  157. return f"{'⏱' if live else '⏲'} {time_str}"
  158. @staticmethod
  159. def _format_idle_since(last_finished_at: Optional[float], turn_live: bool) -> str:
  160. """``✓ 42s`` since the last final response; empty while a turn is live or before the
  161. first turn completes."""
  162. from cli import format_duration_compact
  163. if turn_live or last_finished_at is None:
  164. return ""
  165. return f"✓ {format_duration_compact(max(0.0, time.time() - last_finished_at))}"
  166. def _get_status_bar_snapshot(self) -> dict[str, Any]:
  167. from cli import _reverse_alias_for_display, datetime, format_duration_compact
  168. agent = getattr(self, "agent", None)
  169. # Prefer the agent's model name — it updates on fallback; self.model never changes.
  170. model_name = (getattr(agent, "model", None) or self.model or t("cli.shared.unknown"))
  171. # Friendly display: reverse-alias from config ``model_aliases:`` first (turns long
  172. # Palantir RIDs into the user's short name), else slash/length truncation.
  173. model_short = _reverse_alias_for_display(model_name)
  174. if model_short == model_name:
  175. model_short = model_name.split("/")[-1] if "/" in model_name else model_name
  176. # Shared RID-prefix stripper so this and ModelSwitchResult can't drift.
  177. from hermes_cli.model_switch import format_model_for_display
  178. model_short = format_model_for_display(model_short)
  179. model_short = model_short.removesuffix(".gguf")
  180. if len(model_short) > 26:
  181. model_short = f"{model_short[:23]}..."
  182. prompt_start = getattr(self, "_prompt_start_time", None)
  183. turn_live = prompt_start is not None
  184. elapsed_seconds = max(0.0, (datetime.now() - self.session_start).total_seconds())
  185. snapshot = {
  186. "model_name": model_name,
  187. "model_short": model_short,
  188. "duration": format_duration_compact(elapsed_seconds),
  189. "session_title": self._get_status_bar_session_title(),
  190. "prompt_elapsed": self._format_prompt_elapsed(
  191. prompt_start, getattr(self, "_prompt_duration", 0.0), live=turn_live),
  192. "idle_since": self._format_idle_since(
  193. getattr(self, "_last_turn_finished_at", None), turn_live=turn_live),
  194. "context_tokens": 0,
  195. "context_length": None,
  196. "context_percent": None,
  197. **dict.fromkeys(_AGENT_COUNTERS, 0),
  198. "compressions": 0,
  199. "active_background_tasks": 0,
  200. "active_background_processes": 0,
  201. "active_background_subagents": 0,
  202. "battery_label": "",
  203. "battery_category": "dim",
  204. "focus_label": "", # /focus badge: the reduced-output mode is never invisible.
  205. "git_branch": "",
  206. "goal_active": False,
  207. "goal_turns_used": 0,
  208. "goal_max_turns": 0}
  209. try:
  210. from hermes_cli.focus_view import focus_statusbar_segment
  211. snapshot["focus_label"] = focus_statusbar_segment(
  212. bool(getattr(self, "_focus_view_enabled", False)))
  213. except Exception:
  214. pass
  215. # Git branch (⎇) — opt-in via display.status_bar.fields, so the filesystem probe
  216. # (TTL-cached in status_bar_git) only runs when the user asked for the segment.
  217. try:
  218. _fields = self._get_status_bar_field_set()
  219. if _fields is not None and "git_branch" in _fields:
  220. from hermes_cli.status_bar_git import current_git_branch
  221. snapshot["git_branch"] = current_git_branch()
  222. except Exception:
  223. pass
  224. # Battery reads are memoised inside agent.battery, so per-repaint polling is cheap.
  225. if getattr(self, "_battery_visible", False):
  226. try:
  227. from agent.battery import battery_category, format_battery, read_battery
  228. _batt = read_battery()
  229. snapshot["battery_label"] = format_battery(_batt)
  230. snapshot["battery_category"] = battery_category(_batt)
  231. except Exception:
  232. pass
  233. # Live /bg tasks: entries are removed in the task thread's finally block; dict len()
  234. # is atomic in CPython, no lock needed.
  235. try:
  236. bg_tasks = getattr(self, "_background_tasks", None)
  237. if bg_tasks:
  238. snapshot["active_background_tasks"] = len(bg_tasks)
  239. except Exception:
  240. pass
  241. try:
  242. from hermes_cli.gateway_tools import background_counts
  243. snapshot.update(background_counts())
  244. except Exception:
  245. pass
  246. # Standing /goal (Ralph loop): GoalManager is cached on self — no DB hit per repaint.
  247. # Only an *active* goal earns a segment (paused/done stay out, like the desktop).
  248. try:
  249. goal_mgr = self._get_goal_manager()
  250. if goal_mgr is not None and goal_mgr.is_active():
  251. goal_state = goal_mgr.state
  252. snapshot["goal_active"] = True
  253. snapshot["goal_turns_used"] = int(getattr(goal_state, "turns_used", 0) or 0)
  254. snapshot["goal_max_turns"] = int(getattr(goal_state, "max_turns", 0) or 0)
  255. except Exception:
  256. pass
  257. if not agent:
  258. return snapshot
  259. for key in _AGENT_COUNTERS:
  260. snapshot[key] = getattr(agent, key, 0) or 0
  261. compressor = getattr(agent, "context_compressor", None)
  262. if compressor:
  263. # last_prompt_tokens parks at the -1 sentinel right after a compression until the
  264. # next real API call; clamp so the bar never renders "-1/200K".
  265. context_tokens = max(0, getattr(compressor, "last_prompt_tokens", 0) or 0)
  266. from agent.context_breakdown import context_display_source
  267. snapshot["context_estimated"] = context_display_source(compressor) != "provider_usage"
  268. # Display-only anchoring: on reasoning models a long tool loop replays the turn's
  269. # thinking on every request, so the LAST request's prompt_tokens can exceed the
  270. # durable transcript by hundreds of K and the bar sawtooths at the turn boundary.
  271. # Anchor on the turn's FIRST response plus a delta estimate of appended messages.
  272. # The compression trigger keeps using real last-request usage.
  273. try:
  274. from agent.usage_anchor import anchored_context_tokens
  275. _msgs = getattr(agent, "_session_messages", None)
  276. _anchored = anchored_context_tokens(
  277. _msgs if isinstance(_msgs, list) else [],
  278. getattr(agent, "_turn_base_usage_anchor", None),
  279. charge_stale_thinking=False)
  280. if _anchored is not None and _anchored > 0:
  281. context_tokens = _anchored
  282. anchor = agent._turn_base_usage_anchor
  283. delta = _msgs[int(anchor["base_count"]):]
  284. if delta and delta[0].get("role") == "assistant":
  285. delta = delta[1:]
  286. snapshot["context_estimated"] = bool(delta)
  287. except Exception:
  288. pass
  289. context_length = max(0, getattr(compressor, "context_length", 0) or 0)
  290. if context_length:
  291. context_tokens = min(context_tokens, context_length)
  292. snapshot["context_tokens"] = context_tokens
  293. snapshot["context_length"] = context_length or None
  294. from agent.context_pin import agent_context_marker
  295. marker = agent_context_marker(agent)
  296. snapshot["context_pinned"] = marker == "pinned"
  297. snapshot["context_fallback"] = marker == "fallback"
  298. snapshot["compressions"] = getattr(compressor, "compression_count", 0) or 0
  299. if context_length:
  300. pct = round((context_tokens / context_length) * 100)
  301. snapshot["context_percent"] = max(0, min(100, pct))
  302. # Cache-hit ratio since the last baseline reset (model switch and compression both
  303. # invalidate the prompt cache). hit = cache_read / prompt_tokens, where
  304. # prompt = input + cache_read + cache_write (CanonicalUsage).
  305. pct = None
  306. try:
  307. base_model = getattr(self, "_cache_hit_baseline_model", None)
  308. base_prompt = int(getattr(self, "_cache_hit_baseline_prompt", 0) or 0)
  309. base_read = int(getattr(self, "_cache_hit_baseline_read", 0) or 0)
  310. base_comps = int(getattr(self, "_cache_hit_baseline_compressions", 0) or 0)
  311. cur_comps = int(snapshot["compressions"] or 0)
  312. cur_prompt = int(snapshot["session_prompt_tokens"] or 0)
  313. cur_read = int(snapshot["session_cache_read_tokens"] or 0)
  314. def _rebase(*, tokens: bool) -> None:
  315. nonlocal base_prompt, base_read, base_comps
  316. self._cache_hit_baseline_model = model_name
  317. self._cache_hit_baseline_compressions = base_comps = cur_comps
  318. if tokens:
  319. self._cache_hit_baseline_prompt = base_prompt = cur_prompt
  320. self._cache_hit_baseline_read = base_read = cur_read
  321. if base_model is None:
  322. _rebase(tokens=False)
  323. elif model_name != base_model:
  324. _rebase(tokens=True)
  325. if cur_comps != base_comps:
  326. _rebase(tokens=True)
  327. delta_prompt = cur_prompt - base_prompt
  328. delta_read = cur_read - base_read
  329. # A zero-read regime hides the segment (no data ≠ an alarming 0%); pct stays a
  330. # float so renderers choose their own precision.
  331. if delta_prompt > 0 and delta_read > 0:
  332. pct = max(0.0, min(100.0, (delta_read / delta_prompt) * 100))
  333. except Exception:
  334. pct = None
  335. snapshot["cache_hit_pct"] = pct
  336. snapshot["cache_hit_label"] = f"{pct:.0f}%" if pct is not None else ""
  337. # Rolling avg latency / velocity over the deques kept by agent/conversation_loop.py
  338. # (hidden on Codex app-server, which reports no latency).
  339. avg_lat = avg_vel = None
  340. try:
  341. lhist = list(getattr(agent, "_api_latency_history", []) or [])
  342. ohist = list(getattr(agent, "_api_output_history", []) or [])
  343. n = min(len(lhist), len(ohist)) # appended together; keep aligned
  344. if n:
  345. lhist, ohist = lhist[-n:], ohist[-n:]
  346. total_lat = sum(lhist)
  347. # Mean for latency; sum/sum for velocity (true throughput, not mean of ratios).
  348. avg_lat = _finite(total_lat / n)
  349. avg_vel = _finite(sum(ohist) / total_lat if total_lat > 0 else None)
  350. except Exception:
  351. avg_lat = avg_vel = None
  352. snapshot["avg_latency"] = float(avg_lat) if avg_lat is not None else None
  353. snapshot["avg_latency_label"] = t("cli.status_bar.latency_label", value=f"{avg_lat:.1f}") if avg_lat is not None else ""
  354. snapshot["avg_velocity"] = float(avg_vel) if avg_vel is not None else None
  355. snapshot["avg_velocity_label"] = t("cli.status_bar.velocity_label", value=f"{avg_vel:.0f}") if avg_vel is not None else ""
  356. return snapshot
  357. def _get_status_bar_session_title(self) -> str:
  358. """Current title, polling state.db at most every 1.5s (not on every repaint)."""
  359. pending = str(getattr(self, "_pending_title", None) or "").strip()
  360. session_id = str(getattr(self, "session_id", "") or "")
  361. now = time.monotonic()
  362. checked_at = float(getattr(self, "_status_bar_title_checked_at", 0.0) or 0.0)
  363. cache_fresh = (
  364. getattr(self, "_status_bar_title_session_id", None) == session_id and now - checked_at < 1.5
  365. )
  366. if not pending and cache_fresh:
  367. return str(getattr(self, "_status_bar_title_cache", "") or "")
  368. title = pending
  369. db = getattr(self, "_session_db", None)
  370. if not pending and db is not None and session_id:
  371. try:
  372. title = str(db.get_session_title(session_id) or "").strip()
  373. except Exception:
  374. title = ""
  375. self._status_bar_title_session_id = session_id
  376. self._status_bar_title_cache = title
  377. self._status_bar_title_checked_at = now
  378. return title
  379. @staticmethod
  380. def _status_bar_display_width(text: str) -> int:
  381. """Terminal cell width (some glyphs render wider than one codepoint); keeps the bar
  382. from wrapping onto a second line and leaving duplicate rows."""
  383. try:
  384. from prompt_toolkit.utils import get_cwidth
  385. return get_cwidth(text or "")
  386. except Exception:
  387. return len(text or "")
  388. @classmethod
  389. def _trim_status_bar_text(cls, text: str, max_width: int) -> str:
  390. """Trim status-bar text to a single terminal row."""
  391. if max_width <= 0:
  392. return ""
  393. cw = cls._status_bar_display_width
  394. if cw(text) <= max_width:
  395. return text
  396. ellipsis_width = cw("...")
  397. if max_width <= ellipsis_width:
  398. return "..."[:max_width]
  399. out, width = [], 0
  400. for ch in text:
  401. if width + cw(ch) + ellipsis_width > max_width:
  402. break
  403. out.append(ch)
  404. width += cw(ch)
  405. return "".join(out).rstrip() + "..."
  406. @classmethod
  407. def _status_title_badge(cls, title: str, width: int) -> tuple[str, int] | None:
  408. """(badge, left_width) for the far-right session-title badge, or None when it
  409. doesn't fit (no title / bar narrower than 24 cells)."""
  410. title = str(title or "").strip()
  411. if not title or width < 24:
  412. return None
  413. title_width = max(6, min(30, width // 3))
  414. badge = f" {cls._trim_status_bar_text(title, title_width - 2)} "
  415. suffix_width = cls._status_bar_display_width(" ─") + cls._status_bar_display_width(badge)
  416. return badge, max(0, width - suffix_width)
  417. @classmethod
  418. def _right_align_status_title(cls, text: str, title: str, width: int) -> str:
  419. """Pin a bounded session-title badge to the far-right status-bar edge."""
  420. placed = cls._status_title_badge(title, width)
  421. if placed is None:
  422. return cls._trim_status_bar_text(text, width)
  423. badge, left_width = placed
  424. left = cls._trim_status_bar_text(text.rstrip(), left_width)
  425. padding = " " * max(0, left_width - cls._status_bar_display_width(left))
  426. return f"{left}{padding} ─{badge}"
  427. @classmethod
  428. def _right_align_status_title_fragments(cls, frags, title: str, width: int):
  429. """Styled counterpart to :meth:`_right_align_status_title`."""
  430. placed = cls._status_title_badge(title, width)
  431. if placed is None:
  432. return frags
  433. badge, left_width = placed
  434. trimmed = []
  435. used = 0
  436. for style, value in frags:
  437. remaining = left_width - used
  438. if remaining <= 0:
  439. break
  440. value_width = cls._status_bar_display_width(value)
  441. if value_width <= remaining:
  442. trimmed.append((style, value))
  443. used += value_width
  444. continue
  445. clipped = cls._trim_status_bar_text(value, remaining)
  446. if clipped:
  447. trimmed.append((style, clipped))
  448. used += cls._status_bar_display_width(clipped)
  449. break
  450. if used < left_width:
  451. trimmed.append((_DIM, " " * (left_width - used)))
  452. trimmed.extend([(_DIM, " ─"), ("class:status-bar-session-title", badge)])
  453. return trimmed
  454. @staticmethod
  455. def _get_tui_terminal_width(default: tuple[int, int] = (80, 24)) -> int:
  456. """Live prompt_toolkit width (can be narrower than shutil's, esp. Termux), falling
  457. back to ``shutil``."""
  458. try:
  459. from prompt_toolkit.application import get_app
  460. return get_app().output.get_size().columns
  461. except Exception:
  462. return shutil.get_terminal_size(default).columns
  463. def _use_minimal_tui_chrome(self, width: Optional[int] = None) -> bool:
  464. """Hide low-value chrome on narrow/mobile terminals to preserve rows."""
  465. if width is None:
  466. width = self._get_tui_terminal_width()
  467. return width < 64
  468. @staticmethod
  469. def _scrollback_box_width(width: Optional[int] = None) -> int:
  470. """Full viewport width for printed scrollback box rules, floored at 32 cols so tiny
  471. terminals never hit negative ``'─' * (w - 2)`` math. (The old 56-col clamp against
  472. reflow-on-shrink is gone: the ``_output_screen_diff`` patch keeps chrome out of
  473. scrollback, and reflow of already-printed borders is a cosmetic artifact.)
  474. Previously this clamped to ``max(32, min(width, 56))`` as a defense against terminal-emulator reflow
  475. on column-shrink (#25975, salvaging 24403). That clamp made response/reasoning borders look stubby
  476. on any modern wide terminal. We now trust the prompt_toolkit ``_output_screen_diff`` monkey-patch
  477. landed in #26137 (salvaging 25981) to keep chrome out of scrollback in the first place, and accept
  478. that an aggressive column-shrink may visually reflow already printed Panel borders — that's a
  479. cosmetic artifact of stamped scrollback history, not a live-render bug.
  480. """
  481. if width is None:
  482. try:
  483. width = shutil.get_terminal_size((80, 24)).columns
  484. except Exception:
  485. width = 80
  486. return max(32, int(width or 80))
  487. def _agent_spacer_height(self, width: Optional[int] = None) -> int:
  488. """Spacer height above the status bar while the agent runs."""
  489. if not getattr(self, "_agent_running", False) or getattr(self, "_modern_layout", False):
  490. return 0
  491. return 0 if self._use_minimal_tui_chrome(width=width) else 1
  492. def _spinner_widget_height(self, width: Optional[int] = None) -> int:
  493. """Visible height of the spinner/status line above the status bar."""
  494. spinner_line = self._render_spinner_text()
  495. if not spinner_line or self._use_minimal_tui_chrome(width=width) or getattr(self, "_modern_layout", False):
  496. return 0
  497. width = width or self._get_tui_terminal_width()
  498. if width and width > 10:
  499. return max(1, -(-self._status_bar_display_width(spinner_line) // width))
  500. return 1
  501. def _render_spinner_text(self) -> str:
  502. """The live spinner/status text exactly as rendered in the TUI."""
  503. txt = getattr(self, "_spinner_text", "")
  504. if not txt:
  505. return ""
  506. flow = self._spinner_token_flow()
  507. t0 = getattr(self, "_tool_start_time", 0) or 0
  508. if t0 > 0:
  509. elapsed = time.monotonic() - t0
  510. # Fixed-width timers (01m05s / " 5.2s") avoid status-line wrap jitter on repaint.
  511. if elapsed >= 60:
  512. elapsed_str = t("cli.shared.duration_ms_compact",
  513. minutes=f"{int(elapsed // 60):02d}", seconds=f"{int(elapsed % 60):02d}")
  514. else:
  515. elapsed_str = t("cli.shared.duration_s", seconds=f"{elapsed:5.1f}")
  516. return f" {txt} ({elapsed_str} · {flow})" if flow else f" {txt} ({elapsed_str})"
  517. return f" {txt} ({flow})" if flow else f" {txt}"
  518. def _spinner_token_flow(self) -> str:
  519. """Cumulative output tokens for the running turn, for the spinner."""
  520. if not getattr(self, "_spinner_token_flow_enabled", False):
  521. return ""
  522. if not getattr(self, "_agent_running", False):
  523. return ""
  524. agent = getattr(self, "agent", None)
  525. if agent is None:
  526. return ""
  527. try:
  528. from agent.turn_summary import format_token_flow
  529. produced = (getattr(agent, "session_output_tokens", 0) or 0) - (
  530. getattr(self, "_turn_token_baseline", 0) or 0)
  531. return format_token_flow(produced)
  532. except Exception:
  533. return ""
  534. def _turn_summary_is_active(self) -> bool:
  535. """Whether the per-turn summary line renders here: off for the config key, quiet /
  536. tool-progress-off mode, and every non-interactive path (-q, -Q, gateway)."""
  537. if not getattr(self, "_turn_summary_enabled", False):
  538. return False
  539. if getattr(self, "tool_progress_mode", "all") == "off":
  540. return False
  541. agent = getattr(self, "agent", None)
  542. # The interactive agent itself runs quiet unless --verbose, so in the classic layout this
  543. # line only shows under --verbose; the glyph layout closes every interactive turn with it.
  544. if agent is not None and getattr(agent, "quiet_mode", False) and not getattr(self, "_modern_layout", False):
  545. return False
  546. return bool(getattr(self, "_interactive_turn", False))
  547. def _turn_summary_begin(self) -> None:
  548. """Start per-turn accounting for the turn that is about to run."""
  549. try:
  550. from agent.turn_summary import TurnSummaryCollector
  551. collector = getattr(self, "_turn_summary_collector", None)
  552. if collector is None:
  553. collector = TurnSummaryCollector()
  554. self._turn_summary_collector = collector
  555. collector.begin()
  556. self._turn_summary_start = time.monotonic()
  557. agent = getattr(self, "agent", None)
  558. self._turn_token_baseline = (
  559. getattr(agent, "session_output_tokens", 0) or 0
  560. ) if agent is not None else 0
  561. except Exception:
  562. self._turn_summary_collector = None
  563. def _turn_summary_record(self, function_name, result, is_error: bool) -> None:
  564. """Feed one completed tool call into the active tally."""
  565. collector = getattr(self, "_turn_summary_collector", None)
  566. if collector is None:
  567. return
  568. try:
  569. collector.record_tool(function_name, result=result, is_error=bool(is_error))
  570. except Exception:
  571. pass
  572. def _turn_summary_emit(self) -> None:
  573. """Print the post-turn accounting line, when enabled for this surface."""
  574. from cli import _DIM as _D, _RST, _cprint, logger
  575. collector = getattr(self, "_turn_summary_collector", None)
  576. if collector is None or not self._turn_summary_is_active():
  577. return
  578. try:
  579. started = getattr(self, "_turn_summary_start", 0.0) or 0.0
  580. line = collector.render(max(0.0, time.monotonic() - started) if started else 0.0)
  581. if line and getattr(self, "_modern_layout", False):
  582. from hermes_cli.cli_modern_layout import turn_footer
  583. _cprint(turn_footer(line))
  584. elif line:
  585. _cprint(f" {_D}{line}{_RST}")
  586. except Exception:
  587. logger.debug("Turn summary render failed", exc_info=True)
  588. # ── pet pane ──────────────────────────────────────────────────────────────
  589. def _pet_clear_runtime(self) -> None:
  590. """Drop renderer + queued Kitty state. Caller holds ``_pet_lock``."""
  591. self._pet_enabled = False
  592. self._pet_renderer = None
  593. self._pet_frames_cache.clear()
  594. self._pet_kitty_cache.clear()
  595. self._pet_kitty_pending = ""
  596. self._pet_kitty_image_id = 0
  597. def _pet_resolve_config(self) -> None:
  598. """(Re)resolve the active pet from config so ``/pet`` / ``hermes pets`` changes apply
  599. without a restart (mirrors the TUI's steady poll). Fail-open: any problem disables."""
  600. try:
  601. from agent.pet import constants, store
  602. from hermes_cli.config import load_config
  603. from utils import is_truthy_value
  604. cfg = load_config()
  605. display = cfg.get("display", {}) if isinstance(cfg.get("display"), dict) else {}
  606. pet_cfg = display.get("pet", {}) if isinstance(display.get("pet"), dict) else {}
  607. enabled = is_truthy_value(pet_cfg.get("enabled"), default=False)
  608. slug = str(pet_cfg.get("slug", "") or "")
  609. scale = float(pet_cfg.get("scale", constants.DEFAULT_SCALE) or constants.DEFAULT_SCALE)
  610. cols = constants.resolve_cols(scale, pet_cfg.get("unicode_cols", 0))
  611. configured_mode = str(pet_cfg.get("render_mode", "auto") or "auto").lower()
  612. # Placeholders only on kitty/Ghostty: WezTerm speaks kitty APC but not U+10EEEE
  613. # while detect_terminal_graphics() still says kitty, hence the narrower gate.
  614. use_kitty = (
  615. configured_mode in ("", "auto", "kitty") and terminal_image.supports_kitty_placeholders()
  616. )
  617. renderer_mode = "kitty" if use_kitty else "unicode"
  618. pet = None
  619. if enabled and configured_mode != "off":
  620. pet = store.resolve_active_pet(slug)
  621. if pet is None or not pet.exists:
  622. with self._pet_lock:
  623. self._pet_clear_runtime()
  624. return
  625. with self._pet_lock:
  626. # Rebuild only when the resolved pet, mode, or geometry changes.
  627. if (
  628. self._pet_renderer is None
  629. or self._pet_slug != pet.slug
  630. or self._pet_cols != cols
  631. or self._pet_scale != scale
  632. or self._pet_renderer.mode != renderer_mode):
  633. self._pet_renderer = pet_render.PetRenderer(
  634. str(pet.spritesheet), mode=renderer_mode, scale=scale, unicode_cols=cols)
  635. self._pet_slug = pet.slug
  636. self._pet_cols = cols
  637. self._pet_scale = scale
  638. self._pet_frames_cache.clear()
  639. self._pet_kitty_cache.clear()
  640. self._pet_kitty_pending = ""
  641. self._pet_kitty_image_id = pet_render.kitty_image_id(pet.slug)
  642. self._pet_frame_idx = 0
  643. self._pet_enabled = True
  644. except Exception:
  645. with self._pet_lock:
  646. self._pet_clear_runtime()
  647. def _pet_flash(self, state: str, secs: float = 1.6) -> None:
  648. """Briefly force a transient reaction (wave/jump/failed) before resting."""
  649. self._pet_event = state
  650. self._pet_event_until = time.monotonic() + secs
  651. def _on_reaction(self, kind: str) -> None:
  652. """Core-detected user affection (ily / <3 / good bot): the pet's share of the vibe
  653. signal that plays hearts on the TUI/desktop."""
  654. if kind == "vibe":
  655. self._pet_flash("jump")
  656. def _pet_react_turn_end(self) -> None:
  657. """End-of-turn beat: failed on error, jump on a finished plan, else wave."""
  658. if not self._pet_enabled:
  659. return
  660. from agent.pet.state import todos_all_done
  661. if self._pet_turn_error:
  662. self._pet_flash("failed")
  663. return
  664. try:
  665. store = getattr(self.agent, "_todo_store", None)
  666. done = todos_all_done(store.read()) if store else False
  667. except Exception:
  668. done = False
  669. self._pet_flash("jump" if done else "wave")
  670. def _derive_pet_state(self) -> str:
  671. """A live transient beat wins; otherwise the shared ``agent.pet.state.derive_pet_state``
  672. priority order so the CLI can't drift from the TUI/desktop."""
  673. if self._pet_event and time.monotonic() < self._pet_event_until:
  674. return self._pet_event
  675. self._pet_event = ""
  676. from agent.pet.state import derive_pet_state
  677. # Any blocking modal (approval / clarify / sudo / secret / slash confirm) means the
  678. # agent is paused on the user → `waiting`, which outranks the in-flight signals.
  679. awaiting_input = bool(
  680. self._approval_state
  681. or self._clarify_state
  682. or self._sudo_state
  683. or self._secret_state
  684. or getattr(self, "_slash_confirm_state", None))
  685. return derive_pet_state(
  686. awaiting_input=awaiting_input,
  687. busy=getattr(self, "_agent_running", False),
  688. reasoning=self._pet_reasoning,
  689. ).value
  690. def _pet_frames_for(self, state: str) -> list:
  691. """Return (and cache) the half-block grids for one state."""
  692. cached = self._pet_frames_cache.get(state)
  693. if cached is not None:
  694. return cached
  695. renderer = self._pet_renderer
  696. if renderer is None:
  697. return []
  698. try:
  699. count = renderer.frame_count(state) or 1
  700. grids = [renderer.cells(state, i, cols=self._pet_cols) for i in range(count)]
  701. except Exception:
  702. grids = []
  703. self._pet_frames_cache[state] = grids
  704. return grids
  705. def _pet_kitty_payload_for(self, state: str) -> dict | None:
  706. """Return and cache a Kitty virtual-placeholder payload for *state*."""
  707. with self._pet_lock:
  708. cached = self._pet_kitty_cache.get(state)
  709. if cached is not None:
  710. return cached
  711. renderer = self._pet_renderer
  712. image_id = self._pet_kitty_image_id
  713. if renderer is None or renderer.mode != "kitty":
  714. return None
  715. try:
  716. # PNG encoding outside _pet_lock: first visit of a state must not stall the prompt.
  717. payload = renderer.kitty_payload(state, image_id=image_id)
  718. except Exception:
  719. payload = None
  720. if payload is not None:
  721. payload = {**payload, "image_id": image_id}
  722. with self._pet_lock:
  723. if self._pet_renderer is renderer and self._pet_kitty_image_id == image_id:
  724. self._pet_kitty_cache[state] = payload
  725. return payload
  726. def _pet_queue_kitty_frame(self, state: str | None = None) -> None:
  727. """Queue one virtual Kitty frame for the next prompt_toolkit render. No-op when the
  728. pet pane was never initialized (``__new__`` fixtures, redraw on a pet-less CLI)."""
  729. if not getattr(self, "_pet_enabled", False):
  730. return
  731. if state is None:
  732. state = self._derive_pet_state()
  733. payload = self._pet_kitty_payload_for(state)
  734. if not payload or not payload.get("frames"):
  735. return
  736. with self._pet_lock:
  737. if self._pet_renderer is not None and self._pet_renderer.mode == "kitty":
  738. frames = payload["frames"]
  739. self._pet_kitty_pending = frames[self._pet_frame_idx % len(frames)]
  740. def _pet_flush_kitty_frame(self, app) -> None:
  741. """Write a queued APC after prompt_toolkit has finished its screen diff."""
  742. with self._pet_lock:
  743. frame = self._pet_kitty_pending
  744. self._pet_kitty_pending = ""
  745. if not frame:
  746. return
  747. try:
  748. # U=1/q=2 leaves the cursor and input stream untouched.
  749. app.output.write_raw(frame)
  750. app.output.flush()
  751. except (OSError, ValueError):
  752. pass
  753. def _pet_view(self) -> tuple[str, bool] | None:
  754. """(state, is_kitty) for the current frame, or None when no pet shows."""
  755. with self._pet_lock:
  756. if not self._pet_enabled or self._pet_renderer is None:
  757. return None
  758. return self._derive_pet_state(), self._pet_renderer.mode == "kitty"
  759. def _pet_fragments(self):
  760. """prompt_toolkit FormattedText for the current pet frame, or []."""
  761. view = self._pet_view()
  762. if view is None:
  763. return []
  764. state, kitty = view
  765. frags = []
  766. if kitty:
  767. payload = self._pet_kitty_payload_for(state)
  768. if not payload:
  769. return []
  770. color = terminal_image.kitty_color_hex(payload["image_id"])
  771. for y, row in enumerate(payload["placeholder"]):
  772. if y:
  773. frags.append(("", "\n"))
  774. frags.append((f"fg:{color}", row))
  775. return frags
  776. with self._pet_lock:
  777. grids = self._pet_frames_for(state)
  778. if not grids:
  779. return []
  780. grid = grids[self._pet_frame_idx % len(grids)]
  781. def _hex(r, g, b):
  782. return f"#{r:02x}{g:02x}{b:02x}"
  783. for y, row in enumerate(grid):
  784. if y:
  785. frags.append(("", "\n"))
  786. for (tr, tg, tb, ta), (br, bg, bb, ba) in row:
  787. top_op, bot_op = ta >= 32, ba >= 32
  788. if not top_op and not bot_op:
  789. frags.append(("", " "))
  790. elif top_op and bot_op:
  791. frags.append((f"fg:{_hex(tr, tg, tb)} bg:{_hex(br, bg, bb)}", "▀"))
  792. elif top_op:
  793. # Upper half only — leave the lower half the terminal's bg (cleaner on light
  794. # themes).
  795. frags.append((f"fg:{_hex(tr, tg, tb)}", "▀"))
  796. else:
  797. frags.append((f"fg:{_hex(br, bg, bb)}", "▄"))
  798. return frags
  799. def _pet_widget_height(self) -> int:
  800. """Visible rows for the pet window — 0 collapses it when no pet shows."""
  801. view = self._pet_view()
  802. if view is None:
  803. return 0
  804. state, kitty = view
  805. if kitty:
  806. payload = self._pet_kitty_payload_for(state)
  807. return int(payload.get("rows", 0)) if payload else 0
  808. with self._pet_lock:
  809. grids = self._pet_frames_for(state)
  810. return len(grids[0]) if grids and grids[0] else 0
  811. def _pet_anim_loop(self) -> None:
  812. """Advance the frame + invalidate on a timer while a pet is enabled."""
  813. while self._pet_anim_running:
  814. time.sleep(self._PET_FRAME_INTERVAL)
  815. if getattr(self, "_terminal_io_broken", False):
  816. self._pet_anim_running = False
  817. break
  818. now = time.monotonic()
  819. if now - self._pet_cfg_checked >= self._PET_CFG_INTERVAL:
  820. self._pet_cfg_checked = now
  821. self._pet_resolve_config()
  822. if not self._pet_enabled:
  823. continue
  824. with self._pet_lock:
  825. self._pet_frame_idx += 1
  826. kitty = self._pet_renderer is not None and self._pet_renderer.mode == "kitty"
  827. if kitty:
  828. self._pet_queue_kitty_frame()
  829. app = getattr(self, "_app", None)
  830. if app is not None:
  831. try:
  832. app.invalidate()
  833. except OSError as exc:
  834. if getattr(exc, "errno", None) == errno.EIO:
  835. self._mark_terminal_io_broken("pet_anim")
  836. break
  837. except Exception:
  838. pass
  839. def _pet_start_anim(self) -> None:
  840. if self._pet_anim_running:
  841. return
  842. self._pet_resolve_config()
  843. view = self._pet_view()
  844. if view is not None and view[1]:
  845. self._pet_queue_kitty_frame()
  846. self._pet_anim_running = True
  847. self._pet_anim_thread = threading.Thread(target=self._pet_anim_loop, daemon=True)
  848. self._pet_anim_thread.start()
  849. def _pet_stop_anim(self) -> None:
  850. self._pet_anim_running = False
  851. thread = self._pet_anim_thread
  852. if thread is not None:
  853. thread.join(timeout=0.3)
  854. self._pet_anim_thread = None
  855. # ── voice ─────────────────────────────────────────────────────────────────
  856. def _voice_record_key_label(self) -> str:
  857. """The push-to-talk key label every voice-facing hint advertises. Cached at startup
  858. (``set_voice_record_key_cache``) because the prompt_toolkit binding is registered once —
  859. re-reading config per render could advertise a chord that isn't bound — and this sits on
  860. the hot render path.
  861. Two reasons (review round-13 on 19835): See #19835.
  862. """
  863. return getattr(self, "_voice_record_key_display_cache", None) or "Ctrl+B"
  864. def set_voice_record_key_cache(self, raw_key: object) -> None:
  865. """Populate the voice label cache from a raw ``voice.record_key``; called after the
  866. prompt_toolkit binding is registered so the label matches the live binding."""
  867. try:
  868. from hermes_cli.voice import format_voice_record_key_for_status
  869. self._voice_record_key_display_cache = format_voice_record_key_for_status(raw_key)
  870. except Exception:
  871. self._voice_record_key_display_cache = "Ctrl+B"
  872. def _get_voice_status_fragments(self, width: Optional[int] = None):
  873. """Voice status bar fragments for the interactive TUI."""
  874. width = width or self._get_tui_terminal_width()
  875. compact = self._use_minimal_tui_chrome(width=width)
  876. label = self._voice_record_key_label()
  877. if self._voice_recording:
  878. if compact:
  879. return [("class:voice-status-recording", f" {t('cli.status_bar.voice_rec')} ")]
  880. return [("class:voice-status-recording", f" {t('cli.status_bar.voice_rec_stop_hint', shortcut=label)} ")]
  881. if self._voice_processing:
  882. return [("class:voice-status",
  883. f" {t('cli.status_bar.voice_stt')} " if compact else f" {t('cli.status_bar.voice_transcribing')} ")]
  884. if compact:
  885. return [("class:voice-status", f" 🎤 {label} ")]
  886. tts = t("cli.status_bar.voice_tts_on") if self._voice_tts else ""
  887. cont = t("cli.status_bar.voice_continuous") if self._voice_continuous else ""
  888. return [("class:voice-status", f" {t('cli.status_bar.voice_mode_hint', tts=tts, cont=cont, shortcut=label)} ")]
  889. # ── status bar rendering ──────────────────────────────────────────────────
  890. @staticmethod
  891. def _status_bar_goal_segment(snapshot: dict[str, Any]) -> str:
  892. """``⊙ goal 3/20`` while a goal is active, else ``""`` (paused/done goals already
  893. print their own glyph lines in the thread)."""
  894. if not snapshot.get("goal_active"):
  895. return ""
  896. used = snapshot.get("goal_turns_used") or 0
  897. max_turns = snapshot.get("goal_max_turns") or 0
  898. return t("cli.status_bar.goal_turns", used=used, max=max_turns) if max_turns else t("cli.status_bar.goal")
  899. def _get_status_bar_field_set(self) -> Optional[frozenset]:
  900. """Visible status-bar fields from ``display.status_bar.fields`` (module-level
  901. ``CLI_CONFIG``; no per-render YAML parse). ``None`` = not customized, show everything.
  902. Fields: model, context_detail, context_pct, cache_hit, latency, tps, compressions,
  903. bg_tasks, bg_processes, bg_subagents, goal, git_branch (opt-in only), duration,
  904. prompt_elapsed, idle_since, focus, yolo, stash, battery, title, total_tokens
  905. (opt-in only). Order is fixed; the config controls visibility only.
  906. """
  907. from cli import CLI_CONFIG
  908. if hasattr(self, "_status_bar_field_set_cache"):
  909. return self._status_bar_field_set_cache
  910. result = None
  911. try:
  912. display = CLI_CONFIG.get("display") if isinstance(CLI_CONFIG, dict) else None
  913. status_bar = (display or {}).get("status_bar") if isinstance(display, dict) else None
  914. fields = status_bar.get("fields") if isinstance(status_bar, dict) else None
  915. if isinstance(fields, list) and fields:
  916. result = frozenset(str(f) for f in fields)
  917. except Exception:
  918. result = None
  919. self._status_bar_field_set_cache = result
  920. return result
  921. def _status_bar_segments(
  922. self, snapshot, width: int, field_set, yolo_active: bool, *, styled: bool) -> list:
  923. """Ordered status-bar segments for one width tier (<52 / <76 / wide), each a list of
  924. ``(style, text)`` fragments. Shared by the plain-text and prompt_toolkit renderers so
  925. the two can never drift; ``styled`` selects the graphical context bar."""
  926. from cli import format_token_count_compact
  927. model_short = snapshot["model_short"]
  928. duration_label = snapshot["duration"]
  929. goal_segment = self._status_bar_goal_segment(snapshot)
  930. focus_label = snapshot.get("focus_label") or ""
  931. def _ok(name: str) -> bool:
  932. return field_set is None or name in field_set
  933. segs: list = []
  934. def add(name, style, text):
  935. if _ok(name):
  936. segs.append([(style, text)])
  937. def add_count(name, key, glyph, style=_STRONG):
  938. count = snapshot.get(key, 0)
  939. if count:
  940. add(name, style(count) if callable(style) else style, f"{glyph} {count}")
  941. if _ok("model"):
  942. if styled:
  943. segs.append([(_SB, " ☤ "), (_STRONG, model_short)])
  944. else:
  945. segs.append([("", f"☤ {model_short}")])
  946. narrow, wide = width < 52, width >= 76
  947. if narrow:
  948. # Narrow bars put duration ahead of the goal segment; the other tiers reverse it.
  949. add("duration", _DIM, duration_label)
  950. else:
  951. percent = snapshot["context_percent"]
  952. mark = "~" if snapshot.get("context_estimated") else ""
  953. percent_label = f"{mark}{percent}%" if percent is not None else "--"
  954. if wide and _ok("context_detail"):
  955. if snapshot["context_length"]:
  956. ctx_total = _format_context_length(snapshot["context_length"])
  957. ctx_used = format_token_count_compact(snapshot["context_tokens"])
  958. pin = (t("cli.status_bar.ctx_pinned") if snapshot.get("context_pinned")
  959. else t("cli.status_bar.ctx_fallback") if snapshot.get("context_fallback") else "")
  960. context_label = f"{mark}{ctx_used}/{ctx_total}{pin}"
  961. else:
  962. context_label = t("cli.status_bar.ctx_unknown")
  963. segs.append([(_DIM, context_label)])
  964. if _ok("context_pct"):
  965. bar_style = self._status_bar_context_style(percent)
  966. if wide and styled:
  967. segs.append([
  968. (bar_style, self._build_context_bar(percent)), (_DIM, " "), (bar_style, percent_label),
  969. ])
  970. else:
  971. segs.append([(bar_style, percent_label)])
  972. cache = self._cache_hit_rate(snapshot, precision=1 if wide else 0)
  973. if cache:
  974. add("cache_hit", self._cache_hit_rate_style(cache[0]), cache[1])
  975. if wide:
  976. for name, key, glyph in (
  977. ("latency", "avg_latency_label", "◷"), ("tps", "avg_velocity_label", "↑")):
  978. label = snapshot.get(key) or ""
  979. if label:
  980. add(name, _DIM, f"{glyph} {label}")
  981. add_count("compressions", "compressions", "🗜️", self._compression_count_style)
  982. add_count("bg_tasks", "active_background_tasks", "▶")
  983. add_count("bg_processes", "active_background_processes", "⚙")
  984. add_count("bg_subagents", "active_background_subagents", "⛓")
  985. if goal_segment:
  986. add("goal", _STRONG, goal_segment)
  987. git_branch = snapshot.get("git_branch") or ""
  988. if git_branch:
  989. add("git_branch", _DIM, f"⎇ {git_branch}")
  990. if not narrow:
  991. add("duration", _DIM, duration_label)
  992. if wide:
  993. for name in ("prompt_elapsed", "idle_since"):
  994. label = snapshot.get(name)
  995. if label:
  996. add(name, _DIM, label)
  997. if focus_label:
  998. add("focus", _STRONG, focus_label)
  999. if yolo_active:
  1000. add("yolo", "class:status-bar-yolo", t("cli.status_bar.yolo_badge"))
  1001. if wide:
  1002. # Session token total (Σ) — opt-in only via an explicit fields list.
  1003. total_tokens = snapshot.get("session_total_tokens", 0)
  1004. if total_tokens and field_set is not None and "total_tokens" in field_set:
  1005. segs.append([(_DIM, f"Σ{format_token_count_compact(total_tokens)}")])
  1006. return segs
  1007. def _build_status_bar_text(self, width: Optional[int] = None) -> str:
  1008. """Compact one-line session status string for the TUI footer."""
  1009. try:
  1010. snapshot = self._get_status_bar_snapshot()
  1011. if width is None:
  1012. width = self._get_tui_terminal_width()
  1013. model_short = snapshot["model_short"]
  1014. battery_label = snapshot.get("battery_label") or ""
  1015. field_set = self._get_status_bar_field_set()
  1016. show_title = field_set is None or "title" in field_set
  1017. session_title = (snapshot.get("session_title") or "") if show_title else ""
  1018. segs = self._status_bar_segments(
  1019. snapshot, width, field_set, self._is_session_yolo_active(), styled=False)
  1020. parts = ["".join(t for _, t in seg) for seg in segs] or [f"☤ {model_short}"]
  1021. # Narrow bars always join the battery with │; wider tiers use the tier separator.
  1022. if battery_label:
  1023. parts.insert(0, battery_label)
  1024. if width < 52:
  1025. text = f"{parts[0]} │ " + " · ".join(parts[1:]) if battery_label else " · ".join(parts)
  1026. else:
  1027. text = (" · " if width < 76 else " │ ").join(parts)
  1028. return self._right_align_status_title(text, session_title, width)
  1029. except Exception:
  1030. return f"☤ {self.model if getattr(self, 'model', None) else 'Hermes'}"
  1031. def _get_status_bar_fragments(self):
  1032. if (
  1033. not self._status_bar_visible
  1034. or getattr(self, "_model_picker_state", None)
  1035. or getattr(self, "_command_palette_state", None)):
  1036. return []
  1037. if getattr(self, "_modern_layout", False):
  1038. from hermes_cli.cli_modern_layout import status_line_fragments
  1039. return status_line_fragments(self)
  1040. try:
  1041. snapshot = self._get_status_bar_snapshot()
  1042. # prompt_toolkit's own width: shutil's can be stale (esp. over SSH) and an overflow
  1043. # produces duplicated status-bar rows over long sessions.
  1044. width = self._get_tui_terminal_width()
  1045. field_set = self._get_status_bar_field_set()
  1046. def _ok(name: str) -> bool:
  1047. return field_set is None or name in field_set
  1048. session_title = (snapshot.get("session_title") or "") if _ok("title") else ""
  1049. segs = self._status_bar_segments(
  1050. snapshot, width, field_set, self._is_session_yolo_active(), styled=True)
  1051. sep = " · " if width < 76 else " │ "
  1052. frags: list = []
  1053. for seg in segs or [[(_SB, " ☤ "), (_STRONG, snapshot["model_short"])]]:
  1054. if frags:
  1055. frags.append((_DIM, sep))
  1056. frags.extend(seg)
  1057. # Stash indicator (📌 N) after every width tier so a parked draft is never
  1058. # invisible; before the battery prepend, and the first thing the trim drops.
  1059. try:
  1060. stash_indicator = self._prompt_stash.indicator()
  1061. except Exception:
  1062. stash_indicator = ""
  1063. if stash_indicator and _ok("stash"):
  1064. frags.extend([(_DIM, " · "), (_STRONG, stash_indicator)])
  1065. frags.append((_SB, " ")) # one-cell right margin
  1066. # Battery is the first element when enabled: prepend ahead of the ☤ marker.
  1067. battery_label = snapshot.get("battery_label") or ""
  1068. if battery_label and _ok("battery"):
  1069. battery_style = self._battery_status_style(snapshot.get("battery_category", "dim"))
  1070. frags[0:0] = [(_SB, " "), (battery_style, battery_label), (_DIM, " │")]
  1071. frags = self._right_align_status_title_fragments(frags, session_title, width)
  1072. vim_label = self._vim_mode_label()
  1073. if vim_label:
  1074. frags.extend([(_DIM, " │ "), (_STRONG, vim_label), (_SB, " ")])
  1075. total_width = sum(self._status_bar_display_width(text) for _, text in frags)
  1076. if total_width > width:
  1077. plain_text = "".join(text for _, text in frags)
  1078. return [(_SB, self._trim_status_bar_text(plain_text, width))]
  1079. return frags
  1080. except Exception:
  1081. return [(_SB, f" {self._build_status_bar_text()} ")]
  1082. # ── prompt stash panel ────────────────────────────────────────────────────
  1083. @staticmethod
  1084. def _fmt_stash_age(stashed_at: float) -> str:
  1085. secs = int(time.monotonic() - stashed_at)
  1086. if secs < 10:
  1087. return t("cli.shared.just_now")
  1088. if secs < 90:
  1089. return t("cli.shared.ago_seconds", seconds=secs)
  1090. mins = secs // 60
  1091. return t("cli.shared.ago_minutes", minutes=mins) if mins < 60 else t("cli.shared.ago_hours", hours=mins // 60)
  1092. def _render_stash_panel(self, stash_list: list, cursor: int, width: int) -> list:
  1093. """prompt_toolkit fragments for the stash panel box. Every horizontal measurement uses
  1094. ``_status_bar_display_width`` (display cells), not ``len()`` — 📌 is one codepoint but
  1095. two cells, and CJK previews would otherwise bleed past the right border."""
  1096. cw = self._status_bar_display_width
  1097. W = max(12, min(width - 4, 80))
  1098. n = len(stash_list)
  1099. hdr_key = "cli.status_bar.stash_header_one" if n == 1 else "cli.status_bar.stash_header_other"
  1100. hdr_prefix_str = f"╭─ {t(hdr_key, count=n)} "
  1101. HDR_SUFFIX = " Ctrl+S ─╮"
  1102. FTR_PREFIX = "╰"
  1103. FTR_SUFFIX = f" {t('cli.status_bar.stash_footer')} ─╯"
  1104. # On narrow terminals the full hint text is wider than the box: drop to compact
  1105. # affordances rather than letting the frame bleed past the right edge.
  1106. if cw(hdr_prefix_str) + cw(HDR_SUFFIX) > W:
  1107. hdr_prefix_str = f"╭─ 📌 {n} "
  1108. HDR_SUFFIX = "─╮"
  1109. if cw(FTR_PREFIX) + cw(FTR_SUFFIX) > W:
  1110. FTR_SUFFIX = f" {t('cli.status_bar.stash_footer_compact')} ─╯"
  1111. if cw(FTR_PREFIX) + cw(FTR_SUFFIX) > W:
  1112. FTR_SUFFIX = "─╯"
  1113. hdr_dashes = max(0, W - cw(hdr_prefix_str) - cw(HDR_SUFFIX))
  1114. ftr_dashes = max(0, W - cw(FTR_PREFIX) - cw(FTR_SUFFIX))
  1115. INNER = W - 2 # minus the two '│' border cells
  1116. frags: list = []
  1117. def line(text: str, style: str = "") -> None:
  1118. # Final guard: never emit a line wider than the box.
  1119. frags.append((style, self._trim_status_bar_text(text, W) + "\n"))
  1120. line(f"{hdr_prefix_str}{'─' * hdr_dashes}{HDR_SUFFIX}", "class:subagent-border")
  1121. for i, item in enumerate(stash_list):
  1122. age = self._fmt_stash_age(item["stashed_at"])
  1123. marker = "►" if i == cursor else " "
  1124. prefix = f" {marker} [{i + 1}] {age:<10} "
  1125. if cw(prefix) > INNER - 2:
  1126. prefix = f" {marker} [{i + 1}] "
  1127. avail = max(0, INNER - cw(prefix) - 1)
  1128. preview = self._trim_status_bar_text(item.get("preview") or "", avail)
  1129. preview = preview + " " * max(0, avail - cw(preview))
  1130. if i == cursor:
  1131. row = self._trim_status_bar_text(f"│{prefix}{preview} │", W)
  1132. frags.append(("class:subagent-selected", row + "\n"))
  1133. else:
  1134. frags.append(("class:subagent-border", "│"))
  1135. frags.append(("class:subagent-sub", f"{prefix}{preview} "))
  1136. frags.append(("class:subagent-border", "│\n"))
  1137. line(f"{FTR_PREFIX}{'─' * ftr_dashes}{FTR_SUFFIX}", "class:subagent-border")
  1138. return frags