prompt_stash.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. """Ctrl+S prompt stash — pure state machine for the classic CLI composer.
  2. No prompt_toolkit imports so it can be unit tested directly; ``cli.py`` owns only the keybinding
  3. and the rendering. Newest-first: index 0 is always the most recently stashed draft, so "undo my
  4. last Ctrl+S" is a single keystroke.
  5. """
  6. from __future__ import annotations
  7. import time
  8. from dataclasses import dataclass, field
  9. from typing import Any, List, Optional, Sequence, Tuple
  10. # Single-line preview length for the browse panel.
  11. PREVIEW_WIDTH = 60
  12. # Cap the stack so a user leaning on Ctrl+S can't grow it without bound.
  13. MAX_STASH_ITEMS = 20
  14. def build_preview(text: str, width: int = PREVIEW_WIDTH) -> str:
  15. """Collapse a possibly multi-line draft into one preview line."""
  16. if not text:
  17. return ""
  18. flat = text.replace("\r\n", "\n").replace("\r", "\n")
  19. flat = flat.replace("\n", " ⏎ ").replace("\t", " ")
  20. flat = " ".join(flat.split())
  21. if width > 1 and len(flat) > width:
  22. return flat[: width - 1] + "…"
  23. return flat
  24. @dataclass
  25. class StashEntry:
  26. """One parked draft: exact text plus any images that were attached."""
  27. text: str
  28. images: list[Any] = field(default_factory=list)
  29. stashed_at: float = 0.0
  30. preview: str = ""
  31. def as_dict(self) -> dict:
  32. """Shape ``HermesCLI._render_stash_panel`` consumes."""
  33. return {"text": self.text, "images": list(self.images), "stashed_at": self.stashed_at, "preview": self.preview}
  34. class PromptStash:
  35. """Session-scoped stack of parked composer drafts."""
  36. def __init__(self, *, max_items: int = MAX_STASH_ITEMS, clock=None):
  37. self._items: list[StashEntry] = []
  38. self._max_items = max(1, int(max_items))
  39. self._clock = clock or time.monotonic
  40. self.panel_open = False
  41. self.panel_cursor = 0
  42. def __len__(self) -> int:
  43. return len(self._items)
  44. @property
  45. def items(self) -> list[StashEntry]:
  46. """Newest-first list of entries (a copy — mutate via the API)."""
  47. return list(self._items)
  48. def panel_rows(self) -> list[dict]:
  49. return [e.as_dict() for e in self._items]
  50. def indicator(self) -> str:
  51. """Status-bar indicator: ``📌 2`` idle, ``📌 2 ▲`` while browsing, ``""`` when empty."""
  52. n = len(self._items)
  53. return "" if not n else f"📌 {n} ▲" if self.panel_open else f"📌 {n}"
  54. def placeholder_hint(self) -> str:
  55. """Composer placeholder text advertising the stashed draft."""
  56. n = len(self._items)
  57. if n == 1:
  58. return f"Ctrl+S to restore: {self._items[0].preview}"
  59. return f"Ctrl+S to browse {n} stashed drafts" if n else ""
  60. def stash(self, text: str, images: Optional[Sequence[Any]] = None) -> bool:
  61. """Push a draft. A blank buffer with no images is a no-op (returns False) so Ctrl+S on an
  62. empty composer triggers the restore half of the gesture instead of pushing junk.
  63. """
  64. if not (text or "").strip() and not images:
  65. return False
  66. entry = StashEntry(text=text or "", images=list(images or []), stashed_at=self._clock(),
  67. preview=build_preview(text or "") or "(images only)")
  68. self._items.insert(0, entry)
  69. del self._items[self._max_items:] # drop the oldest past the cap
  70. self.close_panel() # a push invalidates any open browse session
  71. return True
  72. def pop(self, index: int = 0) -> Optional[tuple[str, list[Any]]]:
  73. """Remove and return ``(text, images)`` at ``index``, or None."""
  74. if not 0 <= index < len(self._items):
  75. return None
  76. entry = self._items.pop(index)
  77. if not self._items:
  78. self.panel_open = False
  79. self.panel_cursor = self._clamp_cursor(self.panel_cursor)
  80. return entry.text, list(entry.images)
  81. def peek(self, index: int = 0) -> Optional[StashEntry]:
  82. return self._items[index] if 0 <= index < len(self._items) else None
  83. def clear(self) -> None:
  84. self._items.clear()
  85. self.close_panel()
  86. # ------------------------------------------------------------ panel state
  87. def _clamp_cursor(self, value: int) -> int:
  88. return max(0, min(int(value), len(self._items) - 1)) if self._items else 0
  89. def open_panel(self) -> bool:
  90. """Open the browse panel. False when there is nothing to browse."""
  91. if not self._items:
  92. return False
  93. self.panel_open = True
  94. self.panel_cursor = 0
  95. return True
  96. def close_panel(self) -> None:
  97. self.panel_open = False
  98. self.panel_cursor = 0
  99. def move_cursor(self, delta: int) -> int:
  100. """Move the panel cursor, clamped to the list bounds."""
  101. self.panel_cursor = self._clamp_cursor(self.panel_cursor + int(delta))
  102. return self.panel_cursor
  103. def delete_at_cursor(self) -> bool:
  104. """Delete the highlighted entry. False when there was nothing to drop."""
  105. if not self._items:
  106. return False
  107. idx = self._clamp_cursor(self.panel_cursor)
  108. self._items.pop(idx)
  109. if not self._items:
  110. self.close_panel()
  111. else:
  112. self.panel_cursor = self._clamp_cursor(idx)
  113. return True
  114. def restore_at_cursor(self) -> Optional[tuple[str, list[Any]]]:
  115. """Pop the highlighted entry and close the panel."""
  116. if not self._items:
  117. return None
  118. result = self.pop(self._clamp_cursor(self.panel_cursor))
  119. self.close_panel()
  120. return result
  121. # Outcomes of a single Ctrl+S press.
  122. ACTION_NOOP = "noop"
  123. ACTION_STASHED = "stashed"
  124. ACTION_RESTORED = "restored"
  125. ACTION_OPEN_PANEL = "open_panel"
  126. ACTION_CLOSE_PANEL = "close_panel"
  127. def resolve_ctrl_s(
  128. stash: PromptStash, buffer_text: str, images: Optional[Sequence[Any]] = None
  129. ) -> tuple[str, Optional[tuple[str, list[Any]]]]:
  130. """Decide what one Ctrl+S press does. Returns ``(action, payload)`` where ``payload`` is
  131. ``(text, images)`` for :data:`ACTION_RESTORED`, else None.
  132. """
  133. # Panel open → Ctrl+S is the "close it" escape hatch.
  134. if stash.panel_open:
  135. stash.close_panel()
  136. return ACTION_CLOSE_PANEL, None
  137. # Something to park → park it (onto a stack, so an earlier draft is still reachable).
  138. if (buffer_text or "").strip() or images:
  139. return (ACTION_STASHED if stash.stash(buffer_text, images) else ACTION_NOOP), None
  140. # Empty buffer → restore half of the gesture.
  141. count = len(stash)
  142. if count == 0:
  143. return ACTION_NOOP, None
  144. if count == 1:
  145. return ACTION_RESTORED, stash.pop(0)
  146. stash.open_panel()
  147. return ACTION_OPEN_PANEL, None