The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telegram): move dm_topic_auto_transfer to adapter ingress so the reply lands in the new topic
Teknium407303dfdcec
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex cb1f26e90e4..b1ffb8dd522 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -157,8 +157,6 @@ def _mark_notify_metadata(metadata: dict | None) -> dict:def _reply_anchor_for_event(event) -> str | None:"""Return reply_to id for platforms that need reply semantics."""- if (getattr(event, "metadata", None) or {}).get("telegram_dm_topic_auto_transferred"):- return Noneoverride = getattr(event, "reply_anchor_override", None)if override is not None:return override # the turn was redirected onto another message (#115001)diff --git a/gateway/run_adapters.py b/gateway/run_adapters.pyindex 0c44022bd08..e9f9f8e5ae7 100644--- a/gateway/run_adapters.py+++ b/gateway/run_adapters.py@@ -1363,6 +1363,9 @@ class GatewayAdapterLifecycleMixin:if callable(_set_reaction):_set_reaction(self._handle_reaction_event)adapter.set_topic_recovery_fn(self._recover_telegram_topic_thread_id)+ _set_transfer = getattr(adapter, "set_topic_transfer_fn", None)+ if callable(_set_transfer):+ _set_transfer(self._transfer_telegram_root_dm)adapter.set_authorization_check(authorization_check or self._make_adapter_auth_check(adapter.platform))diff --git a/gateway/run_topics.py b/gateway/run_topics.pyindex 07ce06b9bb2..aa5303f7c7b 100644--- a/gateway/run_topics.py+++ b/gateway/run_topics.py@@ -5,7 +5,6 @@from __future__ import annotationsimport asyncio-import dataclassesimport jsonimport loggingimport re@@ -165,17 +164,17 @@ class GatewayTopicThreadsMixin:logger.debug("telegram topic binding refresh failed (%s)", reason, exc_info=True)def _recover_telegram_topic_thread_id(self, source: SessionSource) -> Optional[str]:- """Pin lobby-shaped topic-mode DM replies (missing ``message_thread_id`` or General) to the- user's most-recent bound topic. Never rewrite a non-lobby, unbound thread id: a brand-new DM- topic is also "unknown" until its first message is recorded. None = leave the source alone."""- # The adapter invokes this synchronous hook before the async runner can- # create a topic. Preserve the lobby source until that attempt finishes.+ """Adapter-ingress recovery hook (sync, called off-loop before session keying): lobby recovery,+ except when ``dm_topic_auto_transfer`` is on — then the root-DM source is left alone so+ ``_transfer_telegram_root_dm`` can open a fresh topic (and fall back to this recovery itself)."""if self._telegram_topic_auto_transfer_enabled(source):return None- return self._recover_telegram_topic_thread_id_after_auto_transfer(source)+ return self._recover_telegram_lobby_thread_id(source)- def _recover_telegram_topic_thread_id_after_auto_transfer(self, source: SessionSource) -> Optional[str]:- """Apply lobby recovery after an auto-transfer creation attempt has failed."""+ def _recover_telegram_lobby_thread_id(self, source: SessionSource) -> Optional[str]:+ """Pin lobby-shaped topic-mode DM replies (missing ``message_thread_id`` or General) to the+ user's most-recent bound topic. Never rewrite a non-lobby, unbound thread id: a brand-new DM+ topic is also "unknown" until its first message is recorded. None = leave the source alone."""if (not self._is_telegram_dm(source) or not source.chat_id or not source.user_idor not self._telegram_topic_mode_enabled(source)@@ -200,44 +199,42 @@ class GatewayTopicThreadsMixin:return recovered if recovered and recovered != inbound else Nonereturn None- def _telegram_topic_auto_transfer_enabled(self, source: SessionSource) -> bool:- """Whether a root-DM message should start a freshly created topic lane.-- This is intentionally opt-in: topic mode normally treats the root DM as a- lobby and recovers it to the most recently active topic.- """- if not self._is_telegram_topic_root_lobby(source):- return False+ def _telegram_dm_topic_auto_transfer_configured(self) -> bool:+ """``gateway.platforms.telegram.extra.dm_topic_auto_transfer``; default False. Off keeps the+ v0.22 lobby recovery (#136567). Config only: no state.db read, safe on the event loop."""config = getattr(self, "config", None)platforms = getattr(config, "platforms", None) if config is not None else Noneplatform_cfg = platforms.get(Platform.TELEGRAM) if platforms else None- extra = getattr(platform_cfg, "extra", None) or {}- return is_truthy_value(extra.get("dm_topic_auto_transfer"))+ return is_truthy_value((getattr(platform_cfg, "extra", None) or {}).get("dm_topic_auto_transfer"))++ def _telegram_topic_auto_transfer_enabled(self, source: SessionSource) -> bool:+ """The key is on and ``source`` is a ``/topic``-mode root DM (reads state.db: call off-loop)."""+ return self._telegram_dm_topic_auto_transfer_configured() and self._is_telegram_topic_root_lobby(source)- async def _maybe_auto_transfer_telegram_topic(self, source: SessionSource) -> Optional[SessionSource]:- """Create a topic lane for an opted-in root-DM message, or return ``None``.+ async def _transfer_telegram_root_dm(self, source: SessionSource) -> Optional[tuple[str, bool]]:+ """Adapter-ingress transfer hook for an opted-in root-DM message (#139136).- Failure is deliberately fail-open: callers retain the lobby source and- apply the established last-bound-topic recovery rule.+ ``(thread_id, True)``: a fresh topic was created and the turn runs there. ``(thread_id, False)``:+ creating it failed, so the message falls back to lobby recovery (the last bound topic).+ ``None``: not applicable (key off, not a topic-mode root DM) or nothing to recover to."""- if not self._telegram_topic_auto_transfer_enabled(source) or not source.chat_id:+ if (not source.chat_id or not self._telegram_dm_topic_auto_transfer_configured()+ or not await asyncio.to_thread(self._is_telegram_topic_root_lobby, source)):return Noneadapter = self._delivery_adapter_for(source)create_topic = getattr(adapter, "_create_dm_topic", None) if adapter is not None else None- if not callable(create_topic):- return None- try:- thread_id = await create_topic(int(source.chat_id), t("gateway.topic.default_title"))- except (TypeError, ValueError):- return None- except Exception:- logger.debug("Failed to auto-transfer Telegram root DM into a new topic", exc_info=True)- return None- if not thread_id:- return None- # A root-DM message cannot be the reply anchor inside the newly created- # topic. Delivery uses direct_messages_topic_id for this first reply.- return dataclasses.replace(source, thread_id=str(thread_id), message_id=None)+ thread_id = None+ if callable(create_topic):+ try:+ thread_id = await create_topic(int(source.chat_id), t("gateway.topic.default_title"))+ except Exception:+ logger.debug("Failed to auto-transfer Telegram root DM into a new topic", exc_info=True)+ if thread_id:+ logger.info("telegram topic auto-transfer: chat=%s user=%s root -> new topic %s",+ source.chat_id, source.user_id, thread_id)+ return str(thread_id), True+ recovered = await asyncio.to_thread(self._recover_telegram_lobby_thread_id, source)+ return (recovered, False) if recovered else None# ── Telegram topic mode: /topic activation helpers ──────────────────────────────────────diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.pyindex 75cec2b635a..ee78c1c6bb9 100644--- a/gateway/run_turn_prepare.py+++ b/gateway/run_turn_prepare.py@@ -294,15 +294,9 @@ class GatewayTurnPrepareMixin:# cross-topic Reply doesn't fragment the conversation.event_metadata = getattr(event, "metadata", None) or {}expected_session_key = str(event_metadata.get("gateway_session_key") or "").strip()- transferred = await self._maybe_auto_transfer_telegram_topic(source) if not expected_session_key else None- if transferred is not None:- source = transferred- event.source = source- event_metadata["telegram_dm_topic_auto_transferred"] = True- event.metadata = event_metadata- recovered = (await asyncio.to_thread(- self._recover_telegram_topic_thread_id_after_auto_transfer, source,- )+ # Plain lobby recovery here even with ``dm_topic_auto_transfer`` on: the opt-in topic transfer+ # already ran at adapter ingress (``_auto_transfer_telegram_topic``), before session keying.+ recovered = (await asyncio.to_thread(self._recover_telegram_lobby_thread_id, source)if not expected_session_key else None)if recovered is not None:logger.info(diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 7df8153d75c..e1cec9fbf23 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -182,6 +182,7 @@ from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcomefrom plugins.platforms.telegram.telegram_entities import expand_link_entitiesfrom plugins.platforms.telegram.telegram_held_inbound import TelegramHeldInboundMixinfrom plugins.platforms.telegram.telegram_ids import normalize_telegram_chat_id, parse_send_target, parse_telegram_message_id+from plugins.platforms.telegram.telegram_topic_transfer import TopicTransferFn, apply_root_dm_topic_transferfrom plugins.platforms.telegram.telegram_network import (SEED_FALLBACK_IPS, TelegramFallbackTransport, discover_fallback_ips, parse_fallback_ip_env, tcp_keepalive_socket_options)from utils import env_float, env_int@@ -2879,8 +2880,13 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):async def handle_message(self, event: MessageEvent) -> None:self._accept_update()+ await apply_root_dm_topic_transfer(self, event) # opt-in dm_topic_auto_transfer (#139136)await super().handle_message(event)+ def set_topic_transfer_fn(self, fn: Optional[TopicTransferFn]) -> None:+ """Install the runner's root-DM topic-transfer hook (``dm_topic_auto_transfer``); None clears."""+ self._topic_transfer_fn = fn+def _register_handlers(self, app) -> None:"""Register every PTB handler on ``app`` (initial connect and the transient-init rebuild)."""table = getattr(app, "handlers", None)@@ -7257,8 +7263,9 @@ def _apply_yaml_config(yaml_cfg: dict, telegram_cfg: dict) -> dict | None:extras.setdefault(key, value)_set_env(env, value)- if "disable_topic_auto_rename" in telegram_cfg:- extras.setdefault("disable_topic_auto_rename", telegram_cfg["disable_topic_auto_rename"])+ for _topic_key in ("disable_topic_auto_rename", "dm_topic_auto_transfer"):+ if _topic_key in telegram_cfg:+ extras.setdefault(_topic_key, telegram_cfg[_topic_key])_effective_rm = telegram_cfg.get("require_mention", yaml_cfg.get("require_mention"))if _effective_rm is not None:_set_env("TELEGRAM_REQUIRE_MENTION", str(_effective_rm).lower())diff --git a/plugins/platforms/telegram/telegram_topic_transfer.py b/plugins/platforms/telegram/telegram_topic_transfer.pynew file mode 100644index 00000000000..7d0328ab847--- /dev/null+++ b/plugins/platforms/telegram/telegram_topic_transfer.py@@ -0,0 +1,56 @@+"""Opt-in root-DM -> fresh topic transfer for Telegram ``/topic`` mode (``dm_topic_auto_transfer``).++Off by default: a root-DM message keeps the v0.22 lobby recovery and is answered in the user's+most recently bound topic (#136567). With the key on, the runner's transfer hook creates a new+topic and the message (and its reply) move there before session keying; if creating the topic+fails, the hook answers with the lobby-recovery topic instead (#139136).+"""++from __future__ import annotations++import logging+from typing import Any, Awaitable, Callable, Optional++from gateway.platforms.base import coerce_plaintext_gateway_command+from gateway.platforms.event import MessageEvent+from gateway.session_identity import replace_source++logger = logging.getLogger(__name__)++# ``(thread_id, created)``: ``created`` = a fresh topic; otherwise the lobby-recovery fallback topic.+TopicTransferFn = Callable[[Any], Awaitable[Optional[tuple[str, bool]]]]+++async def apply_root_dm_topic_transfer(adapter: Any, event: MessageEvent) -> None:+ """Rewrite ``event.source`` onto the topic the transfer hook picks; no-op when it declines.++ Runs at adapter ingress, before session keying, so the turn, its session and its reply all use+ the new topic. Commands, internal wakes, routed events and non-DM traffic are never moved.+ """+ transfer: Optional[TopicTransferFn] = getattr(adapter, "_topic_transfer_fn", None)+ source = getattr(event, "source", None)+ if transfer is None or source is None or getattr(source, "chat_type", None) != "dm":+ return+ if getattr(event, "allow_gateway_control", False):+ coerce_plaintext_gateway_command(event) # "restart gateway" is a lobby command too (idempotent)+ if getattr(event, "internal", False) or event.get_command():+ return+ if str((event.metadata or {}).get("gateway_session_key") or "").strip():+ return+ if adapter._is_sender_authorized(source.user_id, source.chat_type, source.chat_id) is False:+ return+ try:+ decided = await transfer(source)+ except Exception:+ logger.debug("telegram topic transfer hook failed", exc_info=True)+ return+ if not decided:+ return+ thread_id, created = decided+ if not created:+ event.source = replace_source(source, thread_id=str(thread_id))+ return+ # The root-DM message lives outside the new topic, so it cannot anchor the reply there: an empty+ # override plus no source.message_id sends the first reply by message_thread_id alone.+ event.source = replace_source(source, thread_id=str(thread_id), message_id=None)+ event.reply_anchor_override = ""diff --git a/tests/gateway/test_telegram_dm_topic_auto_transfer.py b/tests/gateway/test_telegram_dm_topic_auto_transfer.pynew file mode 100644index 00000000000..8d8f265117b--- /dev/null+++ b/tests/gateway/test_telegram_dm_topic_auto_transfer.py@@ -0,0 +1,175 @@+"""Telegram ``/topic`` mode: opt-in root-DM auto transfer (``dm_topic_auto_transfer``, #139136).++Driven through the real ``TelegramAdapter.handle_message`` ingress (topic recovery, session keying,+background processing, final send) into the real ``GatewayRunner._handle_message``; only the Bot API+(``adapter._bot``) and the model call (``runner._run_agent``) are faked.++* default (key unset): a root-DM message keeps the v0.22 lobby recovery — it is answered in the+ user's most recently bound topic (#136567);+* opted in: the message opens a fresh topic via ``createForumTopic`` and the reply lands there;+* opted in but ``createForumTopic`` fails: it falls back to lobby recovery.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++from tests.gateway.conftest import _ensure_telegram_mock++_ensure_telegram_mock()++from gateway.config import Platform, PlatformConfig+from gateway.platforms.event import MessageEvent+from hermes_state import SessionDB+from plugins.platforms.telegram.adapter import TelegramAdapter+from tests.gateway.test_telegram_topic_mode import (+ _make_runner,+ _make_source,+ _seed_two_topic_bindings,+)++NEW_TOPIC_ID = 777+++def _fake_bot(*, create_fails: bool = False) -> MagicMock:+ bot = MagicMock()+ if create_fails:+ bot.create_forum_topic = AsyncMock(side_effect=RuntimeError("Bad Request: chat is not a forum"))+ else:+ bot.create_forum_topic = AsyncMock(return_value=SimpleNamespace(message_thread_id=NEW_TOPIC_ID))+ bot.send_message = AsyncMock(return_value=SimpleNamespace(message_id=9001))+ bot.send_chat_action = AsyncMock(return_value=True)+ return bot+++def _rig(tmp_path, monkeypatch, *, extra: dict, create_fails: bool = False):+ import gateway.run as gateway_run++ db = SessionDB(db_path=tmp_path / "state.db")+ _seed_two_topic_bindings(db) # topic mode on; topic "222" is the most recently bound+ # The stub session store names every topic-lane session "sess-topic"; the binding FK needs its row.+ db.create_session(session_id="sess-topic", source="telegram", user_id="208214988")+ runner = _make_runner(session_db=db)+ runner.config.platforms[Platform.TELEGRAM].extra.update(extra)+ runs: list[dict] = []++ async def fake_run_agent(*args, **kwargs):+ runs.append(kwargs)+ return {"success": True, "final_response": "agent reply", "session_id": kwargs.get("session_id"),+ "messages": []}++ runner._run_agent = AsyncMock(side_effect=fake_run_agent)+ monkeypatch.setattr(gateway_run, "_resolve_runtime_agent_kwargs", lambda: {"api_key": "***"})++ adapter = TelegramAdapter(PlatformConfig(enabled=True, token="***", extra=dict(extra)))+ adapter._bot = _fake_bot(create_fails=create_fails)+ runner.adapters[Platform.TELEGRAM] = adapter+ # The production wiring: every callback GatewayRunner installs on an adapter (topic recovery and,+ # where it exists, the topic-transfer hook), with the message handler pointed at the real runner.+ runner._busy_text_mode = "interrupt"+ runner._wire_adapter_handlers(+ adapter, message_handler=runner._handle_message,+ authorization_check=lambda *_a, **_k: True, platform_event_handler=AsyncMock())+ return runner, adapter, db, runs+++async def _deliver_root_dm(adapter: TelegramAdapter, text: str = "plan the migration") -> MessageEvent:+ """Plain text takes the adapter's real text-batching ingress (``_enqueue_text_event``, whose batch+ key already runs topic recovery) before ``handle_message``; commands dispatch directly."""+ event = MessageEvent(text=text, source=_make_source(thread_id=None), message_id="4242")+ if event.get_command():+ await adapter.handle_message(event)+ else:+ adapter._text_batch_delay_seconds = adapter._text_batch_split_delay_seconds = 0.0+ adapter._enqueue_text_event(event)+ for _ in range(200):+ if not adapter._pending_text_batches and adapter._session_tasks:+ break+ await asyncio.sleep(0.01)+ for _ in range(200):+ tasks = [t for t in adapter._session_tasks.values() if not t.done()]+ if not tasks and adapter._bot.send_message.await_count:+ break+ await asyncio.sleep(0.01)+ await asyncio.gather(*adapter._session_tasks.values(), return_exceptions=True)+ return event+++def _reply_calls(adapter: TelegramAdapter) -> list:+ """The agent's final reply sends (not the one-off "no home channel" onboarding notice)."""+ return [c for c in adapter._bot.send_message.await_args_list if "agent reply" in str(c.kwargs.get("text"))]+++async def test_default_root_dm_keeps_lobby_recovery_to_last_bound_topic(tmp_path, monkeypatch):+ """Key unset: no topic is created; the turn and its reply go to the last bound topic (#136567)."""+ _runner, adapter, db, runs = _rig(tmp_path, monkeypatch, extra={})++ event = await _deliver_root_dm(adapter)++ adapter._bot.create_forum_topic.assert_not_awaited()+ assert event.source.thread_id == "222"+ assert len(runs) == 1+ (reply,) = _reply_calls(adapter)+ assert reply.kwargs.get("message_thread_id") == 222+ db.close()+++async def test_opt_in_root_dm_opens_new_topic_and_reply_lands_there(tmp_path, monkeypatch):+ _runner, adapter, db, runs = _rig(tmp_path, monkeypatch, extra={"dm_topic_auto_transfer": True})++ event = await _deliver_root_dm(adapter)++ adapter._bot.create_forum_topic.assert_awaited_once()+ assert adapter._bot.create_forum_topic.await_args.kwargs["chat_id"] == 208214988+ assert event.source.thread_id == str(NEW_TOPIC_ID)+ assert len(runs) == 1, "the root-DM message must run as a turn, not get the lobby reminder"+ (reply,) = _reply_calls(adapter)+ assert reply.kwargs.get("message_thread_id") == NEW_TOPIC_ID+ # The root-DM message lives outside the new topic: it can't be the reply anchor there.+ assert reply.kwargs.get("reply_to_message_id") is None+ # The new topic is a bound session lane, so the next message inside it continues this session.+ binding = db.get_telegram_topic_binding(chat_id="208214988", thread_id=str(NEW_TOPIC_ID))+ assert binding is not None and binding["user_id"] == "208214988"+ db.close()+++async def test_opt_in_topic_create_failure_falls_back_to_lobby_recovery(tmp_path, monkeypatch):+ _runner, adapter, db, runs = _rig(+ tmp_path, monkeypatch, extra={"dm_topic_auto_transfer": True}, create_fails=True)++ event = await _deliver_root_dm(adapter)++ adapter._bot.create_forum_topic.assert_awaited_once()+ assert event.source.thread_id == "222"+ assert len(runs) == 1+ (reply,) = _reply_calls(adapter)+ assert reply.kwargs.get("message_thread_id") == 222+ db.close()+++async def test_opt_in_root_dm_command_stays_in_the_lobby(tmp_path, monkeypatch):+ """``/topic`` (and every other command) typed in the root DM is a lobby command: no topic."""+ _runner, adapter, db, runs = _rig(tmp_path, monkeypatch, extra={"dm_topic_auto_transfer": True})++ await _deliver_root_dm(adapter, text="/topic help")++ adapter._bot.create_forum_topic.assert_not_awaited()+ assert runs == []+ db.close()+++def test_top_level_telegram_yaml_key_reaches_extra(monkeypatch):+ """``telegram: dm_topic_auto_transfer: true`` (top-level YAML) lands in PlatformConfig.extra,+ like its neighbour ``disable_topic_auto_rename``."""+ from plugins.platforms.telegram.adapter import _apply_yaml_config++ extras = _apply_yaml_config({}, {"dm_topic_auto_transfer": True}) or {}+ assert extras.get("dm_topic_auto_transfer") is Truediff --git a/tests/gateway/test_telegram_topic_mode.py b/tests/gateway/test_telegram_topic_mode.pyindex 4cc9bb92b26..fbd108dfbe8 100644--- a/tests/gateway/test_telegram_topic_mode.py+++ b/tests/gateway/test_telegram_topic_mode.py@@ -172,16 +172,12 @@ def _make_runner(session_db=None):async def test_root_dm_auto_transfer_creates_a_new_topic_when_opted_in(tmp_path):"""Regression for #139136: opt-in root-DM messages start a fresh topic lane."""db = SessionDB(db_path=tmp_path / "state.db")- db.enable_telegram_topic_mode(chat_id="208214988", user_id="208214988")+ _seed_two_topic_bindings(db)runner = _make_runner(session_db=db)runner.config.platforms[Platform.TELEGRAM].extra["dm_topic_auto_transfer"] = Truerunner.adapters[Platform.TELEGRAM]._create_dm_topic.return_value = 777- transferred = await runner._maybe_auto_transfer_telegram_topic(_make_source())-- assert transferred is not None- assert transferred.thread_id == "777"- assert transferred.message_id is None+ assert await runner._transfer_telegram_root_dm(_make_source()) == ("777", True)runner.adapters[Platform.TELEGRAM]._create_dm_topic.assert_awaited_once()db.close()@@ -189,16 +185,29 @@ async def test_root_dm_auto_transfer_creates_a_new_topic_when_opted_in(tmp_path)@pytest.mark.asyncioasync def test_root_dm_auto_transfer_failure_keeps_lobby_recovery(tmp_path):db = SessionDB(db_path=tmp_path / "state.db")- db.enable_telegram_topic_mode(chat_id="208214988", user_id="208214988")+ _seed_two_topic_bindings(db)runner = _make_runner(session_db=db)runner.config.platforms[Platform.TELEGRAM].extra["dm_topic_auto_transfer"] = Truerunner.adapters[Platform.TELEGRAM]._create_dm_topic.return_value = None- assert await runner._maybe_auto_transfer_telegram_topic(_make_source()) is None+ assert await runner._transfer_telegram_root_dm(_make_source()) == ("222", False)runner.adapters[Platform.TELEGRAM]._create_dm_topic.assert_awaited_once()db.close()+async def test_root_dm_auto_transfer_is_off_by_default(tmp_path):+ db = SessionDB(db_path=tmp_path / "state.db")+ _seed_two_topic_bindings(db)+ runner = _make_runner(session_db=db)++ source = _make_source()+ assert await runner._transfer_telegram_root_dm(source) is None+ assert runner._recover_telegram_topic_thread_id(source) == "222"+ runner.adapters[Platform.TELEGRAM]._create_dm_topic.assert_not_awaited()+ db.close()++def test_root_dm_auto_transfer_defers_lobby_recovery_until_creation_attempt(tmp_path):db = SessionDB(db_path=tmp_path / "state.db")_seed_two_topic_bindings(db)@@ -207,7 +216,7 @@ def test_root_dm_auto_transfer_defers_lobby_recovery_until_creation_attempt(tmp_source = _make_source()assert runner._recover_telegram_topic_thread_id(source) is None- assert runner._recover_telegram_topic_thread_id_after_auto_transfer(source) == "222"+ assert runner._recover_telegram_lobby_thread_id(source) == "222"db.close()diff --git a/website/docs/user-guide/messaging/telegram.md b/website/docs/user-guide/messaging/telegram.mdindex b318eaafb0f..59fe43219c6 100644--- a/website/docs/user-guide/messaging/telegram.md+++ b/website/docs/user-guide/messaging/telegram.md@@ -904,6 +904,22 @@ After activation, the **root DM is a lobby**: normal prompts are rejected with gEvery topic gets its own conversation history, model state, tool execution, and session ID. The isolation key is `agent:main:telegram:dm:{chat_id}:{thread_id}` — identical to the config-driven DM topics isolation.+### Messages sent in the root DM++Some Telegram clients deliver a message typed in the root DM (General / **All Messages**) without a `message_thread_id`. By default Hermes treats such a message as a continuation and answers it in your **most recently active topic** (lobby recovery).++To get a fresh session for every root-DM message instead, turn on `dm_topic_auto_transfer`:++```yaml+gateway:+ platforms:+ telegram:+ extra:+ dm_topic_auto_transfer: true # default: false+```++With it on, a plain message in the root DM makes Hermes create a new topic (named "Hermes Chat" until the auto-title renames it), start a new session there, and post the reply inside that topic. Slash commands typed in the root DM stay lobby commands and never create a topic. If creating the topic fails (for example Threaded Mode was switched off in BotFather), Hermes falls back to the default behaviour and answers in your most recently active topic. The key only matters while `/topic` mode is on.+### Auto-renamed topicsWhen Hermes generates a session title for a topic (via the auto-title pipeline, after the first exchange), the Telegram topic itself is renamed to match — e.g. "New Topic" becomes "Database migration plan". The rename is best-effort: failures are logged but don't break the session.@@ -955,6 +971,7 @@ Shows the current topic's binding: session title, session ID, and hints for `/ne- Topics declared in `extra.dm_topics` are **never auto-renamed** — the operator-chosen name is preserved even when multi-session mode is enabled- Set `extra.disable_topic_auto_rename: true` to turn off auto-rename for **all** topics in the chat (ad-hoc topics created via Threaded Mode included)- The General (pinned top) topic in a forum-enabled DM is treated as the root lobby, regardless of whether Telegram delivers its messages with `message_thread_id=1` or with no thread_id+- A root-lobby message is routed to the user's most recently bound topic; with `extra.dm_topic_auto_transfer: true` it instead opens a new topic via `createForumTopic` (falling back to the most recent topic if that call fails)- Root-lobby reminders are rate-limited to one message per 30 seconds per **(profile, chat)** — a user who forgets topic mode is on and types ten prompts in the root won't get ten replies, and two multiplexed profiles sharing a chat id do not suppress each other's reminders- BotFather setup screenshots are rate-limited to one send per 5 minutes per **(profile, chat)** — repeated `/topic` attempts while Threads Settings are still disabled won't re-upload the same image- `/bg <prompt>` started inside a topic delivers its result back to the same topic; background sessions don't trigger auto-rename of the owning topic