The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(discord): recover auto-thread markers from the routing entry in run_topics
kshitijk4poor5843109310e4
diff --git a/gateway/run_topics.py b/gateway/run_topics.pyindex 7ffbc1877dc..32f45138ca3 100644--- a/gateway/run_topics.py+++ b/gateway/run_topics.py@@ -5,6 +5,7 @@from __future__ import annotationsimport asyncio+import jsonimport loggingimport reimport time@@ -18,6 +19,7 @@ from gateway.config import Platformfrom gateway.platforms.base import _prefix_within_utf16_limit, utf16_lenfrom gateway.platforms.event import MessageEventfrom gateway.session import SessionSource+from gateway.session_identity import replace_sourcefrom utils import is_truthy_valueif TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)@@ -278,6 +280,36 @@ class GatewayTopicThreadsMixin:and bool(getattr(source, "auto_thread_initial_name", None)))+ def _recover_discord_auto_thread_source(self, source: SessionSource, session_key: str) -> SessionSource:+ """*source* with the auto-thread markers of the session's opening event, when that event+ created this same native Discord thread.++ Native Discord stamps the markers only on the opening event, so a later title retry on a+ rebuilt agent arrives unmarked. The routing entry's ``origin`` is that opening source and+ survives restarts. ``replace_source`` keeps the live transport owner and message id."""+ if (+ source.platform != Platform.DISCORD or source.chat_type != "thread" or not source.thread_id+ or source.delivered_via_upstream_relay or self._is_discord_auto_thread_lane(source)+ ):+ return source+ entry = self.session_store.lookup_by_session_key(session_key)+ if entry is None:+ return source+ origin = entry.origin+ if origin is not None and source.message_id and origin.message_id == source.message_id:+ # An entry rebuilt from this very event (lost routing index) holds the unmarked live+ # source; the session row keeps the opening origin until this turn's peer refresh.+ origin = None+ session_db = self._sync_session_db()+ with suppress(Exception):+ row = session_db.get_session(entry.session_id) if session_db is not None else None+ origin = SessionSource.from_dict(json.loads(row["origin_json"]))+ if origin is None or origin.thread_id != source.thread_id or not self._is_discord_auto_thread_lane(origin):+ return source+ return replace_source(+ source, auto_thread_created=True, auto_thread_initial_name=origin.auto_thread_initial_name,+ )+def _is_relay_discord_channel_lane(self, source: SessionSource) -> bool:"""Shape-only check: a relay-delivered Discord CHANNEL event whose reply the connector MAYauto-thread (title-turn registration gate). Deliberately does NOT consult the send-resultdiff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 0c75faf004e..a587e2e67a6 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -26,8 +26,6 @@ from gateway.config import Platformfrom gateway.media_repair import repair_explicit_computer_use_media_pathsfrom gateway.platforms.base import BasePlatformAdapterfrom gateway.platforms.base_exec_approval import ea_default_reason_text-from gateway.session import SessionSource-from gateway.session_identity import replace_sourcefrom gateway.turn_context import TurnContextfrom hermes_cli.config import cfg_getfrom utils import is_truthy_value@@ -871,31 +869,8 @@ class TurnRunner:"Gateway auto-title failure suppressed (not user-visible): %s: %s", task, exc,)session_id = getattr(agent, "session_id", None)- source = ctx.sourcerunner = self._runner- # Native Discord only stamps auto-thread markers on the opening parent-channel event. A- # title retry arrives as an ordinary in-thread event; when the agent was rebuilt, there- # is no first-turn callback left to rename it. Recover only those immutable markers from- # this same thread's persisted origin, while keeping the live source's transport owner.- if (- getattr(source, "platform", None) == Platform.DISCORD- and getattr(source, "chat_type", None) == "thread"- and getattr(source, "thread_id", None)- and getattr(source, "delivered_via_upstream_relay", False) is not True- and not runner._is_discord_auto_thread_lane(source)- ):- with suppress(Exception):- row = agent._session_db.get_session(session_id)- origin = SessionSource.from_dict(json.loads((row or {}).get("origin_json") or "{}"))- if (- runner._is_discord_auto_thread_lane(origin)- and str(origin.thread_id) == str(source.thread_id)- ):- source = replace_source(- source,- auto_thread_created=True,- auto_thread_initial_name=origin.auto_thread_initial_name,- )+ source = runner._recover_discord_auto_thread_source(ctx.source, ctx.session_key)# Both lanes spend a rate-limited platform call per title, so they use the model's title# only (TitleCallback); renaming twice burns Discord's 2-per-10-min budget on a throwaway.# Relay Discord predicate is shape-only: whether the connector auto-threaded our reply isdiff --git a/tests/gateway/test_session_title_rename_lane.py b/tests/gateway/test_session_title_rename_lane.pyindex 418d11a8d90..824111576f9 100644--- a/tests/gateway/test_session_title_rename_lane.py+++ b/tests/gateway/test_session_title_rename_lane.py@@ -30,6 +30,7 @@ def _attach(lane):_is_telegram_topic_lane=lambda src: lane == "telegram",_is_discord_auto_thread_lane=lambda src: lane == "discord",_is_relay_discord_channel_lane=lambda src: False,+ _recover_discord_auto_thread_source=lambda src, key: src,_schedule_telegram_topic_title_rename=(lambda src, sid, title: renames.append(title)),@@ -43,7 +44,7 @@ def _attach(lane):)agent = types.SimpleNamespace(session_id="sess-1")holder._attach_session_title_callback(- holder, agent, types.SimpleNamespace(source=source)+ holder, agent, types.SimpleNamespace(source=source, session_key="key-1"))return agent._on_session_title, renames@@ -59,199 +60,75 @@ def test_the_rename_waits_for_the_model_title(lane):assert renames == ["Fix flaky auth test"]-def _recovery_runner(scheduled):- """Fake runner binding the REAL lane predicate, like NativeRenameRunner below."""-- class RecoveryRunner:- _is_telegram_topic_lane = lambda self, source: False # noqa: E731- _is_relay_discord_channel_lane = lambda self, source: False # noqa: E731- _is_discord_auto_thread_lane = GatewayRunner._is_discord_auto_thread_lane-- def _schedule_discord_semantic_thread_rename(self, source, session_id, title):- scheduled.append((source, session_id, title))-- return RecoveryRunner()---def _recover_agent(session_db, origin):- return types.SimpleNamespace(- session_id="sess-1",- _session_db=session_db- or types.SimpleNamespace(- get_session=lambda session_id: {- "origin_json": json.dumps(origin.to_dict()) if origin else "{}",- }- ),- )---def test_discord_title_retry_recovers_auto_thread_origin():- """A fresh agent on a later thread turn still wires the semantic rename."""- scheduled = []- current = SessionSource(- platform=Platform.DISCORD,- chat_id="thread-1",- chat_type="thread",- thread_id="thread-1",- message_id="follow-up",- )- origin = SessionSource(- platform=Platform.DISCORD,- chat_id="thread-1",- chat_type="thread",- thread_id="thread-1",- message_id="opening-message",- auto_thread_created=True,- auto_thread_initial_name="Opening words",+def _thread_source(thread_id="thread-1", **fields):+ return SessionSource(+ platform=Platform.DISCORD, chat_id=thread_id, chat_type="thread", thread_id=thread_id, **fields,)- runner = _recovery_runner(scheduled)- holder = types.SimpleNamespace(- _runner=runner,- _attach_session_title_callback=TurnRunner._attach_session_title_callback,- )- agent = _recover_agent(None, origin)- holder._attach_session_title_callback(- holder, agent, types.SimpleNamespace(source=current)- )- agent._on_session_title("Recovered semantic title", "llm")- assert len(scheduled) == 1- recovered, session_id, title = scheduled[0]- assert recovered.message_id == "follow-up"- assert recovered.auto_thread_created is True- assert recovered.auto_thread_initial_name == "Opening words"- assert session_id == "sess-1"- assert title == "Recovered semantic title"--- "origin_source",- [- pytest.param(None, id="no-origin-markers"),- pytest.param(- SessionSource(- platform=Platform.DISCORD,- chat_id="thread-1",- chat_type="thread",- thread_id="thread-2",- message_id="opening-message",- auto_thread_created=True,- auto_thread_initial_name="Other thread",- ),- id="other-thread-id",- ),- pytest.param(- SessionSource(- platform=Platform.DISCORD,- chat_id="thread-1",- chat_type="thread",- thread_id="thread-1",- message_id="opening-message",- ),- id="user-created-thread",- ),- ],+_OPENING = _thread_source(+ message_id="opening-message", auto_thread_created=True, auto_thread_initial_name="Opening words",)-def test_discord_title_retry_recovery_no_ops_for_untrusted_origins(origin_source):- """Wrong thread, manual thread, or blank origin: the callback is never wired."""- scheduled = []- current = SessionSource(- platform=Platform.DISCORD,- chat_id="thread-1",- chat_type="thread",- thread_id="thread-1",- message_id="follow-up",- )- runner = _recovery_runner(scheduled)- holder = types.SimpleNamespace(- _runner=runner,- _attach_session_title_callback=TurnRunner._attach_session_title_callback,- )- agent = _recover_agent(None, origin_source)-- holder._attach_session_title_callback(- holder, agent, types.SimpleNamespace(source=current)- )-- assert not hasattr(agent, "_on_session_title")- assert scheduled == []-def test_discord_title_retry_recovery_survives_db_failure():- """A broken session DB degrades to main's behaviour, not a wiring crash."""- scheduled = []- current = SessionSource(- platform=Platform.DISCORD,- chat_id="thread-1",- chat_type="thread",- thread_id="thread-1",- message_id="follow-up",+def _attach_in_thread(current, entry_origin, row_origin=None):+ """Attach the title callback for an unmarked in-thread follow-up *current* whose routing entry+ holds *entry_origin* (and whose session row holds *row_origin*), through the REAL lane+ predicate and recovery. Returns (agent, scheduled renames)."""+ scheduled: list = []+ entry = types.SimpleNamespace(session_id="sess-1", origin=entry_origin)+ row = {"origin_json": json.dumps(row_origin.to_dict())} if row_origin else None+ runner = types.SimpleNamespace(+ session_store=types.SimpleNamespace(lookup_by_session_key={"key-1": entry}.get),+ _session_db=types.SimpleNamespace(get_session={"sess-1": row}.get),+ _is_telegram_topic_lane=lambda src: False,+ _is_relay_discord_channel_lane=lambda src: False,+ _schedule_discord_semantic_thread_rename=lambda src, sid, title: scheduled.append((src, sid, title)),)-- class BrokenDB:- calls = 0-- def get_session(self, session_id):- self.calls += 1- raise RuntimeError("state.db unavailable")-- db = BrokenDB()- runner = _recovery_runner(scheduled)+ for name in ("_sync_session_db", "_is_discord_auto_thread_lane", "_recover_discord_auto_thread_source"):+ setattr(runner, name, types.MethodType(getattr(GatewayRunner, name), runner))holder = types.SimpleNamespace(_runner=runner,_attach_session_title_callback=TurnRunner._attach_session_title_callback,)- agent = _recover_agent(db, None)-+ agent = types.SimpleNamespace(session_id="sess-1")holder._attach_session_title_callback(- holder, agent, types.SimpleNamespace(source=current)+ holder, agent, types.SimpleNamespace(source=current, session_key="key-1"))+ return agent, scheduled- # The recovery DID reach the DB and its failure stayed inside the attach:- # no callback and no scheduling, exactly like main.- assert db.calls == 1- assert not hasattr(agent, "_on_session_title")- assert scheduled == []--def test_discord_title_retry_recovery_preserves_transport_adapter_ref():- """The recovered source keeps the live event's transport owner (multiplex)."""- scheduled = [][email protected]("rebuilt_entry", [False, True], ids=["routing-entry", "rebuilt-entry-falls-back-to-row"])+def test_discord_title_retry_recovers_auto_thread_origin(rebuilt_entry):+ """A fresh agent on a later in-thread turn still wires the semantic rename (#127667), keeping+ the live event's message id and transport owner."""adapter = type("Adapter", (), {})()- current = SessionSource(- platform=Platform.DISCORD,- chat_id="thread-1",- chat_type="thread",- thread_id="thread-1",- message_id="follow-up",- profile="runtime-profile",- )+ current = _thread_source(message_id="follow-up", profile="runtime-profile")current._transport_adapter_ref = weakref.ref(adapter)- origin = SessionSource(- platform=Platform.DISCORD,- chat_id="thread-1",- chat_type="thread",- thread_id="thread-1",- message_id="opening-message",- auto_thread_created=True,- auto_thread_initial_name="Opening words",- )- runner = _recovery_runner(scheduled)- holder = types.SimpleNamespace(- _runner=runner,- _attach_session_title_callback=TurnRunner._attach_session_title_callback,- )- agent = _recover_agent(None, origin)-- holder._attach_session_title_callback(- holder, agent, types.SimpleNamespace(source=current)- )+ if rebuilt_entry: # routing index lost: the entry was rebuilt from this very event+ agent, scheduled = _attach_in_thread(current, entry_origin=current, row_origin=_OPENING)+ else:+ agent, scheduled = _attach_in_thread(current, entry_origin=_OPENING)agent._on_session_title("Recovered semantic title", "llm")- recovered = scheduled[0][0]+ [(recovered, session_id, title)] = scheduledassert recovered.message_id == "follow-up"assert recovered._transport_adapter_ref() is adapter+ assert (recovered.auto_thread_created, recovered.auto_thread_initial_name) == (True, "Opening words")+ assert (session_id, title) == ("sess-1", "Recovered semantic title")++[email protected]("origin", [+ pytest.param(+ _thread_source("thread-2", auto_thread_created=True, auto_thread_initial_name="Other"),+ id="other-thread",+ ),+ pytest.param(_thread_source(message_id="opening-message"), id="user-created-thread"),+])+def test_discord_title_retry_never_borrows_markers_from_another_origin(origin):+ agent, scheduled = _attach_in_thread(_thread_source(message_id="follow-up"), entry_origin=origin)+ assert not hasattr(agent, "_on_session_title")+ assert scheduled == []@pytest.mark.anyio