Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(discord): drain all reaction tasks and in-flight callbacks
Xubin Ren2be3eeb9fee0
diff --git a/nanobot/channels/discord/runtime.py b/nanobot/channels/discord/runtime.pyindex 7ed7f3890..f0800a41b 100644--- a/nanobot/channels/discord/runtime.py+++ b/nanobot/channels/discord/runtime.py@@ -96,6 +96,8 @@ if DISCORD_AVAILABLE:self._channel.logger.warning("app command sync failed: {}", e)async def on_message(self, message: discord.Message) -> None:+ if self._channel._client is not self or not self._channel.is_running:+ returnawait self._channel._handle_discord_message(message)async def on_thread_delete(self, thread: discord.Thread) -> None:@@ -446,7 +448,8 @@ class DiscordChannel(BaseChannel):self._bot_user_id: str | None = Noneself._pending_reactions: dict[str, Any] = {} # chat_id -> message objectself._compaction_notices: dict[tuple[str, str], discord.Message] = {}- self._working_emoji_tasks: dict[str, asyncio.Task[None]] = {}+ self._working_emoji_tasks: dict[str, set[asyncio.Task[None]]] = {}+ self._inbound_tasks: set[asyncio.Task[Any]] = set()self._stream_bufs: dict[str, _StreamBuf] = {}self._known_channels: dict[str, Any] = {}@@ -625,6 +628,17 @@ class DiscordChannel(BaseChannel):raiseasync def _handle_discord_message(self, message: discord.Message) -> None:+ """Own in-flight callbacks until they finish or runtime reset drains them."""+ task = asyncio.current_task()+ if task is not None:+ self._inbound_tasks.add(task)+ try:+ await self._process_discord_message(message)+ finally:+ if task is not None:+ self._inbound_tasks.discard(task)++ async def _process_discord_message(self, message: discord.Message) -> None:"""Handle incoming Discord messages from discord.py.Self-loop guard: only drop messages from this bot's own account. Messages@@ -672,7 +686,17 @@ class DiscordChannel(BaseChannel):with suppress(Exception):await message.add_reaction(self.config.working_emoji)- self._working_emoji_tasks[channel_id] = asyncio.create_task(_delayed_working_emoji())+ task = asyncio.create_task(_delayed_working_emoji())+ self._working_emoji_tasks.setdefault(channel_id, set()).add(task)++ def reaction_done(done: asyncio.Task[None]) -> None:+ tasks = self._working_emoji_tasks.get(channel_id)+ if tasks is not None:+ tasks.discard(done)+ if not tasks:+ self._working_emoji_tasks.pop(channel_id, None)++ task.add_done_callback(reaction_done)try:await self._handle_message(@@ -884,9 +908,11 @@ class DiscordChannel(BaseChannel):async def _clear_reactions(self, chat_id: str) -> None:"""Remove all pending reactions after bot replies."""# Cancel delayed working emoji if it hasn't fired yet- task = self._working_emoji_tasks.pop(chat_id, None)- if task and not task.done():+ tasks = self._working_emoji_tasks.pop(chat_id, set())+ for task in tasks:task.cancel()+ if tasks:+ await asyncio.gather(*tasks, return_exceptions=True)msg_obj = self._pending_reactions.pop(chat_id, None)if msg_obj is None:@@ -904,7 +930,7 @@ class DiscordChannel(BaseChannel):async def _cancel_all_reactions(self) -> None:"""Stop delayed reactions and release their retained messages."""- tasks = tuple(self._working_emoji_tasks.values())+ tasks = tuple(task for group in self._working_emoji_tasks.values() for task in group)self._working_emoji_tasks.clear()self._pending_reactions.clear()for task in tasks:@@ -914,6 +940,14 @@ class DiscordChannel(BaseChannel):async def _reset_runtime_state(self, close_client: bool) -> None:"""Reset client and transient runtime state."""+ self._running = False+ # Drain callbacks before clearing the state they can still create after an await.+ current = asyncio.current_task()+ inbound = tuple(task for task in self._inbound_tasks if task is not current)+ for task in inbound:+ task.cancel()+ if inbound:+ await asyncio.gather(*inbound, return_exceptions=True)await self._cancel_all_typing()await self._cancel_all_reactions()self._compaction_notices.clear()diff --git a/nanobot/channels/discord/tests/test_discord_channel.py b/nanobot/channels/discord/tests/test_discord_channel.pyindex 93ee7e815..4118fa42c 100644--- a/nanobot/channels/discord/tests/test_discord_channel.py+++ b/nanobot/channels/discord/tests/test_discord_channel.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport asynciofrom pathlib import Pathfrom types import SimpleNamespace+from unittest.mock import AsyncMockimport pytest@@ -312,7 +313,7 @@ async def test_stop_cancels_pending_reaction_work() -> None:await asyncio.Event().wait()task = asyncio.create_task(delayed_reaction())- channel._working_emoji_tasks["123"] = task+ channel._working_emoji_tasks["123"] = {task}channel._pending_reactions["123"] = object()await asyncio.wait_for(started.wait(), timeout=1.0)@@ -323,6 +324,89 @@ async def test_stop_cancels_pending_reaction_work() -> None:assert channel._pending_reactions == {}[email protected]("second_channel", [456, 789])+async def test_stop_drains_reactions_for_every_inbound_message(second_channel: int) -> None:+ channel = DiscordChannel(+ DiscordConfig(enabled=True, allow_from=["*"], working_emoji_delay=60), MessageBus()+ )+ client = DiscordBotClient(channel, intents=discord.Intents.default())+ channel._client = client+ channel._running = True+ channel._handle_message = AsyncMock()+ messages = [_make_message(channel_id=456), _make_message(channel_id=second_channel)]+ for message in messages:+ message.add_reaction = AsyncMock()+ await client.on_message(message)+ tasks = [task for group in channel._working_emoji_tasks.values() for task in group]+ assert len(tasks) == 2++ await channel.stop()+ await channel.stop()++ assert all(task.cancelled() for task in tasks)+ assert channel._working_emoji_tasks == {}+ assert channel._pending_reactions == {}+ for message in messages:+ message.add_reaction.assert_awaited_once_with(channel.config.read_receipt_emoji)++[email protected]("blocked_stage", ["download", "receipt"])+async def test_stop_drains_inflight_message_before_reaction_cleanup(blocked_stage: str) -> None:+ channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())+ client = DiscordBotClient(channel, intents=discord.Intents.default())+ channel._client = client+ channel._running = True+ channel._handle_message = AsyncMock()+ entered = asyncio.Event()++ async def block(*args):+ entered.set()+ await asyncio.Event().wait()++ message = _make_message()+ message.add_reaction = AsyncMock()+ if blocked_stage == "download":+ channel._download_attachments = block+ else:+ message.add_reaction.side_effect = block+ handling = asyncio.create_task(client.on_message(message))+ await asyncio.wait_for(entered.wait(), timeout=1)++ await channel.stop()++ assert handling.cancelled()+ assert not channel._inbound_tasks+ assert not channel._typing_tasks+ assert not channel._working_emoji_tasks+ assert not channel._pending_reactions+ channel._handle_message.assert_not_awaited()+ # A queued event from the closed client must not run, even after a new runtime starts.+ channel._client = DiscordBotClient(channel, intents=discord.Intents.default())+ channel._running = True+ await client.on_message(_make_message())+ channel._handle_message.assert_not_awaited()+ await channel.stop()+++async def test_completed_reaction_tasks_release_registry_entries() -> None:+ channel = DiscordChannel(+ DiscordConfig(enabled=True, allow_from=["*"], working_emoji_delay=0), MessageBus()+ )+ channel._handle_message = AsyncMock()+ message = _make_message()+ message.add_reaction = AsyncMock()+ await channel._on_message(message)+ tasks = [task for group in channel._working_emoji_tasks.values() for task in group]+ await asyncio.gather(*tasks)++ assert not channel._working_emoji_tasks+ message.add_reaction.assert_any_await(channel.config.working_emoji)+ await channel.stop()++@pytest.mark.asyncioasync def test_on_message_ignores_self_messages() -> None:# Self-loop guard: messages from this bot's own account must be dropped (#3217).