The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): scheduled heartbeats end silently, emit no progress and quote no stale message
teknium1680735174a09
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex e00e36ea0b2..3bf7d2990b2 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -111,10 +111,7 @@ def _float_env(name: str, default: float) -> float:return _or_default(lambda: float(raw) if raw else default, default)-def _thread_metadata_for_source(- source, reply_to_message_id: str | None = None, *,- allow_source_message_id_fallback: bool = True,-) -> dict | None:+def _thread_metadata_for_source(source, reply_to_message_id: str | None = None) -> dict | None:"""Platform-aware thread metadata for adapter sends. Telegram DM topics route with``message_thread_id`` + a reply anchor; anchorless synthetic/resumed sends fall back to``direct_messages_topic_id`` when supported."""@@ -129,13 +126,10 @@ def _thread_metadata_for_source(if not metadata:return Noneif platform == "telegram" and getattr(source, "chat_type", None) == "dm":+ metadata["telegram_dm_topic_reply_fallback"] = Trueif str(thread_id) not in {"", "1"}:metadata["direct_messages_topic_id"] = str(thread_id)- anchor = reply_to_message_id- if anchor is None and allow_source_message_id_fallback:- anchor = getattr(source, "message_id", None)- if allow_source_message_id_fallback:- metadata["telegram_dm_topic_reply_fallback"] = True+ anchor = reply_to_message_id or getattr(source, "message_id", None)if anchor is not None:metadata["telegram_reply_to_message_id"] = str(anchor)# Routed profile (multiplex / profile_routes): outbound prune paths must not assume the@@ -148,12 +142,7 @@ def _thread_metadata_for_source(def _thread_metadata_for_event(event) -> dict | None:"""``_thread_metadata_for_source`` for an event, anchored on its reply id."""- scheduled_heartbeat = bool(getattr(event, "_heartbeat_session_id", None))- return _thread_metadata_for_source(- event.source,- _reply_anchor_for_event(event),- allow_source_message_id_fallback=not scheduled_heartbeat,- )+ return _thread_metadata_for_source(event.source, _reply_anchor_for_event(event))def _mark_notify_metadata(metadata: dict | None) -> dict:@@ -4078,8 +4067,8 @@ class BasePlatformAdapter(ABC):metadata: Optional[dict]) -> Optional[asyncio.Task]:"""Spawn the typing-refresh task, or None when ``typing_indicator=False``.``stop_event`` is passed only when the (possibly overridden) ``_keep_typing`` accepts it."""- if (not getattr(self.config, "typing_indicator", True)- or getattr(event, "_heartbeat_session_id", None)):+ # A scheduled heartbeat is proactive work: no typing indicator until it has something to say.+ if not getattr(self.config, "typing_indicator", True) or getattr(event, "_heartbeat_session_id", None):return Nonekwargs: Dict[str, Any] = {"metadata": metadata}if self._accepts_kwarg(self._keep_typing, "stop_event", var_kw=False, unknown=True):diff --git a/gateway/response_filters.py b/gateway/response_filters.pyindex c847668e398..f1b8ea04592 100644--- a/gateway/response_filters.py+++ b/gateway/response_filters.py@@ -102,8 +102,15 @@ def is_intentional_silence_agent_result(agent_result: dict | None, response: Anydef display_kind_for_event(event: Any) -> str | None:- """The persisted user-row kind for a gateway turn: only self-injected events are machinery."""- return INTERNAL_NOTIFICATION_DISPLAY_KIND if getattr(event, "internal", False) else None+ """The persisted user-row kind for a gateway turn: only self-injected events are machinery.++ A scheduled heartbeat prompt is self-injected too (``_heartbeat_session_id`` is stamped only+ by the gateway poller, never inferred from inbound text), but it deliberately stays+ non-internal so authorization and the emergency stop still apply to it.+ """+ if getattr(event, "internal", False) or getattr(event, "_heartbeat_session_id", None):+ return INTERNAL_NOTIFICATION_DISPLAY_KIND+ return Nonedef is_machinery_display_kind(display_kind: Any) -> bool:diff --git a/gateway/run.py b/gateway/run.pyindex 42f858b44c3..e3cdcdf6882 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -4085,19 +4085,12 @@ class GatewayRunner(history: Any = Nonedef _thread_metadata_for_source(- self, source, reply_to_message_id: Optional[str] = None, *,- allow_source_message_id_fallback: bool = True,- ) -> Optional[Dict[str, Any]]:+ self, source, reply_to_message_id: Optional[str] = None) -> Optional[Dict[str, Any]]:"""Build the metadata dict platforms need for thread-aware replies."""metadata = self._thread_metadata_for_target(getattr(source, "platform", None), getattr(source, "chat_id", None),getattr(source, "thread_id", None), chat_type=getattr(source, "chat_type", None),- reply_to_message_id=(- reply_to_message_id if reply_to_message_id is not None- else (getattr(source, "message_id", None) if allow_source_message_id_fallback else None)- ),- allow_telegram_dm_topic_reply_fallback=allow_source_message_id_fallback,- )+ reply_to_message_id=reply_to_message_id or getattr(source, "message_id", None))if getattr(source, "platform", None) == Platform.SLACK:# Per-turn egress identity: Slack chat.startStream needs recipient_user_id/team_id; the relay# adapter's _with_scope fallback reads per-chat caches a CONCURRENT turn overwrites.@@ -4132,14 +4125,13 @@ class GatewayRunner(def _thread_metadata_for_target(self, platform: Optional[Platform], chat_id: Optional[str], thread_id: Optional[str], *,chat_type: Optional[str] = None, reply_to_message_id: Optional[str] = None,- adapter: Optional[Any] = None, allow_telegram_dm_topic_reply_fallback: bool = True,- ) -> Optional[Dict[str, Any]]:+ adapter: Optional[Any] = None) -> Optional[Dict[str, Any]]:"""Build thread metadata for synthetic sends that only have routing state."""if thread_id is None:return Nonemetadata: Dict[str, Any] = {"thread_id": thread_id}- if (allow_telegram_dm_topic_reply_fallback and self._is_telegram_dm_topic_target(- platform, chat_id, thread_id, chat_type=chat_type, adapter=adapter)):+ if self._is_telegram_dm_topic_target(+ platform, chat_id, thread_id, chat_type=chat_type, adapter=adapter):metadata["telegram_dm_topic_reply_fallback"] = True# DM topic lanes need direct_messages_topic_id so synthetic sends reach the topic without a reply anchor.tid = str(thread_id)diff --git a/gateway/run_goals.py b/gateway/run_goals.pyindex b87f0064389..14479dd8c8b 100644--- a/gateway/run_goals.py+++ b/gateway/run_goals.py@@ -8,6 +8,7 @@ so ``patch("gateway.run.X")`` keeps intercepting them at call time.from __future__ import annotationsimport asyncio+import dataclassesimport loggingimport timefrom contextlib import nullcontext, suppress@@ -99,7 +100,13 @@ class GatewayGoalsMixin:@staticmethoddef _synthetic_prompt_event(source: Any, text: str, *, internal: bool = False) -> MessageEvent:- """Build the TEXT event used to inject a goal/heartbeat/loop prompt into a session."""+ """Build the TEXT event used to inject a goal/heartbeat/loop prompt into a session.++ The stored source's ``message_id`` is the message that registered the watch; a synthetic+ prompt is not a reply to it, so it is dropped or every progress bubble and final reply+ would quote that stale message (Telegram DM topics route anchorless via the topic id).+ """+ source = dataclasses.replace(source, message_id=None) if getattr(source, "message_id", None) else sourcereturn MessageEvent(text=text, message_type=MessageType.TEXT, source=source, internal=internal)def _register_heartbeat_watch(self, quick_key: str, source: Any, session_id: str) -> None:@@ -153,6 +160,8 @@ class GatewayGoalsMixin:event = self._synthetic_prompt_event(source, prompt)event.metadata["gateway_session_key"] = quick_keyevent._heartbeat_execution_started = False+ # Provenance read by display_kind_for_event / the turn's quiet surfaces; the event stays+ # non-internal so authorization and the emergency stop still apply.event._heartbeat_session_id = session_id# A pinned route skips topic recovery: no await between the idle# check and adapter claim. FIFO alone never wakes an idle session.diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex 47c2bf2656b..cd37b52544b 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -301,11 +301,7 @@ class GatewayTurnMixin:def _event_thread_metadata(self, event, source):"""Thread metadata for a send that replies to ``event`` on ``source``."""- return self._thread_metadata_for_source(- source,- self._reply_anchor_for_event(event),- allow_source_message_id_fallback=not bool(getattr(event, "_heartbeat_session_id", None)),- )+ return self._thread_metadata_for_source(source, self._reply_anchor_for_event(event))@staticmethoddef _pop_post_delivery_callback(adapter, key, generation):@@ -2694,9 +2690,7 @@ class GatewayTurnMixin:headers["X-Hermes-Session-Id"] = session_idbody = {"model": "hermes-agent", "messages": api_messages, "stream": True}- _thread_metadata: Optional[Dict[str, Any]] = self._thread_metadata_for_source(- source, event_message_id, allow_source_message_id_fallback=not scheduled_heartbeat,- )+ _thread_metadata: Optional[Dict[str, Any]] = self._thread_metadata_for_source(source, event_message_id)_stream_consumer = (None if scheduled_heartbeatelse self._proxy_stream_consumer(source, event_message_id, _thread_metadata, _run_still_current)diff --git a/tests/gateway/test_gateway_silence_tokens.py b/tests/gateway/test_gateway_silence_tokens.pyindex 97dcd25ea21..1242d98afa9 100644--- a/tests/gateway/test_gateway_silence_tokens.py+++ b/tests/gateway/test_gateway_silence_tokens.py@@ -144,6 +144,26 @@ async def test_internal_silence_token_suppresses_delivery_but_preserves_transcriassert [msg["role"] for msg in appended if msg.get("role") in {"user", "assistant"}] == ["user", "assistant"]+async def test_scheduled_heartbeat_silence_suppresses_delivery(monkeypatch, tmp_path):+ """A poller-stamped heartbeat turn may end on a bare marker (#113031); the event stays+ non-internal so authorization and the emergency stop still apply to it."""+ runner = _runner(monkeypatch, tmp_path)+ entry = runner.session_store.get_or_create_session.return_value+ entry.suspended = False+ runner.session_store.lookup_by_session_key.return_value = entry+ runner._run_agent = AsyncMock(return_value={+ "final_response": "NO_REPLY",+ "messages": [], "tools": [], "history_offset": 0, "last_prompt_tokens": 0,+ "api_calls": 1, "failed": False,+ })+ event = _event()+ event._heartbeat_session_id = entry.session_id++ assert await runner._handle_message_with_agent(event, _source(), entry.session_key, 1) == ""+ assert not event.internal++@pytest.mark.asyncioasync def test_queued_human_turn_also_gets_the_visible_fallback():runner = gateway_run.GatewayRunner(GatewayConfig())diff --git a/tests/gateway/test_heartbeat_poller.py b/tests/gateway/test_heartbeat_poller.pyindex 70b29142974..2aa981f621a 100644--- a/tests/gateway/test_heartbeat_poller.py+++ b/tests/gateway/test_heartbeat_poller.py@@ -8,6 +8,7 @@ import pytestfrom gateway.config import Platform, PlatformConfigfrom gateway.platforms.base import BasePlatformAdapter, SendResultfrom gateway.platforms.event import MessageEvent+from gateway.response_filters import INTERNAL_NOTIFICATION_DISPLAY_KIND, display_kind_for_eventfrom gateway.run import GatewayRunnerfrom gateway.session import SessionSource, build_session_keyfrom hermes_cli.heartbeat import HeartbeatManager@@ -37,7 +38,7 @@ def poller(monkeypatch):goals._get_session_db()clock = SimpleNamespace(now=1000.0)monkeypatch.setattr(heartbeat, "time", SimpleNamespace(time=lambda: clock.now))- source = SessionSource(platform=Platform.TELEGRAM, chat_id="42", user_id="42", chat_type="dm")+ source = SessionSource(platform=Platform.TELEGRAM, chat_id="42", user_id="42", chat_type="dm", message_id="watch-cmd")key = build_session_key(source)adapter = _HeartbeatAdapter(PlatformConfig(enabled=True, typing_indicator=False), Platform.TELEGRAM)runner = object.__new__(GatewayRunner)@@ -77,6 +78,10 @@ async def test_idle_wake_coalesces_intervals_while_adapter_owns_turn(poller):await runner._heartbeat_poll_once(watch)assert len(received) == 1assert not received[0].internal # authorization and emergency-stop still apply+ # Gateway-stamped provenance: the turn may end silently (#113031) and is not a reply to+ # the message that registered the watch (#112149).+ assert display_kind_for_event(received[0]) == INTERNAL_NOTIFICATION_DISPLAY_KIND+ assert received[0].source.message_id is Noneassert runner._queue_depth(key, adapter=adapter) == 0assert HeartbeatManager("heartbeat-session").state.fire_count == 1finally:diff --git a/tests/gateway/test_telegram_thread_fallback.py b/tests/gateway/test_telegram_thread_fallback.pyindex dac77160a17..cba9f9a86fa 100644--- a/tests/gateway/test_telegram_thread_fallback.py+++ b/tests/gateway/test_telegram_thread_fallback.py@@ -20,7 +20,6 @@ from gateway.config import PlatformConfig, Platformfrom gateway.platforms.base import (SendResult,_reply_anchor_for_event,- _thread_metadata_for_event,_thread_metadata_for_source,)from gateway.platforms.event import MessageEvent, MessageType@@ -298,23 +297,6 @@ def test_base_gateway_metadata_marks_telegram_dm_topics_as_reply_fallback():}-def test_scheduled_heartbeat_metadata_does_not_quote_stored_source_message():- """Heartbeat delivery stays in its DM topic without inheriting a stale reply anchor."""- source = SimpleNamespace(- platform=Platform.TELEGRAM,- chat_type="dm",- thread_id="20189",- message_id="old-user-message",- )- event = MessageEvent(text="scheduled heartbeat", source=source)- event._heartbeat_session_id = "heartbeat-session"-- assert _thread_metadata_for_event(event) == {- "thread_id": "20189",- "direct_messages_topic_id": "20189",- }--@pytest.mark.asyncioasync def test_gateway_runner_busy_ack_replies_to_triggering_message_for_telegram_dm_topic(monkeypatch, tmp_path):"""GatewayRunner's duplicate thread metadata must match the base helper."""@@ -741,3 +723,4 @@ async def test_thread_fallback_only_fires_once():# was cleared per-chunk but the metadata doesn't change between chunks)# The key point: the message was delivered despite the invalid thread+diff --git a/website/docs/user-guide/features/heartbeat.md b/website/docs/user-guide/features/heartbeat.mdindex e38c6ad9a8d..0ab85dd08f9 100644--- a/website/docs/user-guide/features/heartbeat.md+++ b/website/docs/user-guide/features/heartbeat.md@@ -49,6 +49,7 @@ Rule of thumb: if the recurring prompt needs the conversation's context, use `/h- **Gateway recovery.** Startup restores active heartbeats using the current persisted conversation and thread routing, in the owning profile. Each poll retries recovery after temporary storage failures or adapter downtime; paused and cleared heartbeats and suspended conversations do not restart. No new chat message is required.- **Persistence and conversation boundaries.** State lives in `SessionDB.state_meta` keyed by `heartbeat:<session_id>` and follows context-compression session rotations. In the messaging gateway, leaving a conversation through reset, switch, or suspension clears its heartbeat; resuming that archived conversation does not resurrect it. Firing requires the owning process (CLI session or gateway) to be running. An already-admitted gateway tick is checked again after session resolution and before agent execution: it may follow a compression child, but cannot carry its old instruction into a reset or switched conversation.- **Execution accounting.** The gateway reserves a due tick at adapter admission. If that exact attempt ends before entering the agent runner (including cancellation or a routing, authorization, emergency-stop, or preparation rejection), it refunds the tick unless the schedule has since changed. Once the agent runner is entered, the fire remains counted even if execution fails or is interrupted. This count is **not** proof of a successful model response or outbound delivery; abrupt process death can prevent the refund callback.+- **Quiet when there is nothing to say (gateway).** A scheduled heartbeat turn may end with a bare silence marker (`NO_REPLY` / `[SILENT]`): the gateway sends nothing, unlike a human message that returns only a marker (that still gets the visible "try again" notice). While the heartbeat works, no typing indicator, tool-progress, streamed draft or "still working" bubble is posted, and a result it does deliver is routed to the chat/topic without quoting the message that set the heartbeat. Approval prompts and failures stay visible.- **Don't-invent-work guard.** The injected prompt tells the agent to reply briefly and stop when nothing meaningful changed, so an idle heartbeat doesn't generate busywork.## Example