diff --git a/nanobot/channels/discord/runtime.py b/nanobot/channels/discord/runtime.py index 1c506811b..38dcce695 100644 --- a/nanobot/channels/discord/runtime.py +++ b/nanobot/channels/discord/runtime.py @@ -36,8 +36,6 @@ if DISCORD_AVAILABLE: MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024 # 20MB MAX_MESSAGE_LEN = 2000 # Discord message character limit -# Start notices waiting for their outcome; a handful is plenty per bot. -_MAX_COMPACTION_NOTICES = 16 TYPING_INTERVAL_S = 8 @@ -259,6 +257,18 @@ if DISCORD_AVAILABLE: async def send_outbound(self, msg: OutboundMessage) -> None: """Send a nanobot outbound message using Discord transport rules.""" + compaction = msg.event if isinstance(msg.event, ContextCompactionEvent) else None + # A compaction's outcome replaces its own start notice in place, so + # the lifecycle stays visible as one message instead of two (#5719). + # Without a stored notice (restart, edit refused) it is sent as usual. + if compaction is not None and compaction.phase != "started": + notice = self._channel._compaction_notices.pop( + (msg.chat_id, compaction.compaction_id), + None, + ) + if notice is not None and await self._edit_compaction_notice(notice, msg.content or ""): + return + channel_id = int(msg.chat_id) channel = self._channel._known_channels.get(msg.chat_id) or self.get_channel(channel_id) @@ -271,14 +281,6 @@ if DISCORD_AVAILABLE: messageable_channel = cast(Messageable, channel) reference, mention_settings = self._build_reply_context(messageable_channel, msg.reply_to) - compaction = msg.event if isinstance(msg.event, ContextCompactionEvent) else None - # A compaction's outcome replaces its own start notice in place, so - # the lifecycle stays visible as one message instead of two (#5719). - # Without a stored notice (restart, edit refused) it is sent as usual. - if compaction is not None and compaction.phase != "started": - notice = self._channel._compaction_notices.pop(compaction.compaction_id, None) - if notice is not None and await self._edit_compaction_notice(notice, msg.content or ""): - return sent_media = False failed_media: list[str] = [] @@ -302,11 +304,15 @@ if DISCORD_AVAILABLE: kwargs["allowed_mentions"] = mention_settings sent = await messageable_channel.send(**kwargs) if compaction is not None and compaction.phase == "started" and index == 0: - self._channel._remember_compaction_notice(compaction.compaction_id, sent) + self._channel._remember_compaction_notice( + msg.chat_id, + compaction.compaction_id, + sent, + ) - async def _edit_compaction_notice(self, notice: Any, content: str) -> bool: + async def _edit_compaction_notice(self, notice: discord.Message, content: str) -> bool: """Replace a start notice's text with the outcome; False when Discord refused.""" - if not content or notice is None: + if not content: return False try: await notice.edit(content=content) @@ -417,7 +423,7 @@ class DiscordChannel(BaseChannel): self._typing_tasks: dict[str, asyncio.Task[None]] = {} self._bot_user_id: str | None = None self._pending_reactions: dict[str, Any] = {} # chat_id -> message object - self._compaction_notices: dict[str, Any] = {} # compaction_id -> start notice message + self._compaction_notices: dict[tuple[str, str], discord.Message] = {} self._working_emoji_tasks: dict[str, asyncio.Task[None]] = {} self._stream_bufs: dict[str, _StreamBuf] = {} self._known_channels: dict[str, Any] = {} @@ -488,12 +494,14 @@ class DiscordChannel(BaseChannel): self._running = False await self._reset_runtime_state(close_client=True) - def _remember_compaction_notice(self, compaction_id: str, message: Any) -> None: - """Keep the start notice so the outcome can edit it; bounded in case outcomes never arrive.""" - self._compaction_notices[compaction_id] = message - while len(self._compaction_notices) > _MAX_COMPACTION_NOTICES: - oldest = next(iter(self._compaction_notices)) - del self._compaction_notices[oldest] + def _remember_compaction_notice( + self, + chat_id: str, + compaction_id: str, + message: discord.Message, + ) -> None: + """Keep a start notice until its matching outcome consumes it.""" + self._compaction_notices[(chat_id, compaction_id)] = message async def send(self, msg: OutboundMessage) -> None: """Send a message through Discord using discord.py.""" @@ -862,6 +870,7 @@ class DiscordChannel(BaseChannel): async def _reset_runtime_state(self, close_client: bool) -> None: """Reset client and typing state.""" await self._cancel_all_typing() + self._compaction_notices.clear() self._stream_bufs.clear() self._known_channels.clear() if close_client and self._client is not None and not self._client.is_closed(): diff --git a/nanobot/channels/discord/tests/test_discord_channel.py b/nanobot/channels/discord/tests/test_discord_channel.py index f4d9d0059..cdaeeba14 100644 --- a/nanobot/channels/discord/tests/test_discord_channel.py +++ b/nanobot/channels/discord/tests/test_discord_channel.py @@ -1418,10 +1418,15 @@ async def test_send_succeeds_normally() -> None: assert sent_messages[0].chat_id == "123" -def _compaction_message(content: str, phase: str, compaction_id: str = "c1") -> OutboundMessage: +def _compaction_message( + content: str, + phase: str, + compaction_id: str = "c1", + chat_id: str = "123", +) -> OutboundMessage: return OutboundMessage( channel="discord", - chat_id="123", + chat_id=chat_id, content=content, event=ContextCompactionEvent(compaction_id=compaction_id, phase=phase), # type: ignore[arg-type] ) @@ -1446,6 +1451,11 @@ async def test_compaction_outcome_edits_the_start_notice_in_place() -> None: owner, client = _client_with_channel(target) await client.send_outbound(_compaction_message("Compressing context…", "started")) + + async def reject_fetch(_channel_id: int): + raise AssertionError("an existing notice should be edited without resolving its channel") + + client.fetch_channel = reject_fetch # type: ignore[method-assign] await client.send_outbound(_compaction_message("Context compacted.", "succeeded")) assert [payload["content"] for payload in target.sent_payloads] == ["Compressing context…"] @@ -1482,3 +1492,37 @@ async def test_compaction_outcome_falls_back_to_send_when_edit_fails() -> None: ] assert owner._compaction_notices == {} + +@pytest.mark.asyncio +async def test_all_in_flight_compaction_notices_are_retained_until_outcomes() -> None: + owner = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus()) + client = DiscordBotClient(owner, intents=discord.Intents.none()) + targets = {str(index): _FakeChannel(channel_id=index) for index in range(17)} + client.get_channel = lambda channel_id: targets.get(str(channel_id)) # type: ignore[method-assign] + + for chat_id in targets: + await client.send_outbound( + _compaction_message("Compressing context…", "started", f"c-{chat_id}", chat_id) + ) + + assert len(owner._compaction_notices) == len(targets) + + for chat_id in targets: + await client.send_outbound( + _compaction_message("Context compacted.", "succeeded", f"c-{chat_id}", chat_id) + ) + + assert all(len(target.sent_payloads) == 1 for target in targets.values()) + assert all(target.sent_messages[0].content == "Context compacted." for target in targets.values()) + assert owner._compaction_notices == {} + + +@pytest.mark.asyncio +async def test_reset_discards_in_flight_compaction_notices() -> None: + target = _FakeChannel(channel_id=123) + owner, client = _client_with_channel(target) + await client.send_outbound(_compaction_message("Compressing context…", "started")) + + await owner._reset_runtime_state(close_client=False) + + assert owner._compaction_notices == {}