From ac3d7eb4c12bbd5d2cc3518a2d2c08d67b4082d9 Mon Sep 17 00:00:00 2001 From: yu-xin-c <2182712990@qq.com> Date: Fri, 18 Sep 2026 14:45:27 +0800 Subject: [PATCH] fix(discord): clean up reaction state on stop --- nanobot/channels/discord/runtime.py | 13 +++++++++++- .../discord/tests/test_discord_channel.py | 21 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/nanobot/channels/discord/runtime.py b/nanobot/channels/discord/runtime.py index bcd5f6dad..7ed7f3890 100644 --- a/nanobot/channels/discord/runtime.py +++ b/nanobot/channels/discord/runtime.py @@ -902,9 +902,20 @@ class DiscordChannel(BaseChannel): for channel_id in channel_ids: await self._stop_typing(channel_id) + async def _cancel_all_reactions(self) -> None: + """Stop delayed reactions and release their retained messages.""" + tasks = tuple(self._working_emoji_tasks.values()) + self._working_emoji_tasks.clear() + self._pending_reactions.clear() + for task in tasks: + task.cancel() + if tasks: + await asyncio.gather(*tasks, return_exceptions=True) + async def _reset_runtime_state(self, close_client: bool) -> None: - """Reset client and typing state.""" + """Reset client and transient runtime state.""" await self._cancel_all_typing() + await self._cancel_all_reactions() self._compaction_notices.clear() self._stream_bufs.clear() self._known_channels.clear() diff --git a/nanobot/channels/discord/tests/test_discord_channel.py b/nanobot/channels/discord/tests/test_discord_channel.py index dba0aee1c..93ee7e815 100644 --- a/nanobot/channels/discord/tests/test_discord_channel.py +++ b/nanobot/channels/discord/tests/test_discord_channel.py @@ -302,6 +302,27 @@ async def test_stop_is_safe_after_partial_start(monkeypatch) -> None: assert channel._client is None +@pytest.mark.asyncio +async def test_stop_cancels_pending_reaction_work() -> None: + channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus()) + started = asyncio.Event() + + async def delayed_reaction() -> None: + started.set() + await asyncio.Event().wait() + + task = asyncio.create_task(delayed_reaction()) + channel._working_emoji_tasks["123"] = task + channel._pending_reactions["123"] = object() + await asyncio.wait_for(started.wait(), timeout=1.0) + + await channel.stop() + + assert task.cancelled() + assert channel._working_emoji_tasks == {} + assert channel._pending_reactions == {} + + @pytest.mark.asyncio async def test_on_message_ignores_self_messages() -> None: # Self-loop guard: messages from this bot's own account must be dropped (#3217).