The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telegram): 建立 topic 時不再快取名稱,恢復自動改名 (Refs #136567)
sharpnotebot7cfafba18e20
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex b25b9993335..07c51dbd48b 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -7025,8 +7025,6 @@ class TelegramAdapter(TelegramHeldInboundMixin, TelegramTopicRoutingMixin, BasePif topic_info:chat_topic = topic_info.get("name")topic_skill = topic_info.get("skill")- # The topic name a creation reveals is cached by _handle_forum_topic_created, which is the- # only path Telegram delivers a ``forum_topic_created`` service message through.elif chat_type == "group" and thread_id_str:# Forum topic skill binding via config.extra['group_topics']; accepts both# [{"chat_id": ..., "topics": [...]}] and legacy {"-100...": [{"thread_id": 12}]}.diff --git a/plugins/platforms/telegram/telegram_topic_routing.py b/plugins/platforms/telegram/telegram_topic_routing.pyindex 4e954b892fd..2093aaf2515 100644--- a/plugins/platforms/telegram/telegram_topic_routing.py+++ b/plugins/platforms/telegram/telegram_topic_routing.py@@ -75,8 +75,8 @@ class TelegramTopicRoutingMixin:"""Record an authorized, non-bot private-chat topic creation (#136567).The service ``Message`` supplies ``message_thread_id``; ``ForumTopicCreated`` does not.- Apply the existing intake authorization gate before remembering routing state or caching- a name, so rejected users cannot populate either. Routing signal only: never an agent turn.+ Apply the existing intake authorization gate before remembering routing state, so+ rejected users cannot populate it. Routing signal only: never an agent turn."""message = getattr(update, "effective_message", None)created = getattr(message, "forum_topic_created", None) if message is not None else None@@ -101,10 +101,8 @@ class TelegramTopicRoutingMixin:pending.pop(oldest)pending[(chat_id, self._sender_id_str(message))] = (str(thread_id), message_id, time.monotonic())- topic_name = getattr(created, "name", None)- if topic_name and isinstance(getattr(self, "_dm_topics", None), dict):- # The creation is the one message that reveals the new topic's name.- self._cache_dm_topic_from_message(chat_id, str(thread_id), str(topic_name))+ # Never cache the user-chosen name in _dm_topics: _get_dm_topic_info hits there mark+ # operator-fixed topics, so caching it would silently block session-title auto-rename.logger.debug("[%s] Recorded new Telegram topic %s (chat=%s)", self.name, thread_id, chat_id)def _adopt_created_topic_thread(self, message: Any, chat_type: str, thread_id: Optional[str]) -> Optional[str]:diff --git a/tests/plugins/test_telegram_forum_topic_created_opener.py b/tests/plugins/test_telegram_forum_topic_created_opener.pyindex 28c40a9b52f..480615d6e64 100644--- a/tests/plugins/test_telegram_forum_topic_created_opener.py+++ b/tests/plugins/test_telegram_forum_topic_created_opener.py@@ -423,7 +423,8 @@ async def test_healthy_threaded_opener_consumes_creation_without_changing_threadasync with connected(monkeypatch) as (adapter, app, delivered):await _deliver(app, adapter, topic_created(app.bot))assert set(adapter._pending_created_topics) == {("42", "88")}- assert adapter._dm_topics["42:Prova 3"] == 40798+ # A user-chosen name must not enter the operator-topic cache, or auto-rename treats it as fixed.+ assert "42:Prova 3" not in adapter._dm_topicsawait _deliver(app, adapter, opener(app.bot, thread=explicit_thread, is_topic=True))assert [event.source.thread_id for event in delivered] == [str(explicit_thread)]diff --git a/tests/plugins/test_telegram_topic_creation_auto_rename.py b/tests/plugins/test_telegram_topic_creation_auto_rename.pynew file mode 100644index 00000000000..10a0ce084e7--- /dev/null+++ b/tests/plugins/test_telegram_topic_creation_auto_rename.py@@ -0,0 +1,116 @@+"""User-created Telegram topics stay eligible for session-title renaming (Refs #136567).++Exercise real PTB dispatch and adapter lookup; only Telegram's outbound rename is mocked.+"""++from unittest.mock import AsyncMock++import pytest++pytest.importorskip("telegram")++from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.session import build_session_key+from hermes_state import AsyncSessionDB, SessionDB+from tests.plugins.test_telegram_forum_topic_created_opener import (+ _deliver,+ connected,+ opener,+ topic_created,+)+++def session_db(tmp_path):+ db = SessionDB(db_path=tmp_path / "state.db")+ db.apply_telegram_topic_migration()+ try:+ yield db+ finally:+ db.close()+++def _make_runner(adapter, source, db):+ from gateway.run import GatewayRunner++ session_id = "sess-created-topic"+ db.create_session(session_id, source="telegram", user_id=source.user_id)+ db.bind_telegram_topic(+ chat_id=source.chat_id,+ thread_id=source.thread_id,+ user_id=source.user_id,+ session_key=build_session_key(source),+ session_id=session_id,+ )+ runner = object.__new__(GatewayRunner)+ runner.config = GatewayConfig(+ platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, extra={})}+ )+ runner.adapters = {Platform.TELEGRAM: adapter}+ runner._session_db = AsyncSessionDB(db)+ runner._telegram_topic_mode_enabled = lambda source: True+ return runner, session_id+++async def test_user_created_topic_opener_allows_auto_title_rename(monkeypatch, session_db):+ async with connected(monkeypatch) as (adapter, app, delivered):+ await _deliver(+ app, adapter,+ topic_created(app.bot, name="New Chat"),+ opener(app.bot),+ )+ assert len(delivered) == 1+ source = delivered[0].source+ assert source.thread_id == "40798"++ rename = AsyncMock()+ monkeypatch.setattr(adapter, "rename_dm_topic", rename)+ runner, session_id = _make_runner(adapter, source, session_db)+ assert runner._delivery_adapter_for(source) is adapter+ assert runner._is_telegram_topic_lane(source)++ await runner._rename_telegram_topic_for_session_title(source, session_id, "Auto Title")++ rename.assert_awaited_once_with(+ chat_id="42", thread_id="40798", name="Auto Title",+ )+++async def test_operator_fixed_topic_name_is_not_auto_renamed(monkeypatch, session_db):+ async with connected(monkeypatch) as (adapter, app, delivered):+ # Model the state loaded from extra.dm_topics, without creating a remote topic.+ fixed_topic = {"name": "Fixed", "thread_id": 40798}+ adapter._dm_topics_config = [{"chat_id": 42, "topics": [fixed_topic]}]+ adapter._dm_topics["42:Fixed"] = 40798+ await _deliver(+ app, adapter,+ topic_created(app.bot, name="Fixed"),+ opener(app.bot),+ )+ assert len(delivered) == 1+ source = delivered[0].source+ assert source.thread_id == "40798"+ assert adapter._get_dm_topic_info("42", "40798") == fixed_topic++ rename = AsyncMock()+ monkeypatch.setattr(adapter, "rename_dm_topic", rename)+ runner, session_id = _make_runner(adapter, source, session_db)+ assert runner._delivery_adapter_for(source) is adapter+ assert runner._is_telegram_topic_lane(source)++ await runner._rename_telegram_topic_for_session_title(source, session_id, "Auto Title")++ rename.assert_not_called()+++async def test_user_creation_remains_pending_without_operator_name_cache(monkeypatch):+ async with connected(monkeypatch) as (adapter, app, delivered):+ await _deliver(app, adapter, topic_created(app.bot, name="New Chat"))++ assert delivered == []+ assert set(adapter._pending_created_topics) == {("42", "88")}+ assert adapter._pending_created_topics[("42", "88")][:2] == ("40798", 40799)+ assert "42:New Chat" not in adapter._dm_topics