Skip to content

The agent that grows with you

feat(telegram): drop_pending_on_cold_boot knob to preserve offline queue

justcarlosma4a0447b04e8
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index d8d1999b628..20723befead 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -539,6 +539,11 @@ class TelegramAdapter(BasePlatformAdapter):
self._status_indicator_enabled: bool = bool(extra.get("status_indicator", False))
self._status_online_text: str = str(extra.get("status_online", "Online"))
self._status_offline_text: str = str(extra.get("status_offline", "Offline"))
+ # Cold-boot queue: drop server-side pending updates on first boot (default True,
+ # preserves historical behaviour). Set extra.drop_pending_on_cold_boot: false to
+ # receive messages sent while the gateway was offline (e.g. nightly-off hosts).
+ # Watcher reconnects always preserve the queue regardless of this setting.
+ self._drop_pending_on_cold_boot: bool = self._coerce_bool_extra("drop_pending_on_cold_boot", True)
self._dm_topics_config: List[Dict[str, Any]] = extra.get("dm_topics", [])
# chat_ids with DM topics configured (O(1) root-DM ignore check)
self._dm_topic_chat_ids: Set[str] = {str(e["chat_id"]) for e in self._dm_topics_config if "chat_id" in e}
@@ -2974,7 +2979,7 @@ class TelegramAdapter(BasePlatformAdapter):
await self._app.updater.start_webhook(
listen=webhook_host, port=webhook_port, url_path=webhook_path, webhook_url=webhook_url,
secret_token=webhook_secret, allowed_updates=Update.ALL_TYPES,
- drop_pending_updates=not is_reconnect, # push-based ⇒ practically a no-op; mirrors polling
+ drop_pending_updates=self._drop_pending_on_cold_boot if not is_reconnect else False,
)
self._webhook_mode = True
self._polling_progress_accepting = False
@@ -3005,9 +3010,11 @@ class TelegramAdapter(BasePlatformAdapter):
logger.error("[%s] Telegram polling error: %s", self.name, _redact_telegram_error_text(error), exc_info=True)
self._polling_error_callback_ref = _polling_error_callback # reused by _handle_polling_conflict
+ # Cold first boot drops the Bot API queue unless extra.drop_pending_on_cold_boot
+ # is false (nightly-off hosts want the backlog); a watcher reconnect preserves it.
+ drop_pending = self._drop_pending_on_cold_boot if not is_reconnect else False
polling_started = await self._start_polling_resilient(
- # Cold first boot drops the stale Bot API queue; a watcher reconnect preserves it.
- drop_pending_updates=not is_reconnect, error_callback=_polling_error_callback, require_progress=not is_reconnect)
+ drop_pending_updates=drop_pending, error_callback=_polling_error_callback, require_progress=not is_reconnect)
if not polling_started:
logger.warning(
"[%s] Connected in degraded Telegram mode: gateway is alive, polling will be retried in the background", self.name)
@@ -3015,9 +3022,11 @@ class TelegramAdapter(BasePlatformAdapter):
async def connect(self, *, is_reconnect: bool = False) -> bool:
"""Connect via long polling, or a webhook server if ``TELEGRAM_WEBHOOK_URL`` is set.
- ``is_reconnect``: False = cold boot (drop the stale Bot API queue); True = watcher reconnect (preserve queued
- updates, else every message sent during the outage is lost). Webhook env: TELEGRAM_WEBHOOK_URL,
- TELEGRAM_WEBHOOK_PORT (8443), TELEGRAM_WEBHOOK_HOST, TELEGRAM_WEBHOOK_SECRET."""
+ ``is_reconnect``: False = cold boot (drop the Bot API queue unless
+ ``extra.drop_pending_on_cold_boot`` is false); True = watcher reconnect (preserve
+ queued updates, else every message sent during the outage is lost). Webhook env:
+ TELEGRAM_WEBHOOK_URL, TELEGRAM_WEBHOOK_PORT (8443), TELEGRAM_WEBHOOK_HOST,
+ TELEGRAM_WEBHOOK_SECRET."""
# Explicit connect() is the only operation allowed to reopen polling after a completed teardown.
self._polling_teardown_started = False
self._webhook_mode = False # re-evaluated on every explicit connection
diff --git a/tests/gateway/test_telegram_cold_boot_queue.py b/tests/gateway/test_telegram_cold_boot_queue.py
new file mode 100644
index 00000000000..0b77c1d55e7
--- /dev/null
+++ b/tests/gateway/test_telegram_cold_boot_queue.py
@@ -0,0 +1,58 @@
+"""Cold-boot pending-queue knob for the Telegram adapter.
+
+Contract: a cold boot drops Telegram's server-side pending updates unless
+``extra.drop_pending_on_cold_boot`` is false; a watcher reconnect always
+preserves them. Conflict recovery is a separate path and is not covered here.
+"""
+
+from unittest.mock import AsyncMock
+
+import pytest
+
+from gateway.config import PlatformConfig
+from plugins.platforms.telegram.adapter import TelegramAdapter
+
+
+def _make_adapter(extra=None) -> TelegramAdapter:
+ return TelegramAdapter(PlatformConfig(enabled=True, token="test-token", extra=extra or {}))
+
+
+async def _capture_drop_pending(adapter: TelegramAdapter, *, is_reconnect: bool):
+ """Run _start_polling_mode with staging mocked; return the forwarded flag."""
+ captured = {}
+ adapter._delete_webhook_best_effort = AsyncMock()
+
+ async def _fake_resilient(*, drop_pending_updates, error_callback, require_progress=False):
+ captured["drop_pending_updates"] = drop_pending_updates
+ captured["require_progress"] = require_progress
+ return True
+
+ adapter._start_polling_resilient = _fake_resilient
+ await adapter._start_polling_mode(is_reconnect=is_reconnect)
+ return captured
+
+
+async def test_cold_boot_drops_queue_by_default():
+ """Default config: cold boot drops, reconnect preserves."""
+ adapter = _make_adapter()
+ assert adapter._drop_pending_on_cold_boot is True
+
+ cold = await _capture_drop_pending(adapter, is_reconnect=False)
+ assert cold["drop_pending_updates"] is True
+
+ warm = await _capture_drop_pending(adapter, is_reconnect=True)
+ assert warm["drop_pending_updates"] is False
+
+
+async def test_cold_boot_preserves_queue_when_opted_out():
+ """extra.drop_pending_on_cold_boot=false: cold boot preserves the backlog."""
+ adapter = _make_adapter(extra={"drop_pending_on_cold_boot": False})
+ assert adapter._drop_pending_on_cold_boot is False
+
+ cold = await _capture_drop_pending(adapter, is_reconnect=False)
+ assert cold["drop_pending_updates"] is False
+
+ warm = await _capture_drop_pending(adapter, is_reconnect=True)
+ assert warm["drop_pending_updates"] is False
diff --git a/website/docs/user-guide/messaging/telegram.md b/website/docs/user-guide/messaging/telegram.md
index 68a6e35f8c2..d6b838a1795 100644
--- a/website/docs/user-guide/messaging/telegram.md
+++ b/website/docs/user-guide/messaging/telegram.md
@@ -83,6 +83,37 @@ Notes:
profile-text indicator.
- Off by default, since it mutates the bot's global profile.
+### Cold-boot pending queue (Optional)
+
+By default the adapter drops server-side pending updates on a cold boot
+(`drop_pending_updates=True` on the first `start_polling`). That fits
+always-on servers: a restart means "clean up," and the queue is treated as
+stale. It does not fit hosts that turn off (a desktop shut down overnight):
+messages sent while the gateway is offline sit in Telegram's Bot API queue,
+and the next boot discards them before Hermes ever sees them — silently, no
+log, no retry.
+
+Set `drop_pending_on_cold_boot: false` to receive that backlog in order on
+startup instead:
+
+```yaml
+platforms:
+ telegram:
+ extra:
+ drop_pending_on_cold_boot: false
+```
+
+Notes:
+
+- Default is `true`: existing behavior is unchanged unless you opt in.
+- Watcher reconnects (brief network outages with the process still alive)
+ always preserve the queue regardless of this setting.
+- Conflict recovery still drops pending updates to terminate the competing
+ `getUpdates` session — that path is unrelated to this knob.
+- After a crash, a preserved queue can redeliver an update the crashed
+ instance partially processed. Telegram's offset usually prevents this,
+ but time-sensitive commands sent during a long outage will run on boot.
+
### Command menu priority and cap (Optional)
Hermes registers its command menu automatically when the Telegram gateway starts. The menu is built from the central slash-command registry plus eligible plugin/skill commands, then capped so Telegram accepts the payload reliably. The default cap is 60 commands — enough to keep all built-in commands plus common skill commands visible.