cli_session_dock.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. """Goal, loop + queued-prompt rows for the classic CLI live-work dock.
  2. Sibling of ``cli_process_dock``: the dock paints an active ``/goal``, a standing ``/loop`` with its
  3. countdown, and the prompts waiting in ``/queue`` around the subagent and process blocks, so they are
  4. visible while the agent works instead of only through ``/goal status``, ``/loop status`` and
  5. ``/queue list``.
  6. """
  7. from __future__ import annotations
  8. import math
  9. import time
  10. # Queued prompts drain one per turn; past this many the dock shows a ``+N more`` line.
  11. QUEUE_ROWS = 3
  12. def sync_automation(cli) -> None:
  13. """Re-read the goal/loop managers' mirrored state once after the gateway flagged it changed mid-turn
  14. (``_mark_automation_stale``): one ``state`` round trip per change, none while nothing moves."""
  15. if not getattr(cli, "_automation_stale", False):
  16. return
  17. cli._automation_stale = False
  18. for attr in ("_goal_manager", "_loop_manager"):
  19. mgr = getattr(cli, attr, None)
  20. if mgr is not None and mgr.session_id == getattr(cli, "session_id", None):
  21. mgr.refresh()
  22. def goal_line(cli) -> str:
  23. """``GoalManager.status_line()`` for an active or paused goal, else ``''``.
  24. Reads only the manager the CLI already holds for its current session: the dock refreshes on
  25. the spinner thread every second and must never be the thing that opens state.db.
  26. """
  27. mgr = getattr(cli, "_goal_manager", None)
  28. if mgr is None or mgr.session_id != getattr(cli, "session_id", None) or not mgr.has_goal():
  29. return ""
  30. return mgr.status_line()
  31. def countdown(seconds: float) -> str:
  32. """Time left until the next wakeup, rounded UP: whole minutes until the last one, then seconds.
  33. Minute steps keep an idle prompt's dock to one repaint a minute (the spinner thread repaints only
  34. when the dock text changes); per-second repaints of a 45-minute wait would fight terminal viewport
  35. restoration for nothing.
  36. """
  37. left = max(0, math.ceil(seconds))
  38. if left < 60:
  39. return f"{left}s"
  40. hours, minutes = divmod(math.ceil(left / 60), 60)
  41. return f"{hours}h{minutes:02d}m" if hours else f"{minutes}m"
  42. def loop_row(cli, now: float | None = None) -> tuple[str, str, str]:
  43. """``(badge, line, prompt)`` for an active or paused /loop, else ``('', '', '')``.
  44. ``line`` is the expanded dock row (``↻ loop · every 5m · 2 runs · next in 4m · <prompt>``),
  45. ``badge`` the collapsed heading's count fragment (``↻ loop next in 4m``). Same rule as :func:`goal_line`:
  46. only the manager the CLI already holds is read, never state.db.
  47. """
  48. mgr = getattr(cli, "_loop_manager", None)
  49. # One read of ``state``: the input thread's ``/loop stop`` sets it to None under this spinner-thread poll.
  50. s = mgr.state if mgr is not None and mgr.session_id == getattr(cli, "session_id", None) else None
  51. if s is None or s.status not in {"active", "paused"}:
  52. return "", "", ""
  53. runs = f"{s.ticks_fired}/{s.times} runs" if s.times else f"{s.ticks_fired} run{'s' if s.ticks_fired != 1 else ''}"
  54. if s.status == "paused":
  55. reason = f" · {s.paused_reason}" if s.paused_reason else ""
  56. return "⏸ loop paused", f"⏸ loop paused{reason} · {runs} · {s.prompt}", s.prompt
  57. if s.awaiting_response:
  58. when = "running now"
  59. else:
  60. remaining = s.next_due_at - (time.time() if now is None else now)
  61. when = f"next in {countdown(remaining)}" if remaining > 0 else "due, waiting for idle"
  62. return f"↻ loop {when}", f"↻ loop · {s.cadence_label()} · {runs} · {when} · {s.prompt}", s.prompt
  63. def _prompt_text(item) -> str:
  64. if isinstance(item, tuple): # (text, images) from an image-attached submit
  65. item = item[0]
  66. # TimelineNotification carries a compact title; voice/seeded sentinels wrap their text.
  67. text = getattr(item, "display_text", None) or getattr(item, "text", None) or str(item)
  68. return " ".join(str(text).split())
  69. def queued_prompts(cli) -> list[str]:
  70. """One-line previews of the turns waiting in ``_pending_input``, oldest first."""
  71. from hermes_cli.gateway_tools_notify import gateway_store
  72. owned: list = []
  73. store = gateway_store(cli) if getattr(cli, "session_id", None) else None
  74. if store is not None:
  75. # The gateway's FIFO runs first (#134889 N5): its queued admissions as the owner last published them.
  76. from hermes_cli.gateway_queue import published_queue
  77. owned = published_queue(cli, store)
  78. pending = getattr(cli, "_pending_input", None)
  79. if pending is None:
  80. return [text for text in map(_prompt_text, owned) if text]
  81. with pending.mutex:
  82. items = list(pending.queue)
  83. return [text for text in map(_prompt_text, owned + items) if text]