Skip to content

The agent that grows with you

fix(discord): batch bot tag continuations

simpolism5d220ed693b4
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index bc6bcfb38aa..382740a2feb 100644
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@ -1034,6 +1034,10 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
# Text batching: merge rapid successive messages (Telegram-style)
self._text_batch_delay_seconds = env_float("HERMES_DISCORD_TEXT_BATCH_DELAY_SECONDS", 0.6)
self._text_batch_split_delay_seconds = env_float("HERMES_DISCORD_TEXT_BATCH_SPLIT_DELAY_SECONDS", 2.0)
+ # A tagged bot may emit one logical response as several Discord
+ # messages. Keep its unmentioned continuation chunks eligible for the
+ # existing text batcher during this short, sender-scoped window.
+ self._bot_tag_debounce_until: Dict[str, float] = {}
self._voice_text_channels: Dict[int, int] = {} # guild_id -> text_channel_id
self._voice_sources: Dict[int, Dict[str, Any]] = {} # guild_id -> linked text channel source metadata
self._voice_timeout_tasks: Dict[int, asyncio.Task] = {} # guild_id -> timeout task
@@ -1434,13 +1438,19 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
role_authorized = False
if getattr(message.author, "bot", False):
allow_bots = self._get_allow_bots()
+ bot_tag_continuation = self._is_bot_tag_debounce_continuation(message)
if allow_bots == "none":
return False, False
- if allow_bots == "mentions" and not self._self_is_explicitly_mentioned(message):
+ if (
+ allow_bots == "mentions"
+ and not self._self_is_explicitly_mentioned(message)
+ and not bot_tag_continuation
+ ):
return False, False
if (
self._discord_bots_require_inline_mention()
and not self._self_is_raw_mentioned(message)
+ and not bot_tag_continuation
):
return False, False
else:
@@ -1490,6 +1500,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
admitted, role_authorized = self._discord_message_admission(message, claim=True)
if not admitted:
return False
+ self._record_bot_tag_debounce(message)
return await self._handle_message(message, role_authorized=role_authorized)
# --- gateway_platform_event fire-sites ---
@@ -4771,6 +4782,46 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
raw = self._gate_raw("allow_bots", "DISCORD_ALLOW_BOTS")
return str(raw or "none").lower().strip() or "none"
+ @staticmethod
+ def _bot_tag_debounce_key(message: Any) -> str:
+ return (
+ f"{getattr(getattr(message, 'channel', None), 'id', '')}:"
+ f"{getattr(getattr(message, 'author', None), 'id', '')}"
+ )
+
+ def _record_bot_tag_debounce(self, message: Any) -> None:
+ """Open a short continuation window after a bot-authored tag."""
+ if (
+ self._text_batch_delay_seconds <= 0
+ or not getattr(getattr(message, "author", None), "bot", False)
+ or not self._self_is_explicitly_mentioned(message)
+ ):
+ return
+ window = max(
+ self._text_batch_delay_seconds,
+ self._text_batch_split_delay_seconds,
+ )
+ self._bot_tag_debounce_until[self._bot_tag_debounce_key(message)] = (
+ time.monotonic() + window
+ )
+
+ def _is_bot_tag_debounce_continuation(self, message: Any) -> bool:
+ """Return whether an unmentioned chunk belongs to a recent bot tag."""
+ if (
+ getattr(self, "_text_batch_delay_seconds", 0) <= 0
+ or not getattr(getattr(message, "author", None), "bot", False)
+ ):
+ return False
+ key = self._bot_tag_debounce_key(message)
+ debounce_until = getattr(self, "_bot_tag_debounce_until", None)
+ if not debounce_until:
+ return False
+ deadline = debounce_until.get(key, 0.0)
+ if deadline <= time.monotonic():
+ debounce_until.pop(key, None)
+ return False
+ return True
+
def _discord_free_response_channels(self) -> set:
"""Channel IDs/names needing no mention; a lone "*" is preserved for wildcard short-circuit."""
raw = self.config.extra.get("free_response_channels")
@@ -5799,7 +5850,11 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
)
in_bot_thread = self._in_bot_thread(message)
if require_mention and not is_free_channel and not in_bot_thread:
- if not self._self_is_explicitly_mentioned(message) and not mention_prefix:
+ if (
+ not self._self_is_explicitly_mentioned(message)
+ and not mention_prefix
+ and not self._is_bot_tag_debounce_continuation(message)
+ ):
return False
# Auto-thread: isolate each @mention in a text channel into its own thread (Slack-style).
auto_threaded_channel = None
@@ -5933,6 +5988,12 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
timestamp=message.created_at, auto_skill=_skills, channel_prompt=_channel_prompt,
channel_context=_channel_context,
)
+ if (
+ getattr(getattr(message, "author", None), "bot", False)
+ and self._is_bot_tag_debounce_continuation(message)
+ ):
+ event._bot_tag_debounce = True # type: ignore[attr-defined]
+
# Track participation so follow-ups in this thread don't need @mention.
if thread_id:
self._threads.mark(thread_id)
@@ -5943,6 +6004,13 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
await self.handle_message(event)
return True
+ def _text_batch_delay_for(self, pending: Optional[MessageEvent]) -> float:
+ """A bot handoff's continuation chunks arrive at Discord's send rate (~1/s), so a
+ batch opened by a bot tag waits the split delay regardless of chunk length."""
+ if getattr(pending, "_bot_tag_debounce", False):
+ return self._text_batch_split_delay_seconds
+ return super()._text_batch_delay_for(pending)
+
# ---------------------------------------------------------------------------
# Discord UI Components (outside the adapter class)
diff --git a/tests/gateway/test_discord_bot_tag_debounce.py b/tests/gateway/test_discord_bot_tag_debounce.py
new file mode 100644
index 00000000000..13e43a6960c
--- /dev/null
+++ b/tests/gateway/test_discord_bot_tag_debounce.py
@@ -0,0 +1,99 @@
+"""Tests for coalescing rapid bot-authored Discord message chunks."""
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import discord
+import pytest
+
+from gateway.platforms.helpers import MessageDeduplicator
+from plugins.platforms.discord.adapter import DiscordAdapter
+
+
+def _message(*, author_id: int, channel_id: int, mentions=()):
+ return SimpleNamespace(
+ id=author_id * 100 + channel_id,
+ author=SimpleNamespace(id=author_id, bot=True),
+ channel=SimpleNamespace(id=channel_id),
+ mentions=list(mentions),
+ content="chunk",
+ type=discord.MessageType.default,
+ )
+
+
+def _adapter():
+ adapter = object.__new__(DiscordAdapter)
+ adapter._bot_tag_debounce_until = {}
+ adapter._text_batch_delay_seconds = 0.6
+ adapter._text_batch_split_delay_seconds = 2.0
+ adapter._self_is_explicitly_mentioned = lambda message: bool(message.mentions)
+ return adapter
+
+
+def test_tag_opens_short_window_for_same_bot_and_channel_only():
+ adapter = _adapter()
+ tagged = _message(author_id=1, channel_id=10, mentions=[SimpleNamespace(id=99)])
+ continuation = _message(author_id=1, channel_id=10)
+
+ adapter._record_bot_tag_debounce(tagged)
+
+ assert adapter._is_bot_tag_debounce_continuation(continuation) is True
+ assert adapter._is_bot_tag_debounce_continuation(
+ _message(author_id=2, channel_id=10)
+ ) is False
+ assert adapter._is_bot_tag_debounce_continuation(
+ _message(author_id=1, channel_id=11)
+ ) is False
+
+
+def test_disabling_text_batching_disables_bot_tag_debounce():
+ adapter = _adapter()
+ adapter._text_batch_delay_seconds = 0
+ tagged = _message(author_id=1, channel_id=10, mentions=[SimpleNamespace(id=99)])
+
+ adapter._record_bot_tag_debounce(tagged)
+
+ assert adapter._is_bot_tag_debounce_continuation(
+ _message(author_id=1, channel_id=10)
+ ) is False
+
+
+def test_uninitialized_debounce_state_is_treated_as_disabled():
+ adapter = object.__new__(DiscordAdapter)
+
+ assert adapter._is_bot_tag_debounce_continuation(
+ _message(author_id=1, channel_id=10)
+ ) is False
+
+
+def test_mentions_mode_admits_unmentioned_chunk_during_debounce():
+ adapter = _adapter()
+ own_user = SimpleNamespace(id=99)
+ adapter._client = SimpleNamespace(user=own_user)
+ adapter._dedup = MessageDeduplicator()
+ adapter._get_allow_bots = Mock(return_value="mentions")
+ adapter._discord_bots_require_inline_mention = Mock(return_value=True)
+ adapter._self_is_raw_mentioned = Mock(return_value=False)
+ tagged = _message(author_id=1, channel_id=10, mentions=[own_user])
+ continuation = _message(author_id=1, channel_id=10)
+ adapter._record_bot_tag_debounce(tagged)
+
+ admitted, _ = adapter._discord_message_admission(continuation, claim=True)
+
+ assert admitted is True
+
+
+async def test_rejected_bot_tag_does_not_open_debounce_window():
+ adapter = _adapter()
+ adapter._ready_event = asyncio.Event()
+ adapter._ready_event.set()
+ adapter._record_bot_tag_debounce = Mock()
+ adapter._discord_message_admission = Mock(return_value=(False, False))
+ adapter._handle_message = AsyncMock()
+ message = _message(author_id=1, channel_id=10)
+
+ assert await adapter._dispatch_discord_message(message) is False
+ adapter._record_bot_tag_debounce.assert_not_called()
+ adapter._handle_message.assert_not_awaited()
diff --git a/tests/gateway/test_discord_free_response.py b/tests/gateway/test_discord_free_response.py
index fc58b982a37..9548facbe3b 100644
--- a/tests/gateway/test_discord_free_response.py
+++ b/tests/gateway/test_discord_free_response.py
@@ -1,5 +1,6 @@
"""Tests for Discord free-response defaults and mention gating."""
+import asyncio
from datetime import datetime, timezone
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -227,6 +228,62 @@ async def test_discord_accepts_and_strips_bot_mentions_when_required(adapter, mo
assert event.text == "hello with mention"
+async def test_unmentioned_bot_chunks_join_recent_tag_batch(adapter, monkeypatch):
+ monkeypatch.setenv("DISCORD_REQUIRE_MENTION", "true")
+ monkeypatch.setenv("DISCORD_AUTO_THREAD", "false")
+ adapter._text_batch_delay_seconds = 0.01
+ adapter._text_batch_split_delay_seconds = 0.02
+ channel = FakeTextChannel(channel_id=321)
+ bot_user = adapter._client.user
+ tagged = make_message(
+ channel=channel,
+ content=f"<@{bot_user.id}> first chunk",
+ mentions=[bot_user],
+ )
+ tagged.author.bot = True
+ second = make_message(channel=channel, content="second chunk")
+ second.id = 124
+ second.author.bot = True
+ third = make_message(channel=channel, content="third chunk")
+ third.id = 125
+ third.author.bot = True
+ adapter._record_bot_tag_debounce(tagged)
+
+ assert await adapter._handle_message(tagged, role_authorized=True) is True
+ assert await adapter._handle_message(second, role_authorized=True) is True
+ assert await adapter._handle_message(third, role_authorized=True) is True
+ await asyncio.sleep(0.03)
+
+ adapter.handle_message.assert_awaited_once()
+ event = adapter.handle_message.await_args.args[0]
+ assert event.text == "first chunk\nsecond chunk\nthird chunk"
+
+
+async def test_short_tagged_bot_chunk_waits_for_followup_window(adapter, monkeypatch):
+ monkeypatch.setenv("DISCORD_REQUIRE_MENTION", "true")
+ monkeypatch.setenv("DISCORD_AUTO_THREAD", "false")
+ adapter._text_batch_delay_seconds = 0.01
+ adapter._text_batch_split_delay_seconds = 0.08
+ channel = FakeTextChannel(channel_id=321)
+ bot_user = adapter._client.user
+ tagged = make_message(
+ channel=channel,
+ content=f"<@{bot_user.id}> short chunk",
+ mentions=[bot_user],
+ )
+ tagged.author.bot = True
+ adapter._record_bot_tag_debounce(tagged)
+
+ assert await adapter._handle_message(tagged, role_authorized=True) is True
+ await asyncio.sleep(0.03)
+ adapter.handle_message.assert_not_awaited()
+
+ await asyncio.sleep(0.07)
+ adapter.handle_message.assert_awaited_once()
+
+
@pytest.mark.asyncio
async def test_discord_reply_message_skips_auto_thread(adapter, monkeypatch):
"""Quote-replies should stay in-channel instead of trying to create a thread."""
diff --git a/website/docs/user-guide/messaging/discord.md b/website/docs/user-guide/messaging/discord.md
index e03802d3416..7f49a5275a8 100644
--- a/website/docs/user-guide/messaging/discord.md
+++ b/website/docs/user-guide/messaging/discord.md
@@ -323,7 +323,7 @@ Discord behavior is controlled through two files: **`~/.hermes/.env`** for crede
| `DISCORD_ALLOW_ANY_ATTACHMENT` | No | `false` | When `true`, the bot accepts attachments of any file type (not just the built-in PDF/text/zip/office allowlist). Unknown types are cached to disk and surfaced to the agent as a local path with `application/octet-stream` MIME so it can inspect them with `terminal` / `read_file` / `ffprobe` / etc. |
| `DISCORD_MAX_ATTACHMENT_BYTES` | No | `33554432` | Maximum bytes per attachment the gateway will download and cache. Default 32 MiB. Set to `0` for no cap (attachments are held in memory while being written, so unlimited carries a real memory cost). |
| `HERMES_DISCORD_TEXT_BATCH_DELAY_SECONDS` | No | `0.6` | Grace window the adapter waits before flushing a queued text chunk. Useful for smoothing streamed output. |
-| `HERMES_DISCORD_TEXT_BATCH_SPLIT_DELAY_SECONDS` | No | `2.0` | Delay between split chunks when a single message exceeds Discord's length limit. |
+| `HERMES_DISCORD_TEXT_BATCH_SPLIT_DELAY_SECONDS` | No | `2.0` | Longer quiet period for near-limit Discord splits and continuation chunks from a recently tagged bot in the same channel. |
:::tip Bot-to-bot handoffs require hard mentions
`DISCORD_ALLOW_BOTS` defaults to `"none"`. When you opt into `"mentions"` or `"all"`, bot-authored messages must contain a literal inline mention of Hermes by default. Discord's automatic replied-user ping does not count, so replying to another bot cannot silently invoke it again.