cli_backtrack.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. """Codex-style backtrack for the classic CLI: Esc Esc on an idle, empty composer (or ``/rewind``)
  2. lists earlier prompts newest first; Enter edits & resends one, ``f`` forks a branch before it.
  3. Edit & resend cuts NOTHING until the edited text is submitted: the submission travels to the
  4. process loop as a :class:`BacktrackResend`, which re-validates the picked turn and only then runs
  5. the same durable rewind ``/undo`` uses (``_rewind_to_user_ordinal``). Cancelling (Esc Esc, Ctrl+C,
  6. an empty submit, or submitting something else) leaves the session as it was. Fork reuses
  7. ``/branch`` and rewinds only the child, so the original session's rows stay active.
  8. Mixin bound FIRST in ``HermesCLI``'s bases so its overrides wrap the TUI handlers via ``super()``.
  9. cli.py-internal symbols are imported lazily (import cycle).
  10. """
  11. from __future__ import annotations
  12. from agent.i18n import t
  13. _LABEL_CHARS = 72
  14. _PREVIEW_LINES = 4
  15. _PREVIEW_CHARS = 80
  16. class BacktrackResend(str):
  17. """An edited prompt to send after rewinding to the turn it was picked from."""
  18. __slots__ = ("expected", "number", "ordinal", "session_id")
  19. def __new__(cls, text: str, *, ordinal: int, expected: str, session_id, number: int):
  20. obj = super().__new__(cls, text)
  21. obj.ordinal, obj.expected, obj.session_id, obj.number = ordinal, expected, session_id, number
  22. return obj
  23. def _one_line(text: str, limit: int) -> str:
  24. line = " ".join((text or "").split())
  25. return line if len(line) <= limit else line[: limit - 1] + "…"
  26. class CLIBacktrackMixin:
  27. _backtrack_state = None # picker: {"entries": [(ordinal, text)], newest first, "selected", "_scroll_offset"}
  28. _backtrack_edit = None # pending edit & resend: {"ordinal", "expected", "session_id", "number"}
  29. _backtrack_widget = None
  30. # ---- model ---------------------------------------------------------------------------
  31. def _backtrack_prompts(self) -> list[str]:
  32. """Editable text of every real user turn, oldest first (ordinal = index); the same
  33. predicate /undo counts turns with, so an ordinal here is the ordinal it rewinds."""
  34. from agent.context_compressor import user_originated_turn_view
  35. from agent.message_metadata import typed_prompt_content
  36. from hermes_cli.cli_session_mixin import _user_turn_indices
  37. history = self.conversation_history or []
  38. prompts = []
  39. for index in _user_turn_indices(history):
  40. view = user_originated_turn_view(history[index]) or {}
  41. prompts.append(self._undo_content_to_text(typed_prompt_content(view.get("content"), history[index])))
  42. return prompts
  43. def _backtrack_blocked(self) -> bool:
  44. return bool(self._agent_running or self._command_running or self._clarify_state or self._approval_state
  45. or self._sudo_state or self._secret_state or self._connection_state or self._slash_confirm_state
  46. or self._model_picker_state or self._command_palette_state)
  47. # ---- picker --------------------------------------------------------------------------
  48. def _open_backtrack_picker(self) -> bool:
  49. from cli import _cprint
  50. if self._backtrack_state or self._backtrack_blocked():
  51. return False
  52. prompts = self._backtrack_prompts()
  53. if not prompts:
  54. _cprint(f" {t('cli.backtrack.nothing')}")
  55. return False
  56. self._backtrack_state = {
  57. "entries": list(reversed(list(enumerate(prompts)))), "selected": 0, "_scroll_offset": 0}
  58. self._invalidate(min_interval=0.0)
  59. return True
  60. def _close_backtrack_picker(self) -> None:
  61. self._backtrack_state = None
  62. self._invalidate(min_interval=0.0)
  63. def _backtrack_selected(self):
  64. state = self._backtrack_state or {}
  65. entries = state.get("entries") or []
  66. selected = state.get("selected", 0)
  67. return entries[selected] if 0 <= selected < len(entries) else None
  68. def _get_backtrack_display_fragments(self):
  69. state = self._backtrack_state
  70. if not state:
  71. return []
  72. entries = state["entries"]
  73. total = len(entries)
  74. picked = self._backtrack_selected()
  75. hints = [t("cli.backtrack.keys_hint")]
  76. if picked is not None:
  77. ordinal, text = picked
  78. lines = (text or "").splitlines() or [""]
  79. hints += ["", t("cli.backtrack.preview_label", number=ordinal + 1, total=total)]
  80. hints += [f" {_one_line(line, _PREVIEW_CHARS)}" for line in lines[:_PREVIEW_LINES]]
  81. if len(lines) > _PREVIEW_LINES:
  82. hints.append(f" {t('cli.backtrack.more_lines', count=len(lines) - _PREVIEW_LINES)}")
  83. labels = [f"{ordinal + 1:>3}. {_one_line(text, _LABEL_CHARS)}" for ordinal, text in entries]
  84. return self._render_scroll_list_panel(
  85. state, t("cli.backtrack.title"), hints, labels, min_width=50, max_width=90, indent=" ")
  86. def _backtrack_move(self, delta: int) -> None:
  87. state = self._backtrack_state
  88. if state:
  89. state["selected"] = max(0, min(len(state["entries"]) - 1, state.get("selected", 0) + delta))
  90. self._invalidate(min_interval=0.0)
  91. def _backtrack_choose_edit(self) -> None:
  92. picked = self._backtrack_selected()
  93. self._close_backtrack_picker()
  94. if picked is not None:
  95. self._backtrack_begin_edit(*picked)
  96. def _backtrack_choose_fork(self) -> None:
  97. picked = self._backtrack_selected()
  98. self._close_backtrack_picker()
  99. if picked is not None:
  100. # Branching writes the DB and switches sessions: run it on the process loop like /branch.
  101. self._pending_input.put(f"/rewind fork {picked[0] + 1}")
  102. # ---- edit & resend -------------------------------------------------------------------
  103. def _backtrack_begin_edit(self, ordinal: int, text: str) -> None:
  104. self._backtrack_edit = {"ordinal": ordinal, "expected": text, "session_id": self.session_id,
  105. "number": ordinal + 1}
  106. self._prefill_input_buffer(text)
  107. def _backtrack_cancel_edit(self) -> bool:
  108. from cli import _cprint
  109. if self._backtrack_edit is None:
  110. return False
  111. self._backtrack_edit = None
  112. _cprint(f" {t('cli.backtrack.edit_cancelled')}")
  113. return True
  114. def _backtrack_apply_resend(self, item: BacktrackResend):
  115. """Rewind to the picked turn, then return the edited text to send (None: nothing sent)."""
  116. from cli import _cprint
  117. prompts = self._backtrack_prompts()
  118. if (item.session_id != self.session_id or item.ordinal >= len(prompts)
  119. or prompts[item.ordinal] != item.expected or self._agent_running):
  120. _cprint(f" {t('cli.backtrack.target_changed', number=item.number)}")
  121. self._prefill_input_buffer(str(item))
  122. return None
  123. rewound = self._rewind_to_user_ordinal(item.ordinal, failure_key="cli.backtrack.rewind_failed")
  124. if rewound is None:
  125. self._prefill_input_buffer(str(item))
  126. return None
  127. _cprint(f" {t('cli.backtrack.rewound', number=item.number, count=rewound[1])}")
  128. return str(item)
  129. # ---- fork ----------------------------------------------------------------------------
  130. def _backtrack_fork(self, ordinal: int) -> None:
  131. """/branch, then rewind the CHILD to just before ``ordinal`` and prefill that prompt."""
  132. from cli import _cprint
  133. parent_session_id = self.session_id
  134. self._handle_branch_command("/branch")
  135. if self.session_id == parent_session_id:
  136. return # /branch refused and said why; nothing changed
  137. rewound = self._rewind_to_user_ordinal(ordinal, failure_key="cli.backtrack.rewind_failed")
  138. if rewound is None:
  139. return
  140. _cprint(f" {t('cli.backtrack.forked', number=ordinal + 1, parent=parent_session_id)}")
  141. self._prefill_input_buffer(rewound[0])
  142. # ---- /rewind -------------------------------------------------------------------------
  143. def _handle_rewind_command(self, cmd_original: str) -> None:
  144. """/rewind opens the picker; ``/rewind N`` edits prompt N; ``/rewind fork N`` forks before it."""
  145. from cli import _cprint
  146. if self._agent_running:
  147. return _cprint(f" {t('cli.commands.shared.agent_busy', command='/rewind')}")
  148. args = cmd_original.split()[1:]
  149. fork = bool(args) and args[0].lower() == "fork"
  150. args = args[1:] if fork else args
  151. if not args and not fork:
  152. self._open_backtrack_picker()
  153. return None
  154. if len(args) != 1 or not args[0].isdigit():
  155. return _cprint(f" {t('cli.backtrack.usage')}")
  156. prompts = self._backtrack_prompts()
  157. number = int(args[0])
  158. if not prompts:
  159. return _cprint(f" {t('cli.backtrack.nothing')}")
  160. if not 1 <= number <= len(prompts):
  161. return _cprint(f" {t('cli.backtrack.invalid', value=args[0], total=len(prompts))}")
  162. if fork:
  163. return self._backtrack_fork(number - 1)
  164. self._backtrack_begin_edit(number - 1, prompts[number - 1])
  165. return None
  166. # ---- TUI hooks (wrap CLITuiMixin / CLITuiRuntimeMixin via super()) --------------------
  167. def _tui_handle_double_escape(self, event):
  168. """Idle + empty composer + no overlay: open the picker. A draft is still discarded (and a
  169. pending edit cancelled with it); mid-turn behaviour is unchanged."""
  170. buf = event.app.current_buffer
  171. if not (buf.text or self._attached_images):
  172. if self._backtrack_edit is not None:
  173. self._backtrack_cancel_edit()
  174. elif not self._backtrack_blocked():
  175. self._open_backtrack_picker()
  176. return None
  177. self._backtrack_cancel_edit()
  178. return super()._tui_handle_double_escape(event)
  179. def _tui_submit_buffer(self, event, buf):
  180. from cli import _looks_like_slash_command
  181. edit = self._backtrack_edit
  182. if edit is None:
  183. return super()._tui_submit_buffer(event, buf)
  184. text = buf.text.strip()
  185. if not text and not self._attached_images:
  186. self._backtrack_cancel_edit()
  187. return None
  188. if (self._agent_running or self._attached_images or _looks_like_slash_command(text)
  189. or text.startswith("!")):
  190. self._backtrack_cancel_edit()
  191. return super()._tui_submit_buffer(event, buf)
  192. self._backtrack_edit = None
  193. self._inline_pastes(buf)
  194. self._pending_input.put(BacktrackResend(buf.text.strip(), **edit))
  195. buf.reset(append_to_history=True)
  196. event.app.invalidate()
  197. return None
  198. def _tui_process_one_input(self, user_input):
  199. if isinstance(user_input, BacktrackResend):
  200. user_input = self._backtrack_apply_resend(user_input)
  201. if user_input is None:
  202. return None
  203. return super()._tui_process_one_input(user_input)
  204. def _tui_clear_or_exit(self, event) -> None:
  205. if self._backtrack_cancel_edit() and not (event.app.current_buffer.text or self._attached_images):
  206. return None # the press cancelled the pending edit; never exit on it
  207. return super()._tui_clear_or_exit(event)
  208. def _tui_handle_ctrl_c(self, event):
  209. if self._backtrack_state:
  210. self._close_backtrack_picker()
  211. return None
  212. return super()._tui_handle_ctrl_c(event)
  213. def _tui_hint_text(self):
  214. hint = super()._tui_hint_text()
  215. if not hint and self._backtrack_edit is not None and not self._backtrack_state:
  216. return [("class:hint", " " + t("cli.backtrack.editing_hint", number=self._backtrack_edit["number"]))]
  217. return hint
  218. def _tui_hint_height(self):
  219. if self._backtrack_edit is not None:
  220. return 1
  221. return super()._tui_hint_height()
  222. def _get_extra_tui_widgets(self) -> list:
  223. extra = super()._get_extra_tui_widgets()
  224. return [self._backtrack_widget, *extra] if self._backtrack_widget is not None else extra
  225. def _tui_build_layout(self, kb):
  226. self._backtrack_widget = self._tui_overlay_widget(self._get_backtrack_display_fragments, "_backtrack_state")
  227. return super()._tui_build_layout(kb)
  228. def _tui_build_key_bindings(self):
  229. """Picker keys, registered after the generic ones so they win while it is open (the
  230. last matching binding wins); Keys.Any swallows typing so nothing lands in the composer."""
  231. from prompt_toolkit.filters import Condition
  232. from prompt_toolkit.keys import Keys
  233. kb = super()._tui_build_key_bindings()
  234. picker = Condition(lambda: bool(self._backtrack_state))
  235. kb.add(Keys.Any, filter=picker)(lambda event: None)
  236. kb.add("up", filter=picker)(lambda event: self._backtrack_move(-1))
  237. kb.add("down", filter=picker)(lambda event: self._backtrack_move(1))
  238. kb.add("enter", filter=picker, eager=True)(lambda event: self._backtrack_choose_edit())
  239. kb.add("f", filter=picker)(lambda event: self._backtrack_choose_fork())
  240. kb.add("escape", filter=picker, eager=True)(lambda event: self._close_backtrack_picker())
  241. return kb