Skip to content

The agent that grows with you

feat(gateway): add opt-in Telegram DM topic transfer

KoNit-K3cdd75ba5806
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index b1ffb8dd522..cb1f26e90e4 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -157,6 +157,8 @@ 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 None
override = 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_topics.py b/gateway/run_topics.py
index 849ae07ac6a..07ce06b9bb2 100644
--- a/gateway/run_topics.py
+++ b/gateway/run_topics.py
@@ -5,6 +5,7 @@
from __future__ import annotations
import asyncio
+import dataclasses
import json
import logging
import re
@@ -167,6 +168,14 @@ class GatewayTopicThreadsMixin:
"""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.
+ if self._telegram_topic_auto_transfer_enabled(source):
+ return None
+ return self._recover_telegram_topic_thread_id_after_auto_transfer(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."""
if (
not self._is_telegram_dm(source) or not source.chat_id or not source.user_id
or not self._telegram_topic_mode_enabled(source)
@@ -191,6 +200,45 @@ class GatewayTopicThreadsMixin:
return recovered if recovered and recovered != inbound else None
return 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
+ config = getattr(self, "config", None)
+ platforms = getattr(config, "platforms", None) if config is not None else None
+ platform_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"))
+
+ 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``.
+
+ Failure is deliberately fail-open: callers retain the lobby source and
+ apply the established last-bound-topic recovery rule.
+ """
+ if not self._telegram_topic_auto_transfer_enabled(source) or not source.chat_id:
+ return None
+ adapter = 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)
+
# ── Telegram topic mode: /topic activation helpers ──────────────────────────────────────
async def _get_telegram_topic_capabilities(self, source: SessionSource) -> dict:
diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.py
index ca837064c39..75cec2b635a 100644
--- a/gateway/run_turn_prepare.py
+++ b/gateway/run_turn_prepare.py
@@ -294,7 +294,15 @@ 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()
- recovered = (await asyncio.to_thread(self._recover_telegram_topic_thread_id, source)
+ 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,
+ )
if not expected_session_key else None)
if recovered is not None:
logger.info(
diff --git a/tests/gateway/test_telegram_topic_mode.py b/tests/gateway/test_telegram_topic_mode.py
index 47882da632b..4cc9bb92b26 100644
--- a/tests/gateway/test_telegram_topic_mode.py
+++ b/tests/gateway/test_telegram_topic_mode.py
@@ -168,6 +168,49 @@ def _make_runner(session_db=None):
return runner
+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")
+ runner = _make_runner(session_db=db)
+ runner.config.platforms[Platform.TELEGRAM].extra["dm_topic_auto_transfer"] = True
+ runner.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
+ runner.adapters[Platform.TELEGRAM]._create_dm_topic.assert_awaited_once()
+ db.close()
+
+
+async 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")
+ runner = _make_runner(session_db=db)
+ runner.config.platforms[Platform.TELEGRAM].extra["dm_topic_auto_transfer"] = True
+ runner.adapters[Platform.TELEGRAM]._create_dm_topic.return_value = None
+
+ assert await runner._maybe_auto_transfer_telegram_topic(_make_source()) is None
+ runner.adapters[Platform.TELEGRAM]._create_dm_topic.assert_awaited_once()
+ 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)
+ runner = _make_runner(session_db=db)
+ runner.config.platforms[Platform.TELEGRAM].extra["dm_topic_auto_transfer"] = True
+
+ 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"
+ db.close()
+
+
@pytest.mark.asyncio
async def test_topic_restore_quote_never_exposes_compaction_scaffolding(tmp_path):
db = SessionDB(db_path=tmp_path / "state.db")