The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): rename a Discord thread once, after the reply lands
Brooklyn Nicholson34577fcb036f
diff --git a/acp_adapter/server.py b/acp_adapter/server.pyindex 7fc0a7403e4..d558d289dbd 100644--- a/acp_adapter/server.py+++ b/acp_adapter/server.py@@ -1907,7 +1907,7 @@ class HermesACPAgent(acp.Agent):# Auto-titling fires inside the turn prologue now; give the agent# this session's notifier so a new title reaches the client as a# session-info update instead of waiting for the next one.- def _notify_title_update(_title: str) -> None:+ def _notify_title_update(_title: str, _source: str) -> None:if conn:loop.call_soon_threadsafe(asyncio.create_task,diff --git a/agent/title_generator.py b/agent/title_generator.pyindex 74ecfdb701e..ca664022efc 100644--- a/agent/title_generator.py+++ b/agent/title_generator.py@@ -32,7 +32,18 @@ logger = logging.getLogger(__name__)# so silent-drops (e.g. OpenRouter 402 exhausting the fallback chain)# become visible instead of piling up as NULL session titles.FailureCallback = Callable[[str, BaseException], None]-TitleCallback = Callable[[str], None]++# Callback signature: (title, source) -> None, where source is the provenance+# the title was persisted under (``derived`` for the instant slice of the user's+# own words, ``llm`` for the model's upgrade of it).+#+# Titling is two-stage, and the stage matters to the consumer. A local surface+# wants both, so the sidebar renames instantly and sharpens a second later. A+# consumer that spends a rate-limited remote call per title — renaming a Discord+# thread, a Telegram topic — wants ``llm`` only: acting on both burns two calls+# to end up at the same name, and on Discord (2 renames per 10 minutes per+# channel) the throwaway one can be what survives.+TitleCallback = Callable[[str, str], None]# Validation callback: () -> bool. Called right before the LLM request in# generate_title(). Return False to skip — e.g. the user switched models@@ -392,7 +403,7 @@ def generate_title(return None-def _persist_session_title(session_db, session_id, title, *, source):+def _persist_session_title(session_db, session_id, title, *, source, dedupe=True):"""Persist a title at *source* authority, recovering from name collisions.The write goes through ``set_auto_title`` (precedence check + write in one@@ -401,6 +412,14 @@ def _persist_session_title(session_db, session_id, title, *, source):session (the unique-title index); rather than leave the session untitled(#50537), append a ``#N`` suffix via ``get_next_title_in_lineage``.+ ``dedupe=False`` re-raises that collision instead. The derived title is the+ one write on the turn's critical path, and it is also the one that collides+ constantly — it is a slice of the user's own words, and people open sessions+ with "hi" and "help me debug this". Scanning the lineage for the next free+ "hi #N" is a widening scan, run inline, for a name the model replaces a+ second later. The background stage picks the collision back up, so nothing+ is lost by declining it here.+Returns the title actually persisted, or None when a higher-authoritytitle already held the row (nothing was written)."""@@ -429,7 +448,7 @@ def _persist_session_title(session_db, session_id, title, *, source):return _set(title)except ValueError:next_title_fn = getattr(session_db, "get_next_title_in_lineage", None)- if next_title_fn is None:+ if not dedupe or next_title_fn is None:raisededuped = next_title_fn(title)if not deduped or deduped == title:@@ -458,11 +477,11 @@ def apply_instant_title(if not title:return Nonepersisted = _persist_session_title(- session_db, session_id, title, source="derived"+ session_db, session_id, title, source="derived", dedupe=False)if persisted and title_callback is not None:try:- title_callback(persisted)+ title_callback(persisted, "derived")except Exception:logger.debug("Instant-title callback failed", exc_info=True)return persisted@@ -573,25 +592,55 @@ def _auto_title_session(main_runtime=main_runtime,runtime_validator=runtime_validator,)+ source = "llm"if not title:- return+ # No model title, so the derived one has to hold — and it may never have+ # been written, since the inline attempt declines a name collision+ # rather than scan the lineage on the turn's critical path. Off that+ # path the scan is affordable, so spend it here and leave the session+ # named rather than nameless.+ title = derive_title(user_message)+ source = "derived"+ if not title:+ returntry:- persisted = _persist_session_title(- session_db, session_id, title, source="llm"- )+ persisted = _persist_session_title(session_db, session_id, title, source=source)if persisted is None:returnlogger.debug("Auto-generated session title: %s", persisted)if title_callback is not None:try:- title_callback(persisted)+ title_callback(persisted, source)except Exception:logger.debug("Auto-title callback failed", exc_info=True)except Exception as e:logger.debug("Failed to set auto-generated title: %s", e)+def _session_is_untitled(session_db, session_id: str) -> bool:+ """Whether the session still carries no title of any provenance.++ Titling normally reads the opening message and nothing else, but an opener+ isn't always titleable: an image with no caption, a compaction handoff, a+ bare slash command. Those sessions stayed nameless for life — the same guard+ that stops us re-titling on every turn also stopped us ever trying again.+ This reopens the question on later turns, and only while the answer is still+ missing, so a named session asks nothing and pays nothing.++ Answers False when it can't tell: an unreadable title is not a reason to+ start spending a model call per turn.+ """+ getter = getattr(session_db, "get_session_title", None)+ if not callable(getter):+ return False+ try:+ return not str(getter(session_id) or "").strip()+ except Exception:+ logger.debug("Untitled check failed for %s", session_id, exc_info=True)+ return False++def maybe_auto_title(session_db,session_id: str,@@ -624,7 +673,7 @@ def maybe_auto_title(for m in (conversation_history or [])if isinstance(m, dict) and m.get("role") == "user")- if user_msg_count > 1:+ if user_msg_count > 1 and not _session_is_untitled(session_db, session_id):returnif not is_titleable_user_message(user_message):diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.pyindex 73f7cf29410..9e071864294 100644--- a/gateway/relay/adapter.py+++ b/gateway/relay/adapter.py@@ -85,6 +85,10 @@ class RelayAdapter(BasePlatformAdapter):# feedback off SendResult — see send()). Consumed by the gateway's# semantic thread-rename lane; bounded like the sibling caches.self._auto_thread_by_chat: Dict[str, Tuple[str, str]] = {}+ # chat_id -> event fired when the entry above lands, so a consumer that+ # arrives before the send can wait for it instead of polling. See+ # wait_for_auto_thread_info.+ self._auto_thread_waiters: Dict[str, asyncio.Event] = {}# chat_id -> chat_type (e.g. "dm", "channel", "group") learned from the# inbound event. Used to reproduce native Slack's synthetic-DM-thread# suppression on the relay lane: a DM streaming reply carries@@ -993,6 +997,13 @@ class RelayAdapter(BasePlatformAdapter):)except Exception: # noqa: BLE001 - feedback capture must never break sendpass+ # Wake the rename lane on EVERY send into this chat, not only the ones+ # that auto-threaded. It is waiting to learn where this turn's reply+ # landed, and "nowhere new" is an answer — one it should get now rather+ # than by outlasting a timeout.+ waiter = self._auto_thread_waiters.get(str(chat_id))+ if waiter is not None:+ waiter.set()return SendResult(success=bool(result.get("success")),message_id=result.get("message_id"),@@ -1007,6 +1018,42 @@ class RelayAdapter(BasePlatformAdapter):gateway's semantic thread-rename lane (auto session title)."""return self._auto_thread_by_chat.get(str(chat_id))+ async def wait_for_auto_thread_info(+ self, chat_id: str, timeout: float+ ) -> Optional[Tuple[str, str]]:+ """``auto_thread_info_for_chat``, but willing to wait for the send.++ The rename lane asks where the reply landed as soon as the session is+ titled, and the session is titled from the user's opening message —+ before the model has answered, let alone before we've sent anything. So+ the question arrives a whole turn early, and a turn is a one-liner or+ twenty minutes of tool calls.++ Waits for the next send into this chat and then answers, so a reply the+ connector didn't auto-thread reports its miss as soon as it's sent+ instead of holding until *timeout* — which is only a backstop for a turn+ that never sends at all.+ """+ info = self.auto_thread_info_for_chat(chat_id)+ if info is not None:+ return info+ key = str(chat_id)+ waiter = self._auto_thread_waiters.get(key)+ if waiter is None:+ waiter = asyncio.Event()+ self._auto_thread_waiters[key] = waiter+ try:+ await asyncio.wait_for(waiter.wait(), timeout)+ except asyncio.TimeoutError:+ return None+ finally:+ # Only the waiter we may have installed, and only if no later call+ # replaced it; a fired event must not be left behind to make the+ # next turn's wait return instantly on stale feedback.+ if self._auto_thread_waiters.get(key) is waiter:+ self._auto_thread_waiters.pop(key, None)+ return self.auto_thread_info_for_chat(chat_id)+def _resolve_reply_to_for_send(self,chat_id: str,diff --git a/gateway/run.py b/gateway/run.pyindex c3aae82cf53..52df713f7f4 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -1016,6 +1016,17 @@ def _startup_restore_drain_timeout_secs() -> float:return float(_STARTUP_RESTORE_DRAIN_TIMEOUT_SECS_DEFAULT)+def _as_thread_info(info: Any) -> Optional[Tuple[str, str]]:+ """*info* as a (thread_id, initial_name) pair, or None if it isn't one.++ The pair comes back across the relay connector boundary, so its shape is+ the connector's word rather than ours.+ """+ if isinstance(info, tuple) and len(info) == 2 and all(isinstance(x, str) for x in info):+ return cast(Tuple[str, str], info)+ return None++def _float_env(name: str, default: float) -> float:"""Read an env var as float, falling back to ``default`` on typos/empty.@@ -4460,9 +4471,15 @@ class TurnRunner:session_id = getattr(agent, "session_id", None)source = ctx.source+ # Both lanes below spend a rate-limited platform call per title, so+ # they take the model's title and skip the derived one — see+ # TitleCallback. Renaming twice lands on the same name at twice the+ # cost, and Discord's 2-per-10-minutes channel budget can spend+ # itself on the throwaway and drop the one worth showing.if self._runner._is_telegram_topic_lane(source):- agent._on_session_title = lambda title: (- self._runner._schedule_telegram_topic_title_rename(+ agent._on_session_title = lambda title, title_source: (+ title_source == "llm"+ and self._runner._schedule_telegram_topic_title_rename(source, session_id, title,))@@ -4477,8 +4494,9 @@ class TurnRunner:# fire time (staging repro 2026-07-31: gating registration on# the cache read meant it never registered and no# thread_rename op was ever sent).- agent._on_session_title = lambda title: (- self._runner._schedule_discord_semantic_thread_rename(+ agent._on_session_title = lambda title, title_source: (+ title_source == "llm"+ and self._runner._schedule_discord_semantic_thread_rename(source, session_id, title,))@@ -20381,14 +20399,34 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewif not callable(info_fn):return Nonetry:- info = info_fn(str(source.chat_id))- if (- isinstance(info, tuple)- and len(info) == 2- and all(isinstance(x, str) for x in info)- ):- return cast(Tuple[str, str], info)+ return _as_thread_info(info_fn(str(source.chat_id)))+ except Exception:return None++ async def _await_relay_auto_thread_info(+ self, source: SessionSource+ ) -> Optional[Tuple[str, str]]:+ """``_relay_auto_thread_info``, waited out until this turn delivers.++ The legacy send-result path can only answer once the reply is sent, and+ the caller asks at title time — one turn early. The adapter answers on+ the send either way, so the timeout is only a backstop for a turn that+ never sends at all; the turn's own inactivity limit is exactly how long+ that turn could still be alive.+ """+ # The connector-stamped prospective id is known at ingest, so most+ # sessions answer here and never wait at all.+ known = self._relay_auto_thread_info(source)+ if known is not None:+ return known+ adapter = self._adapter_for_source(source)+ wait_fn = getattr(adapter, "wait_for_auto_thread_info", None)+ if not callable(wait_fn) or not source.chat_id:+ return None+ # 0 means the operator disabled the turn limit; the backstop still needs one.+ timeout = _float_env("HERMES_AGENT_TIMEOUT", 1800) or 1800+ try:+ return _as_thread_info(await wait_fn(str(source.chat_id), timeout))except Exception:return None@@ -20424,18 +20462,15 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewif relay_info is None and not await asyncio.to_thread(self._is_discord_auto_thread_lane, source):- # Relay title turn with no feedback captured at schedule time:- # the auto-title thread races the delivery that produces the- # connector's send-result feedback (thread_id + initial name).- # Poll the adapter cache briefly before giving up — delivery is- # typically milliseconds-to-seconds behind the title.+ # Relay title turn with no feedback captured at schedule time: the+ # title comes off the user's opening message, so it beats the+ # delivery that produces the connector's send-result feedback+ # (thread_id + initial name) by the whole length of the turn. Wait+ # on the adapter for that send rather than guessing how long the+ # turn will take.if not self._is_relay_discord_channel_lane(source):return- for _ in range(20): # up to ~10s- relay_info = self._relay_auto_thread_info(source)- if relay_info is not None:- break- await asyncio.sleep(0.5)+ relay_info = await self._await_relay_auto_thread_info(source)if relay_info is None:# True miss: the connector did not auto-thread this reply# (policy off, DM, already-threaded, or send failed).diff --git a/tests/gateway/relay/test_relay_threads.py b/tests/gateway/relay/test_relay_threads.pyindex bb1dd45d14c..a456f6059ef 100644--- a/tests/gateway/relay/test_relay_threads.py+++ b/tests/gateway/relay/test_relay_threads.py@@ -260,6 +260,65 @@ async def test_send_without_thread_feedback_leaves_no_info():assert adapter.auto_thread_info_for_chat("chan2") is None+async def test_waiting_for_auto_thread_feedback_outlasts_the_turn():+ """The rename lane asks where the reply landed before the reply exists.++ Titling reads the user's opening message, so the question arrives one whole+ turn early — and a turn is however long the agent takes. Waiting on the send+ rather than on a fixed nap is what makes the answer arrive at all.+ """+ import asyncio++ adapter, stub = _adapter()++ async def send_outbound(action, *, platform=None):+ return {+ "success": True,+ "message_id": "m1",+ "thread_id": "th-auto-1",+ "auto_thread_name": "What is a duck",+ }++ stub.send_outbound = send_outbound # type: ignore[method-assign]+ waiting = asyncio.ensure_future(adapter.wait_for_auto_thread_info("chan1", 10.0))+ await asyncio.sleep(0)+ assert not waiting.done()++ await adapter.send("chan1", "quack")+ assert await waiting == ("th-auto-1", "What is a duck")+++async def test_a_reply_that_was_not_auto_threaded_reports_its_miss_on_send():+ """A miss is an answer, and the send is when we have it.++ Only a turn that never sends at all should reach the timeout, so a policy+ that doesn't auto-thread costs a wait as long as the turn, not as long as+ the backstop.+ """+ import asyncio++ adapter, stub = _adapter()++ async def send_outbound(action, *, platform=None):+ return {"success": True, "message_id": "m1"}++ stub.send_outbound = send_outbound # type: ignore[method-assign]+ waiting = asyncio.ensure_future(adapter.wait_for_auto_thread_info("chan1", 600.0))+ await asyncio.sleep(0)++ await adapter.send("chan1", "quack")+ assert await waiting is None+++async def test_waiting_for_auto_thread_feedback_gives_up():+ """A turn that never sends anything still has to end."""+ adapter, _stub = _adapter()+ assert await adapter.wait_for_auto_thread_info("chan-quiet", 0.05) is None++@pytest.mark.asyncioasync def test_auto_thread_feedback_is_bounded():adapter, stub = _adapter()@@ -291,6 +350,7 @@ def _mk_runner_stub():class _Stub:_is_relay_discord_channel_lane = GatewayRunner._is_relay_discord_channel_lane_relay_auto_thread_info = GatewayRunner._relay_auto_thread_info+ _await_relay_auto_thread_info = GatewayRunner._await_relay_auto_thread_info_is_discord_auto_thread_lane = GatewayRunner._is_discord_auto_thread_lane_sanitize_discord_thread_title = GatewayRunner._sanitize_discord_thread_title_rename_discord_auto_thread_for_session_title = (@@ -411,9 +471,12 @@ async def test_sibling_threads_in_one_channel_each_rename_to_own_thread():@pytest.mark.asyncio-async def test_title_rename_polls_feedback_that_arrives_late():- """The auto-title races delivery: feedback lands AFTER the rename lane- starts. The lane must poll the adapter cache and still rename."""+async def test_title_rename_waits_for_feedback_that_arrives_late():+ """The title beats delivery by a whole turn, and the lane still renames.++ Feedback only exists once the reply is sent, so the lane waits on the send+ rather than on a nap long enough to cover a turn it can't measure.+ """import asyncioadapter, stub_conn = _adapter()@@ -434,11 +497,21 @@ async def test_title_rename_polls_feedback_that_arrives_late():runner = _mk_runner_stub()(adapter)src = _relay_channel_source()- async def land_feedback_late():- await asyncio.sleep(0.7) # past the first poll tick- adapter._auto_thread_by_chat["chan-parent"] = ("th-9", "Initial words")+ async def send_outbound(action, *, platform=None):+ return {+ "success": True,+ "message_id": "m1",+ "thread_id": "th-9",+ "auto_thread_name": "Initial words",+ }- task = asyncio.create_task(land_feedback_late())+ stub_conn.send_outbound = send_outbound # type: ignore[method-assign]++ async def deliver_late():+ await asyncio.sleep(0.05)+ await adapter.send("chan-parent", "the reply")++ task = asyncio.create_task(deliver_late())await runner._rename_discord_auto_thread_for_session_title(src, "sess1", "Debugging the flux capacitor")@@ -455,11 +528,11 @@ async def test_title_rename_polls_feedback_that_arrives_late():@pytest.mark.asyncio-async def test_title_rename_true_miss_noops(monkeypatch):- """No feedback ever arrives (connector didn't auto-thread): no rename."""- import gateway.run as run_mod+async def test_title_rename_true_miss_noops():+ """The connector didn't auto-thread this reply, so there is nothing to rename."""+ import asyncio- adapter, _ = _adapter()+ adapter, stub_conn = _adapter()renames: list = []async def rename_thread(thread_id, name, **kw):@@ -469,14 +542,19 @@ async def test_title_rename_true_miss_noops(monkeypatch):adapter.rename_thread = rename_thread # type: ignore[method-assign]runner = _mk_runner_stub()(adapter)src = _relay_channel_source()- # Shrink the poll loop for test speed: 20 ticks of 0.5s -> patch sleep.- orig_sleep = run_mod.asyncio.sleep- async def fast_sleep(_s):- await orig_sleep(0)+ async def send_outbound(action, *, platform=None):+ return {"success": True, "message_id": "m1"}++ stub_conn.send_outbound = send_outbound # type: ignore[method-assign]++ async def deliver():+ await asyncio.sleep(0.05)+ await adapter.send("chan-parent", "the reply")- monkeypatch.setattr(run_mod.asyncio, "sleep", fast_sleep)+ task = asyncio.create_task(deliver())await runner._rename_discord_auto_thread_for_session_title(src, "sess1", "A title")+ await taskassert renames == []diff --git a/tests/gateway/test_session_title_rename_lane.py b/tests/gateway/test_session_title_rename_lane.pynew file mode 100644index 00000000000..691f31c19f9--- /dev/null+++ b/tests/gateway/test_session_title_rename_lane.py@@ -0,0 +1,55 @@+"""Which title stage is allowed to spend a platform rename.++Titling is two-stage: a derived slice of the user's own words lands inline, and+the model's version replaces it a moment later. A local sidebar wants both. A+Discord thread or a Telegram topic wants only the second — renaming twice lands+on the same name at twice the cost, and Discord allows two channel renames per+ten minutes, so the throwaway can be the one that survives.+"""++from __future__ import annotations++import types++import pytest++from gateway.config import Platform+from gateway.run import TurnRunner+++def _attach(lane):+ """Attach the title callback for *lane* and return (callback, renames)."""+ renames: list = []+ source = types.SimpleNamespace(platform=Platform.DISCORD, chat_id="chan-1")++ runner = types.SimpleNamespace(+ _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,+ _schedule_telegram_topic_title_rename=(+ lambda src, sid, title: renames.append(title)+ ),+ _schedule_discord_semantic_thread_rename=(+ lambda src, sid, title: renames.append(title)+ ),+ )+ holder = types.SimpleNamespace(+ _runner=runner,+ _attach_session_title_callback=TurnRunner._attach_session_title_callback,+ )+ agent = types.SimpleNamespace(session_id="sess-1")+ holder._attach_session_title_callback(+ holder, agent, types.SimpleNamespace(source=source)+ )+ return agent._on_session_title, renames++[email protected]("lane", ["telegram", "discord"])+def test_the_rename_waits_for_the_model_title(lane):+ callback, renames = _attach(lane)++ callback("fix the flaky auth test in log", "derived")+ assert renames == []++ callback("Fix flaky auth test", "llm")+ assert renames == ["Fix flaky auth test"]diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.pyindex 2df2b124e37..b5a9f0eacab 100644--- a/tests/test_tui_gateway_server.py+++ b/tests/test_tui_gateway_server.py@@ -12238,7 +12238,15 @@ def test_prompt_submit_wires_live_title_rename_callback(monkeypatch):hook = getattr(agent, "_on_session_title", None)assert callable(hook), "gateway did not install a live title-rename hook"- hook("Founding of Rome")+ # Titling is two-stage, and a local surface wants both: the sidebar renames+ # off the derived slice instantly and sharpens when the model's lands. Only+ # the lanes that spend a rate-limited remote rename filter by stage.+ hook("tell me about rome", "derived")+ hook("Founding of Rome", "llm")+ assert [payload["title"] for kind, payload in emitted if kind == "session.title"] == [+ "tell me about rome",+ "Founding of Rome",+ ]assert ("session.title",{"session_id": "session-key", "title": "Founding of Rome"},diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 1631441bfbf..b9dcb00bff8 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -9859,7 +9859,7 @@ def _run_prompt_submit(# sidebar repaints the moment a title lands, rather than waiting# for the next list refresh._title_key = session.get("session_key") or sid- agent._on_session_title = lambda t, _k=_title_key: _emit(+ agent._on_session_title = lambda t, _src, _k=_title_key: _emit("session.title", sid, {"session_id": _k, "title": t})result = agent.run_conversation(run_message, **run_kwargs)