fix(discord): update the compaction notice in place instead of sending a second message
Automatic compaction delivered two standalone Discord messages, "Compressing context…" and "Context compacted.", even with sendProgress off. The lifecycle itself is information the user should keep seeing (it changes the context of every later turn), so the dispatcher keeps delivering both events to every channel; the noise is a presentation problem of the Discord adapter. The Discord client now remembers the message it sent for a compaction's "started" event, keyed by compaction_id, and edits that message with the outcome when it arrives, so one compaction is one message. Without a stored notice (restart, or the edit being refused) the outcome is sent as before. The earlier dispatcher-level filtering is dropped, and the manager test pins that both lifecycle events reach a channel whose progress messages are off. Fixes #5719
This commit is contained in:
1 parent
a068de8068
commit
4d712937a5
4 files changed
+123
-64
No files matched your search
@@ -14,7 +14,7 @@ from typing import TYPE_CHECKING, Any, Literal, cast
|
||||
from pydantic import Field
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.command.builtin import build_help_text
|
||||
@@ -36,6 +36,8 @@ 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
|
||||
|
||||
|
||||
@@ -269,6 +271,14 @@ 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] = []
|
||||
|
||||
@@ -290,7 +300,20 @@ if DISCORD_AVAILABLE:
|
||||
if index == 0 and reference is not None and not sent_media:
|
||||
kwargs["reference"] = reference
|
||||
kwargs["allowed_mentions"] = mention_settings
|
||||
await messageable_channel.send(**kwargs)
|
||||
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)
|
||||
|
||||
async def _edit_compaction_notice(self, notice: Any, content: str) -> bool:
|
||||
"""Replace a start notice's text with the outcome; False when Discord refused."""
|
||||
if not content or notice is None:
|
||||
return False
|
||||
try:
|
||||
await notice.edit(content=content)
|
||||
except Exception as e:
|
||||
self._channel.logger.warning("compaction notice edit failed, sending instead: {}", e)
|
||||
return False
|
||||
return True
|
||||
|
||||
async def _send_file(
|
||||
self,
|
||||
@@ -394,6 +417,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._working_emoji_tasks: dict[str, asyncio.Task[None]] = {}
|
||||
self._stream_bufs: dict[str, _StreamBuf] = {}
|
||||
self._known_channels: dict[str, Any] = {}
|
||||
@@ -464,6 +488,13 @@ 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]
|
||||
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
"""Send a message through Discord using discord.py."""
|
||||
client = self._client
|
||||
|
||||
@@ -12,7 +12,7 @@ pytest.importorskip("discord")
|
||||
import discord
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.discord.runtime import (
|
||||
MAX_MESSAGE_LEN,
|
||||
@@ -1416,3 +1416,69 @@ async def test_send_succeeds_normally() -> None:
|
||||
assert len(sent_messages) == 1
|
||||
assert sent_messages[0].content == "hello world"
|
||||
assert sent_messages[0].chat_id == "123"
|
||||
|
||||
|
||||
def _compaction_message(content: str, phase: str, compaction_id: str = "c1") -> OutboundMessage:
|
||||
return OutboundMessage(
|
||||
channel="discord",
|
||||
chat_id="123",
|
||||
content=content,
|
||||
event=ContextCompactionEvent(compaction_id=compaction_id, phase=phase), # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
|
||||
def _client_with_channel(target: _FakeChannel) -> tuple[DiscordChannel, "DiscordBotClient"]:
|
||||
owner = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
|
||||
client = DiscordBotClient(owner, intents=discord.Intents.none())
|
||||
|
||||
async def fetch_channel(channel_id: int):
|
||||
return target if channel_id == target.id else None
|
||||
|
||||
client.fetch_channel = fetch_channel # type: ignore[method-assign]
|
||||
return owner, client
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_compaction_outcome_edits_the_start_notice_in_place() -> None:
|
||||
# One message per compaction: the outcome replaces the "Compressing…" text
|
||||
# instead of arriving as a second notice (#5719).
|
||||
target = _FakeChannel(channel_id=123)
|
||||
owner, client = _client_with_channel(target)
|
||||
|
||||
await client.send_outbound(_compaction_message("Compressing context…", "started"))
|
||||
await client.send_outbound(_compaction_message("Context compacted.", "succeeded"))
|
||||
|
||||
assert [payload["content"] for payload in target.sent_payloads] == ["Compressing context…"]
|
||||
assert target.sent_messages[0].content == "Context compacted."
|
||||
assert owner._compaction_notices == {}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_compaction_outcome_without_a_start_notice_is_sent() -> None:
|
||||
# After a restart (or when the edit is refused) the outcome still arrives.
|
||||
target = _FakeChannel(channel_id=123)
|
||||
owner, client = _client_with_channel(target)
|
||||
|
||||
await client.send_outbound(_compaction_message("Unable to compact context.", "failed"))
|
||||
|
||||
assert [payload["content"] for payload in target.sent_payloads] == ["Unable to compact context."]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_compaction_outcome_falls_back_to_send_when_edit_fails() -> None:
|
||||
target = _FakeChannel(channel_id=123)
|
||||
owner, client = _client_with_channel(target)
|
||||
await client.send_outbound(_compaction_message("Compressing context…", "started"))
|
||||
|
||||
async def refuse_edit(**_kwargs) -> None:
|
||||
raise RuntimeError("message deleted")
|
||||
|
||||
target.sent_messages[0].edit = refuse_edit # type: ignore[method-assign]
|
||||
await client.send_outbound(_compaction_message("Context compacted.", "succeeded"))
|
||||
|
||||
assert [payload["content"] for payload in target.sent_payloads] == [
|
||||
"Compressing context…",
|
||||
"Context compacted.",
|
||||
]
|
||||
assert owner._compaction_notices == {}
|
||||
|
||||
@@ -15,7 +15,6 @@ from loguru import logger
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import (
|
||||
ContextCompactionEvent,
|
||||
ProgressEvent,
|
||||
RetryWaitEvent,
|
||||
RuntimeModelUpdatedEvent,
|
||||
@@ -811,18 +810,6 @@ class ChannelManager:
|
||||
):
|
||||
continue
|
||||
|
||||
# Compaction changes the context of every later turn, so its
|
||||
# outcome (compacted / failed / cancelled) is always delivered.
|
||||
# The "Compressing context…" start notice is transient progress
|
||||
# text and follows the channel's progress setting, so a channel
|
||||
# with progress off gets one notice per compaction, not two.
|
||||
if (
|
||||
isinstance(event, ContextCompactionEvent)
|
||||
and event.phase == "started"
|
||||
and not self._should_send_progress(msg.channel)
|
||||
):
|
||||
continue
|
||||
|
||||
if isinstance(event, RetryWaitEvent):
|
||||
continue
|
||||
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
"""Context-compaction notices on channels with ``send_progress`` off.
|
||||
"""Context-compaction lifecycle notices are delivered regardless of ``send_progress``.
|
||||
|
||||
A compaction emits ``ContextCompactionEvent`` start/finish notices. The
|
||||
outcome (compacted / failed / cancelled) is always delivered because it
|
||||
changes the context of every later turn; the "Compressing context…" start
|
||||
notice is transient progress text and follows the channel's progress
|
||||
setting, so such a channel receives one notice per compaction instead of
|
||||
two (#5719).
|
||||
Compaction changes the context of every later turn, so both the start and
|
||||
the outcome of a compaction are information for the user, not progress
|
||||
chatter: a channel with ``send_progress`` off still receives them. Reducing
|
||||
the noise (one message updated in place) is the adapter's job; see the
|
||||
Discord channel (#5719).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,6 +16,7 @@ import pytest
|
||||
|
||||
from nanobot.bus.outbound_events import (
|
||||
ContextCompactionEvent,
|
||||
ProgressEvent,
|
||||
outbound_message_for_event,
|
||||
)
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -66,49 +66,24 @@ async def _dispatch_until(manager: ChannelManager, expected: int) -> None:
|
||||
pass
|
||||
|
||||
|
||||
def _compaction(phase: str):
|
||||
return outbound_message_for_event(
|
||||
channel="mock",
|
||||
chat_id="c1",
|
||||
event=ContextCompactionEvent(compaction_id="cmp-1", phase=phase),
|
||||
)
|
||||
def _sent_contents(manager: ChannelManager) -> list[str]:
|
||||
return [call.args[0].content for call in manager.channels["mock"]._send_mock.await_args_list]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_only_the_outcome_is_delivered_when_progress_is_off(manager):
|
||||
channel = manager.channels["mock"]
|
||||
channel.send_progress = False
|
||||
await manager.bus.publish_outbound(_compaction("started"))
|
||||
await manager.bus.publish_outbound(_compaction("succeeded"))
|
||||
async def test_compaction_lifecycle_is_delivered_with_progress_off(manager: ChannelManager) -> None:
|
||||
manager.channels["mock"].send_progress = False
|
||||
for event in (
|
||||
ProgressEvent(content="ordinary progress"),
|
||||
ContextCompactionEvent(compaction_id="c1", phase="started"),
|
||||
ContextCompactionEvent(compaction_id="c1", phase="succeeded"),
|
||||
):
|
||||
await manager.bus.publish_outbound(
|
||||
outbound_message_for_event(channel="mock", chat_id="chat", event=event)
|
||||
)
|
||||
|
||||
await _dispatch_until(manager, expected=1)
|
||||
await _dispatch_until(manager, 2)
|
||||
|
||||
contents = [call.args[0].content for call in channel._send_mock.await_args_list]
|
||||
assert contents == ["Context compacted."]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_and_outcome_are_delivered_when_progress_is_on(manager):
|
||||
channel = manager.channels["mock"]
|
||||
channel.send_progress = True
|
||||
await manager.bus.publish_outbound(_compaction("started"))
|
||||
await manager.bus.publish_outbound(_compaction("succeeded"))
|
||||
|
||||
await _dispatch_until(manager, expected=2)
|
||||
|
||||
contents = [call.args[0].content for call in channel._send_mock.await_args_list]
|
||||
assert contents == ["Compressing context…", "Context compacted."]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_failed_and_cancelled_outcomes_are_delivered_when_progress_is_off(manager):
|
||||
channel = manager.channels["mock"]
|
||||
channel.send_progress = False
|
||||
await manager.bus.publish_outbound(_compaction("started"))
|
||||
await manager.bus.publish_outbound(_compaction("failed"))
|
||||
await manager.bus.publish_outbound(_compaction("cancelled"))
|
||||
|
||||
await _dispatch_until(manager, expected=2)
|
||||
|
||||
contents = [call.args[0].content for call in channel._send_mock.await_args_list]
|
||||
assert contents == ["Unable to compact context.", "Context compaction cancelled."]
|
||||
contents = _sent_contents(manager)
|
||||
assert "ordinary progress" not in contents
|
||||
assert len(contents) == 2
|
||||
Reference in new issue
Block a user