Skip to content

The agent that grows with you

fix(tui): heartbeat ticks share the /loop idle poll and rewind when no turn starts

Teknium5106e939e0b3
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]
new file mode 100644
index 00000000000..788e359ca41
--- /dev/null
+++ b/contributors/emails/[email protected]
@@ -0,0 +1,2 @@
+Halldrix
+# PR #102118 /heartbeat TUI driver
diff --git a/hermes_cli/heartbeat.py b/hermes_cli/heartbeat.py
index ed5dddbace2..d3f440d9ed2 100644
--- a/hermes_cli/heartbeat.py
+++ b/hermes_cli/heartbeat.py
@@ -140,6 +140,7 @@ class HeartbeatManager:
def __init__(self, session_id: str):
self.session_id = session_id
self._state: Optional[HeartbeatState] = load_heartbeat(session_id)
+ self._last_claim: Optional[tuple[float, int]] = None # (last_fired_at, fire_count) before the last due_prompt
@property
def state(self) -> Optional[HeartbeatState]:
@@ -206,11 +207,28 @@ class HeartbeatManager:
s = self._state
if s is None or not s.is_due(now):
return None
+ self._last_claim = (s.last_fired_at, s.fire_count)
s.last_fired_at = now if now is not None else time.time()
s.fire_count += 1
save_heartbeat(self.session_id, s)
return s.render_prompt()
+ def abandon_fire(self) -> bool:
+ """Rewind the fire recorded by the last :meth:`due_prompt` whose turn never started, so the tick stays
+ due for the next poll instead of being silently consumed. Mirrors ``LoopManager.abandon_tick``. Skipped
+ (False) when the persisted state moved on — a pause/resume/clear that landed in between wins."""
+ claim, s = self._last_claim, self._state
+ if claim is None or s is None:
+ return False
+ current = load_heartbeat(self.session_id)
+ if current is None or current.status != "active" or (current.last_fired_at, current.fire_count) != (
+ s.last_fired_at, s.fire_count):
+ return False
+ s.last_fired_at, s.fire_count = claim
+ self._last_claim = None
+ save_heartbeat(self.session_id, s)
+ return True
+
def migrate_heartbeat_to_session(old_session_id: str, new_session_id: str) -> bool:
"""Carry a heartbeat across a compression session rotation (copy to child, archive parent, never raise).
diff --git a/tests/tui_gateway/test_heartbeat_tui_tick.py b/tests/tui_gateway/test_heartbeat_tui_tick.py
index 6b9d02f7cf4..5052330d210 100644
--- a/tests/tui_gateway/test_heartbeat_tui_tick.py
+++ b/tests/tui_gateway/test_heartbeat_tui_tick.py
@@ -1,106 +1,145 @@
-"""Tests for the TUI/Desktop heartbeat driver (issue #102056).
+"""/heartbeat firing from the TUI/Desktop session-owner process (#102056, #103044).
-The slash worker that parses ``/heartbeat`` starts a watchdog thread in its
-own process, where the queued prompt is never consumed. The real driver lives
-in ``tui_gateway/server._maybe_fire_tui_heartbeat_tick``, which polls the
-session-owner process and re-enters the live session via ``_run_prompt_submit``.
+The slash worker that parses ``/heartbeat`` runs a HermesCLI whose watchdog queues the due prompt
+into its own ``_pending_input`` — a queue no turn loop drains in that process. The per-session
+notification poller (the same driver that fires ``/loop``) must poll the persisted HeartbeatManager
+and re-enter the live session through ``_run_prompt_submit``.
"""
+from __future__ import annotations
+
+import importlib
+import threading
import time
-from types import SimpleNamespace
+from pathlib import Path
+from unittest.mock import MagicMock, patch
import pytest
-import tui_gateway.server as server
-from hermes_cli.heartbeat import HeartbeatManager, HeartbeatState
-
-
-def _due_manager(session_id):
- """A HeartbeatManager whose state is already due, bypassing SessionDB."""
- mgr = HeartbeatManager.__new__(HeartbeatManager)
- mgr.session_id = session_id
- # created long ago so is_due() is immediately true.
- mgr._state = HeartbeatState(
- prompt="report backend health",
- interval_seconds=60,
- status="active",
- created_at=time.time() - 3600,
- )
- return mgr
-
-
-def _idle_session():
- return {
- "agent": SimpleNamespace(),
- "session_key": "hb-tui-key",
- "history": [],
- "history_lock": server.threading.Lock(),
- "running": False,
- }
-
-
-def test_tui_heartbeat_fires_when_idle_and_due(monkeypatch):
- submitted = []
-
- def _submit(_rid, sid, session, text):
- submitted.append(text)
- monkeypatch.setattr(server, "_run_prompt_submit", _submit)
- monkeypatch.setattr(server, "_emit", lambda *a, **k: None)
- monkeypatch.setattr(
- "hermes_cli.heartbeat.HeartbeatManager", lambda session_id: _due_manager(session_id)
- )
+def hermes_home(tmp_path, monkeypatch):
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ from hermes_cli import goals
- session = _idle_session()
- server._maybe_fire_tui_heartbeat_tick("sid-hb", session)
+ goals._DB_CACHE.clear()
+ yield home
+ goals._DB_CACHE.clear()
- assert len(submitted) == 1
- assert "report backend health" in submitted[0]
- assert session["running"] is True
+def server(hermes_home):
+ with patch.dict("sys.modules", {"hermes_cli.env_loader": MagicMock(), "hermes_cli.banner": MagicMock()}):
+ mod = importlib.import_module("tui_gateway.server")
+ yield mod
+ mod._sessions.clear()
-def test_tui_heartbeat_skips_when_busy(monkeypatch):
- submitted = []
- def _submit(_rid, sid, session, text):
- submitted.append(text)
+def session(server):
+ sid, key = "sid-hb-test", "tui-hb-session-1"
+ s = {"session_key": key, "history": [], "history_lock": threading.Lock(), "history_version": 0,
+ "running": False, "attached_images": [], "cols": 120, "agent": MagicMock()}
+ server._sessions[sid] = s
+ return sid, key, s
- monkeypatch.setattr(server, "_run_prompt_submit", _submit)
- monkeypatch.setattr(server, "_emit", lambda *a, **k: None)
- monkeypatch.setattr(
- "hermes_cli.heartbeat.HeartbeatManager", lambda session_id: _due_manager(session_id)
- )
- session = _idle_session()
- session["running"] = True # an in-flight turn owns the session
- server._maybe_fire_tui_heartbeat_tick("sid-hb", session)
+def _arm_due(key: str):
+ from hermes_cli.heartbeat import HeartbeatManager, save_heartbeat
- assert submitted == []
- # The tick stays due; the driver never claims the session.
- assert session["running"] is True
-
-
-def test_tui_heartbeat_skips_when_not_due(monkeypatch):
- submitted = []
-
- def _submit(_rid, sid, session, text):
- submitted.append(text)
-
- monkeypatch.setattr(server, "_run_prompt_submit", _submit)
- monkeypatch.setattr(server, "_emit", lambda *a, **k: None)
-
- mgr = HeartbeatManager.__new__(HeartbeatManager)
- mgr.session_id = "hb-tui-key"
- mgr._state = HeartbeatState(
- prompt="not yet",
- interval_seconds=60,
- status="active",
- created_at=time.time(), # just armed — not due
- )
- monkeypatch.setattr("hermes_cli.heartbeat.HeartbeatManager", lambda session_id: mgr)
+ mgr = HeartbeatManager(key)
+ state = mgr.set("report backend health", 60)
+ state.created_at = time.time() - 3600
+ save_heartbeat(key, state)
+ return mgr
- session = _idle_session()
- server._maybe_fire_tui_heartbeat_tick("sid-hb", session)
- assert submitted == []
- assert session["running"] is False
\ No newline at end of file
+def _submits(server, submit):
+ return patch.object(server, "_run_prompt_submit", submit), patch.object(server, "_emit")
+
+
+def test_notification_poller_fires_due_heartbeat_when_idle(server, session):
+ """The session-owner poller loop itself dispatches a due heartbeat exactly once; the same state on
+ the base loop never fired (armed-but-dead)."""
+ sid, key, s = session
+ _arm_due(key)
+ dispatched: list[str] = []
+
+ def submit(rid, sid_, session_, text, **kw):
+ dispatched.append(text)
+ return True
+
+ stop = threading.Event()
+ p_submit, p_emit = _submits(server, submit)
+ with p_submit, p_emit:
+ t = threading.Thread(target=server._notification_poller_loop, args=(stop, sid, s), daemon=True)
+ t.start()
+ deadline = time.monotonic() + 8
+ while not dispatched and time.monotonic() < deadline:
+ time.sleep(0.1)
+ stop.set()
+ t.join(timeout=5)
+
+ from hermes_cli.heartbeat import load_heartbeat
+
+ assert len(dispatched) == 1 and "report backend health" in dispatched[0]
+ assert s["running"] is True # claimed for the heartbeat turn
+ assert load_heartbeat(key).fire_count == 1 and not load_heartbeat(key).is_due()
+
+
[email protected]("running,due", [(True, True), (False, False)])
+def test_heartbeat_tick_defers_when_busy_or_not_due(server, session, running, due):
+ sid, key, s = session
+ mgr = _arm_due(key)
+ if not due:
+ mgr.state.created_at = time.time()
+ from hermes_cli.heartbeat import save_heartbeat
+
+ save_heartbeat(key, mgr.state)
+ s["running"] = running
+ p_submit, p_emit = _submits(server, MagicMock())
+ with p_submit as submit, p_emit:
+ server._maybe_fire_tui_heartbeat_tick(sid, s)
+ submit.assert_not_called()
+ from hermes_cli.heartbeat import load_heartbeat
+
+ assert s["running"] is running # a busy session is never released by the poller
+ assert load_heartbeat(key).fire_count == 0 # tick not consumed — still due when the session frees up
+
+
[email protected]("failure", ["refused", "raised"])
+def test_heartbeat_dispatch_that_never_starts_a_turn_stays_due(server, session, failure):
+ """A refused/failed submit must release the claim AND rewind the persisted fire, otherwise the tick is
+ silently consumed (fire_count advanced, nothing ran) — the Desktop-side follow-up bug in #104011."""
+ sid, key, s = session
+ _arm_due(key)
+
+ def submit(*a, **k):
+ if failure == "raised":
+ raise RuntimeError("transport down")
+ with s["history_lock"]:
+ s["running"] = False # _admit_prompt_turn refusal releases itself and returns False
+ return False
+
+ p_submit, p_emit = _submits(server, submit)
+ with p_submit, p_emit:
+ server._maybe_fire_tui_heartbeat_tick(sid, s)
+
+ from hermes_cli.heartbeat import load_heartbeat
+
+ assert s["running"] is False
+ assert load_heartbeat(key).fire_count == 0 and load_heartbeat(key).is_due()
+
+
+def test_abandon_fire_never_overwrites_a_concurrent_pause(hermes_home):
+ from hermes_cli.heartbeat import HeartbeatManager, load_heartbeat
+
+ key = "hb-abandon-race"
+ driver = _arm_due(key)
+ assert driver.due_prompt() is not None
+ HeartbeatManager(key).pause() # lands between the claim and the failed dispatch
+ assert driver.abandon_fire() is False
+ assert load_heartbeat(key).status == "paused" and load_heartbeat(key).fire_count == 1
diff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.py
index 1cef2242be7..f00e1ec9963 100644
--- a/tui_gateway/session_notifications.py
+++ b/tui_gateway/session_notifications.py
@@ -112,8 +112,7 @@ def _notification_event_dedup_key(evt: dict) -> tuple:
# Mirror gateway/kanban_watchers.py TERMINAL_KINDS: claim silent kinds (archived/unblocked) too so the cursor advances
# past them and they can't wedge a later completed/blocked event behind an unclaimed row.
_KANBAN_NOTIFY_KINDS = ("completed", "blocked", "gave_up", "crashed", "timed_out", "status", "archived", "unblocked")
-_KANBAN_POLL_SECONDS = _LOOP_POLL_SECONDS = 5.0
-_HEARTBEAT_POLL_SECONDS = 5.0
+_KANBAN_POLL_SECONDS = _LOOP_POLL_SECONDS = 5.0 # /loop and /heartbeat share one idle-poll cadence
def _notif_release_turn(session: dict) -> None:
@@ -175,39 +174,38 @@ def _notif_slash_loop_tick(rid: str, sid: str, session: dict, mgr, wakeup: str)
def _maybe_fire_tui_heartbeat_tick(sid: str, session: dict) -> None:
- """Fire a due /heartbeat prompt for an idle TUI/Desktop session (issue #102056).
-
- The slash-worker process that parses ``/heartbeat`` starts a heartbeat watchdog thread in its
- OWN process, where the queued prompt has no turn loop to consume it — armed-but-dead. The
- durable state lives in SessionDB, so the real driver belongs in the session-owner process:
- this mirror of ``_maybe_fire_tui_loop_tick`` polls from the per-session notification poller
- and re-enters the live session through ``_run_prompt_submit`` as a plain user turn (alternation
- + prompt caching untouched).
+ """Fire a due /heartbeat prompt for an idle TUI/Desktop/dashboard session (#102056, #103044).
+
+ ``/heartbeat`` runs in the slash worker, whose CLI watchdog queues the due prompt into a
+ ``_pending_input`` no turn loop ever drains — armed-but-dead. State is durable in SessionDB, so
+ the session-owner process drives firing exactly like ``_maybe_fire_tui_loop_tick``: claim the
+ idle session first (a racing user prompt wins), then re-enter through ``_run_prompt_submit`` as a
+ plain user turn. A dispatch that never starts a turn rewinds the persisted fire so the tick stays
+ due instead of being silently consumed.
"""
try:
from hermes_cli.heartbeat import HeartbeatManager
except Exception:
return
- sid_key = session.get("session_key") or ""
- if not sid_key:
+ if not (sid_key := session.get("session_key") or ""):
return
mgr = HeartbeatManager(session_id=sid_key)
- if not mgr.is_active() or not mgr.state.is_due():
- return
- if not _notif_claim_turn(session):
- return # busy — tick coalesces to the next idle poll
- prompt = mgr.due_prompt()
- if not prompt:
+ if not mgr.is_active() or not mgr.state.is_due() or not _notif_claim_turn(session):
+ return # not due, or busy — the tick coalesces to the next idle poll
+ if not (prompt := mgr.due_prompt()):
_notif_release_turn(session)
return
- rid = f"__heartbeat__{int(time.time() * 1000)}"
+ started = False
try:
- _emit("status.update", sid, {"kind": "heartbeat", "text": "♥ heartbeat firing…"})
- _emit("message.start", sid)
- _run_prompt_submit(rid, sid, session, prompt)
+ _emit("status.update", sid, {"kind": "heartbeat", "text": f"♥ heartbeat #{mgr.state.fire_count} firing…"})
+ started = bool(_run_prompt_submit(f"__heartbeat__{int(time.time() * 1000)}", sid, session, prompt))
except Exception as exc:
_notif_log_failure("heartbeat dispatch failed", exc)
+ if not started:
+ # _run_prompt_submit releases ``running`` itself when it refuses the turn; make it unconditional.
_notif_release_turn(session)
+ with contextlib.suppress(Exception):
+ mgr.abandon_fire()
def _maybe_fire_tui_loop_tick(sid: str, session: dict) -> None:
@@ -453,26 +451,18 @@ def _notification_poller_loop(stop_event: threading.Event, sid: str, session: di
emitted: set = set() # dedup re-queued events so one completion isn't emitted 50 times while busy
handle = lambda evt, deferred: _notif_handle_event( # noqa: E731
sid, session, evt, emitted, process_registry, format_process_notification, deferred)
- last_kanban_poll = last_loop_poll = last_heartbeat_poll = 0.0
+ last_kanban_poll = last_loop_poll = 0.0
while not stop_event.is_set() and not session.get("_finalized"):
now = time.monotonic()
- # ── /heartbeat driver ─────────────────────────────────────────────────
- # The slash worker that parses /heartbeat cannot drive firing (its watchdog queues into a process that
- # never runs turns), so the session-owner process polls for due heartbeats itself (#102056).
- if now - last_heartbeat_poll >= _HEARTBEAT_POLL_SECONDS:
- last_heartbeat_poll = now
- try:
- _maybe_fire_tui_heartbeat_tick(sid, session)
- except Exception as hb_exc:
- _notif_log_failure("heartbeat poll failed", hb_exc)
- # /loop wakeup driver: fire a due tick for THIS session while idle (same claim-under-lock as kanban dispatch).
- # An active non-parked /goal owns the idle boundary and defers it.
+ # /loop and /heartbeat wakeup drivers: fire a due tick for THIS session while idle (same claim-under-lock
+ # as kanban dispatch). An active non-parked /goal owns the idle boundary and defers the loop tick.
if now - last_loop_poll >= _LOOP_POLL_SECONDS:
last_loop_poll = now
- try:
- _maybe_fire_tui_loop_tick(sid, session)
- except Exception as loop_exc:
- _notif_log_failure("loop wakeup poll failed", loop_exc)
+ for what, fire in (("loop wakeup", _maybe_fire_tui_loop_tick), ("heartbeat", _maybe_fire_tui_heartbeat_tick)):
+ try:
+ fire(sid, session)
+ except Exception as tick_exc:
+ _notif_log_failure(f"{what} poll failed", tick_exc)
if now - last_kanban_poll >= _KANBAN_POLL_SECONDS:
last_kanban_poll = now
_notif_poll_kanban(sid, session)
diff --git a/website/docs/user-guide/features/heartbeat.md b/website/docs/user-guide/features/heartbeat.md
index 69984a3d7fa..87c49e25f8a 100644
--- a/website/docs/user-guide/features/heartbeat.md
+++ b/website/docs/user-guide/features/heartbeat.md
@@ -37,7 +37,7 @@ Rule of thumb: if the recurring prompt needs the conversation's context, use `/h
| `/heartbeat resume` | Resume (re-anchors the timer — no instant stale fire). |
| `/heartbeat clear` | Remove the heartbeat. |
-`/hb` is an alias. Works on the CLI and gateway platforms (on Slack, use `/hermes heartbeat …`).
+`/hb` is an alias. Works on the CLI, the TUI / Desktop app, and gateway platforms (on Slack, use `/hermes heartbeat …`).
## Behavior details