fix: stop sending context compaction notifications

This commit is contained in:
Arthur K. authored and Xubin Ren committed 2026-09-30 13:44:42 +08:00
1 parent fbe9b4fd72
commit 0b402d0414
31 files changed
+157 -38

No files matched your search

+5 -2
View File
@@ -1245,6 +1245,7 @@ class Consolidator:
runtime: LLMRuntime, runtime: LLMRuntime,
max_suffix: int = 0, max_suffix: int = 0,
events: EventSink = NO_EVENTS, events: EventSink = NO_EVENTS,
notify: bool = False,
) -> str | None: ) -> str | None:
"""Replace archived history with a summary checkpoint. """Replace archived history with a summary checkpoint.
@@ -1267,7 +1268,7 @@ class Consolidator:
compaction_id = uuid4().hex compaction_id = uuid4().hex
await events.emit( await events.emit(
ContextCompactionEvent(compaction_id=compaction_id, phase="started"), ContextCompactionEvent(compaction_id=compaction_id, phase="started", notify=notify),
) )
last_active = session.updated_at last_active = session.updated_at
archive_end = archive_start + len(messages_to_archive) archive_end = archive_start + len(messages_to_archive)
@@ -1288,12 +1289,13 @@ class Consolidator:
ContextCompactionEvent( ContextCompactionEvent(
compaction_id=compaction_id, compaction_id=compaction_id,
phase="cancelled" if isinstance(exc, asyncio.CancelledError) else "failed", phase="cancelled" if isinstance(exc, asyncio.CancelledError) else "failed",
notify=notify,
), ),
) )
raise raise
if not summary: if not summary:
await events.emit( await events.emit(
ContextCompactionEvent(compaction_id=compaction_id, phase="failed"), ContextCompactionEvent(compaction_id=compaction_id, phase="failed", notify=notify),
) )
return None return None
@@ -1301,6 +1303,7 @@ class Consolidator:
ContextCompactionEvent( ContextCompactionEvent(
compaction_id=compaction_id, compaction_id=compaction_id,
phase="succeeded", phase="succeeded",
notify=notify,
), ),
) )
+6 -1
View File
@@ -67,7 +67,12 @@ def _bind_events(
) )
async def publish(event: AgentEvent) -> None: async def publish(event: AgentEvent) -> None:
if not accepts(type(event)): # A maintenance result destination does not own the internal context.
if is_internal_session(session_key) and isinstance(event, ContextCompactionEvent):
return
if not notification_is_deliverable(
event, channel=channel, publish_lifecycle=route.publish_lifecycle,
):
return return
await bus.publish_event( await bus.publish_event(
event, channel=channel, chat_id=chat_id, metadata=deepcopy(metadata), event, channel=channel, chat_id=chat_id, metadata=deepcopy(metadata),
+2 -1
View File
@@ -33,9 +33,10 @@ NOTIFICATION_AUDIENCES: dict[type[AgentEvent], NotificationAudience] = {
def notification_is_deliverable( def notification_is_deliverable(
event_type: type[AgentEvent], *, channel: str, publish_lifecycle: bool, event: AgentEvent | type[AgentEvent], *, channel: str, publish_lifecycle: bool,
) -> bool: ) -> bool:
"""Admit operation notifications to a channel only by explicit policy.""" """Admit operation notifications to a channel only by explicit policy."""
event_type = event if isinstance(event, type) else type(event)
audience = NOTIFICATION_AUDIENCES.get(event_type) audience = NOTIFICATION_AUDIENCES.get(event_type)
if audience is None: if audience is None:
return False return False
+3
View File
@@ -21,6 +21,7 @@ from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel from nanobot.channels.base import BaseChannel
from nanobot.config.schema import Base from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
from nanobot.security.network import validate_resolved_url, validate_url_target from nanobot.security.network import validate_resolved_url, validate_url_target
DINGTALK_MAX_REMOTE_MEDIA_BYTES = 20 * 1024 * 1024 DINGTALK_MAX_REMOTE_MEDIA_BYTES = 20 * 1024 * 1024
@@ -735,6 +736,8 @@ class DingTalkChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
"""Send a message through DingTalk.""" """Send a message through DingTalk."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
token = await self._get_access_token() token = await self._get_access_token()
if not token: if not token:
raise RuntimeError("DingTalk access token unavailable") raise RuntimeError("DingTalk access token unavailable")
+2
View File
@@ -261,6 +261,8 @@ if DISCORD_AVAILABLE:
async def send_outbound(self, msg: OutboundMessage) -> None: async def send_outbound(self, msg: OutboundMessage) -> None:
"""Send a nanobot outbound message using Discord transport rules.""" """Send a nanobot outbound message using Discord transport rules."""
compaction = msg.event if isinstance(msg.event, ContextCompactionEvent) else None compaction = msg.event if isinstance(msg.event, ContextCompactionEvent) else None
if compaction is not None and not compaction.notify:
return
# A compaction's outcome replaces its own start notice in place, so # A compaction's outcome replaces its own start notice in place, so
# the lifecycle stays visible as one message instead of two (#5719). # the lifecycle stays visible as one message instead of two (#5719).
# Without a stored notice (restart, edit refused) it is sent as usual. # Without a stored notice (restart, edit refused) it is sent as usual.
@@ -1787,7 +1787,9 @@ def _compaction_message(
channel="discord", channel="discord",
chat_id=chat_id, chat_id=chat_id,
content=content, content=content,
event=ContextCompactionEvent(compaction_id=compaction_id, phase=phase), # type: ignore[arg-type] event=ContextCompactionEvent(
compaction_id=compaction_id, phase=phase, notify=True,
), # type: ignore[arg-type]
) )
@@ -1822,6 +1824,19 @@ async def test_compaction_outcome_edits_the_start_notice_in_place() -> None:
assert owner._compaction_notices == {} assert owner._compaction_notices == {}
@pytest.mark.asyncio
async def test_automatic_compaction_is_received_but_not_sent() -> None:
target = _FakeChannel(channel_id=123)
_owner, client = _client_with_channel(target)
await client.send_outbound(OutboundMessage(
channel="discord", chat_id="123", content="Compressing context…",
event=ContextCompactionEvent(compaction_id="c1", phase="started"),
))
assert target.sent_payloads == []
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_compaction_outcome_without_a_start_notice_is_sent() -> None: 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. # After a restart (or when the edit is refused) the outcome still arrives.
+3
View File
@@ -29,6 +29,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_media_dir from nanobot.config.paths import get_media_dir
from nanobot.config.schema import Base from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
from nanobot.utils.helpers import safe_filename from nanobot.utils.helpers import safe_filename
@@ -239,6 +240,8 @@ class EmailChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
"""Send email via SMTP.""" """Send email via SMTP."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if not self.config.consent_granted: if not self.config.consent_granted:
self.logger.warning("Skip email send: consent_granted is false") self.logger.warning("Skip email send: consent_granted is false")
return return
+3
View File
@@ -42,6 +42,7 @@ from nanobot.channels.feishu.instances import (
from nanobot.channels.feishu.websocket import get_feishu_ws_runner from nanobot.channels.feishu.websocket import get_feishu_ws_runner
from nanobot.command.router import normalize_command_text from nanobot.command.router import normalize_command_text
from nanobot.config.paths import get_media_dir from nanobot.config.paths import get_media_dir
from nanobot.events import ContextCompactionEvent
from nanobot.pairing import clear_channel from nanobot.pairing import clear_channel
from nanobot.utils.helpers import safe_filename from nanobot.utils.helpers import safe_filename
from nanobot.utils.logging_bridge import redirect_lib_logging from nanobot.utils.logging_bridge import redirect_lib_logging
@@ -2440,6 +2441,8 @@ class FeishuChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
"""Send a message through Feishu, including media (images/files) if present.""" """Send a message through Feishu, including media (images/files) if present."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if not self._client: if not self._client:
self.logger.warning("client not initialized") self.logger.warning("client not initialized")
return return
+2
View File
@@ -130,6 +130,8 @@ class LinearChannel(BaseChannel):
if isinstance(event, ContextCompactionEvent): if isinstance(event, ContextCompactionEvent):
if event.phase == "succeeded": if event.phase == "succeeded":
self._issue_contexts.pop(msg.chat_id, None) self._issue_contexts.pop(msg.chat_id, None)
if not event.notify:
return
# Idle notifications have no originating Linear turn. Sending a thought # Idle notifications have no originating Linear turn. Sending a thought
# through the cached route would reactivate an already completed session. # through the cached route would reactivate an already completed session.
if _linear_route(msg.metadata) is None: if _linear_route(msg.metadata) is None:
+5 -3
View File
@@ -815,7 +815,7 @@ async def test_compaction_restores_issue_context_on_next_message(
await channel.send(outbound_message_for_event( await channel.send(outbound_message_for_event(
channel="linear", chat_id=inbound.chat_id, channel="linear", chat_id=inbound.chat_id,
metadata={} if idle else inbound.metadata, metadata={} if idle else inbound.metadata,
event=ContextCompactionEvent(compaction_id="compact", phase=phase), event=ContextCompactionEvent(compaction_id="compact", phase=phase, notify=True),
)) ))
for delivery, include_context in (("after", phase == "succeeded"), ("again", False)): for delivery, include_context in (("after", phase == "succeeded"), ("again", False)):
await channel._process_webhook(delivery, followup) # pyright: ignore[reportPrivateUsage] await channel._process_webhook(delivery, followup) # pyright: ignore[reportPrivateUsage]
@@ -1211,7 +1211,9 @@ async def test_compaction_uses_temporary_progress_and_a_persistent_outcome(
channel="linear", channel="linear",
chat_id="session-1", chat_id="session-1",
metadata=metadata, metadata=metadata,
event=ContextCompactionEvent(compaction_id="compaction-1", phase="started"), event=ContextCompactionEvent(
compaction_id="compaction-1", phase="started", notify=True,
),
)) ))
assert client.activities[0]["content"] == { assert client.activities[0]["content"] == {
"type": "thought", "body": "Compressing context\u2026", "type": "thought", "body": "Compressing context\u2026",
@@ -1222,7 +1224,7 @@ async def test_compaction_uses_temporary_progress_and_a_persistent_outcome(
channel="linear", channel="linear",
chat_id="session-1", chat_id="session-1",
metadata=metadata, metadata=metadata,
event=ContextCompactionEvent(compaction_id="compaction-1", phase=phase), event=ContextCompactionEvent(compaction_id="compaction-1", phase=phase, notify=True),
) )
await channel.send(outcome) await channel.send(outcome)
assert client.activities[-1]["content"] == {"type": "thought", "body": outcome.content} assert client.activities[-1]["content"] == {"type": "thought", "body": outcome.content}
+3
View File
@@ -64,6 +64,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_data_dir, get_media_dir from nanobot.config.paths import get_data_dir, get_media_dir
from nanobot.config.schema import Base from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
from nanobot.utils.helpers import safe_filename from nanobot.utils.helpers import safe_filename
from nanobot.utils.logging_bridge import redirect_lib_logging from nanobot.utils.logging_bridge import redirect_lib_logging
@@ -615,6 +616,8 @@ class MatrixChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
"""Send outbound content; clear typing for non-progress messages.""" """Send outbound content; clear typing for non-progress messages."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if not self.client: if not self.client:
raise RuntimeError("Matrix client not initialized") raise RuntimeError("Matrix client not initialized")
text = msg.content or "" text = msg.content or ""
+3
View File
@@ -16,6 +16,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_media_dir from nanobot.config.paths import get_media_dir
from nanobot.config_base import Base from nanobot.config_base import Base
from nanobot.events import ContextCompactionEvent
from nanobot.pairing import PAIRING_CODE_META_KEY, format_pairing_reply, generate_code, is_approved from nanobot.pairing import PAIRING_CODE_META_KEY, format_pairing_reply, generate_code, is_approved
from nanobot.utils.helpers import safe_filename, split_message from nanobot.utils.helpers import safe_filename, split_message
@@ -492,6 +493,8 @@ class MattermostChannel(BaseChannel):
# Send --------------------------------------------------------------------- # Send ---------------------------------------------------------------------
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if not self._http_client: if not self._http_client:
self.logger.warning("client not initialized") self.logger.warning("client not initialized")
return return
+3
View File
@@ -20,6 +20,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_runtime_subdir from nanobot.config.paths import get_runtime_subdir
from nanobot.config.schema import Base from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
try: try:
import socketio import socketio
@@ -350,6 +351,8 @@ class MochatChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
"""Send outbound message to session or panel.""" """Send outbound message to session or panel."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if not self.config.claw_token: if not self.config.claw_token:
self.logger.warning("claw_token missing, skip send") self.logger.warning("claw_token missing, skip send")
return return
+3
View File
@@ -40,6 +40,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_workspace_path from nanobot.config.paths import get_workspace_path
from nanobot.config.schema import Base from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
MSTEAMS_AVAILABLE = ( MSTEAMS_AVAILABLE = (
importlib.util.find_spec("jwt") is not None importlib.util.find_spec("jwt") is not None
@@ -250,6 +251,8 @@ class MSTeamsChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
"""Send a plain text reply into an existing Teams conversation.""" """Send a plain text reply into an existing Teams conversation."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if not self._http: if not self._http:
raise RuntimeError("MSTeams HTTP client not initialized") raise RuntimeError("MSTeams HTTP client not initialized")
+3
View File
@@ -24,6 +24,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_media_dir from nanobot.config.paths import get_media_dir
from nanobot.config.schema import Base from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
from nanobot.security.network import validate_url_target from nanobot.security.network import validate_url_target
from nanobot.utils.helpers import safe_filename from nanobot.utils.helpers import safe_filename
@@ -437,6 +438,8 @@ class NapcatChannel(BaseChannel):
# ------------------------------------------------------------------ # ------------------------------------------------------------------
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if self._ws is None: if self._ws is None:
raise RuntimeError("napcat: not connected") raise RuntimeError("napcat: not connected")
+1 -1
View File
@@ -311,7 +311,7 @@ class QQChannel(BaseChannel):
# (#5784); showCompactionNotices: true restores them. # (#5784); showCompactionNotices: true restores them.
if ( if (
isinstance(msg.event, ContextCompactionEvent) isinstance(msg.event, ContextCompactionEvent)
and not self.config.show_compaction_notices and (not msg.event.notify or not self.config.show_compaction_notices)
): ):
return return
+3
View File
@@ -23,6 +23,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_media_dir from nanobot.config.paths import get_media_dir
from nanobot.config.schema import Base from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
from nanobot.pairing import is_approved from nanobot.pairing import is_approved
from nanobot.utils.helpers import safe_filename, split_message from nanobot.utils.helpers import safe_filename, split_message
@@ -564,6 +565,8 @@ class SignalChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
"""Send a message through Signal.""" """Send a message through Signal."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
is_progress_message = isinstance(msg.event, ProgressEvent) is_progress_message = isinstance(msg.event, ProgressEvent)
try: try:
plain_text, text_styles = _markdown_to_signal(msg.content) plain_text, text_styles = _markdown_to_signal(msg.content)
+3
View File
@@ -20,6 +20,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_media_dir from nanobot.config.paths import get_media_dir
from nanobot.config.schema import Base from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
from nanobot.pairing import is_approved from nanobot.pairing import is_approved
from nanobot.security.network import ( from nanobot.security.network import (
PinnedDNSAsyncTransport, PinnedDNSAsyncTransport,
@@ -201,6 +202,8 @@ class SlackChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
"""Send a message through Slack.""" """Send a message through Slack."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if not self._web_client: if not self._web_client:
self.logger.warning("client not running") self.logger.warning("client not running")
return return
+2
View File
@@ -1096,6 +1096,8 @@ class TelegramChannel(BaseChannel):
# Compaction notices collapse into one message: the started phase sends # Compaction notices collapse into one message: the started phase sends
# it, a terminal phase edits it in place instead of posting a new one. # it, a terminal phase edits it in place instead of posting a new one.
if isinstance(msg.event, ContextCompactionEvent): if isinstance(msg.event, ContextCompactionEvent):
if not msg.event.notify:
return
await self._send_compaction_notice( await self._send_compaction_notice(
chat_id, msg, msg.event, reply_params, thread_kwargs, chat_id, msg, msg.event, reply_params, thread_kwargs,
) )
@@ -3267,7 +3267,7 @@ def _compaction_message(phase: str, compaction_id: str = "c1") -> OutboundMessag
"failed": "Unable to compact context.", "failed": "Unable to compact context.",
"cancelled": "Context compaction cancelled.", "cancelled": "Context compaction cancelled.",
}[phase], }[phase],
event=ContextCompactionEvent(compaction_id=compaction_id, phase=phase), event=ContextCompactionEvent(compaction_id=compaction_id, phase=phase, notify=True),
) )
@@ -3297,6 +3297,23 @@ async def test_compaction_terminal_phase_edits_started_notice_in_place() -> None
assert ("999", "c1") not in channel._compaction_notices assert ("999", "c1") not in channel._compaction_notices
@pytest.mark.asyncio
async def test_automatic_compaction_is_received_but_not_sent() -> None:
channel = TelegramChannel(
TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]),
MessageBus(),
)
_install_ready_app(channel)
channel._app.bot.send_message = AsyncMock()
await channel.send(OutboundMessage(
channel="telegram", chat_id="999", content="Compressing context…",
event=ContextCompactionEvent(compaction_id="c1", phase="started"),
))
channel._app.bot.send_message.assert_not_awaited()
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_compaction_edit_failure_falls_back_to_new_message() -> None: async def test_compaction_edit_failure_falls_back_to_new_message() -> None:
from telegram.error import BadRequest from telegram.error import BadRequest
+3
View File
@@ -18,6 +18,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_media_dir from nanobot.config.paths import get_media_dir
from nanobot.config.schema import Base from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
WECOM_AVAILABLE = importlib.util.find_spec("wecom_aibot_sdk") is not None WECOM_AVAILABLE = importlib.util.find_spec("wecom_aibot_sdk") is not None
WECOM_WEBSOCKET_HOST = "openws.work.weixin.qq.com" WECOM_WEBSOCKET_HOST = "openws.work.weixin.qq.com"
@@ -410,6 +411,8 @@ class WecomChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
"""Send a message through WeCom.""" """Send a message through WeCom."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if not self._client: if not self._client:
raise RuntimeError("WeCom client not initialized") raise RuntimeError("WeCom client not initialized")
+4 -1
View File
@@ -38,6 +38,7 @@ from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_media_dir, get_runtime_subdir from nanobot.config.paths import get_media_dir, get_runtime_subdir
from nanobot.config.schema import Base from nanobot.config.schema import Base
from nanobot.utils.logging_bridge import redirect_lib_logging from nanobot.utils.logging_bridge import redirect_lib_logging
from nanobot.events import ContextCompactionEvent
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Protocol constants (from openclaw-weixin types.ts) # Protocol constants (from openclaw-weixin types.ts)
@@ -1883,13 +1884,15 @@ class WeixinChannel(BaseChannel):
self._record_context_send(context_token) self._record_context_send(context_token)
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
event = getattr(msg, "event", None)
if isinstance(event, ContextCompactionEvent) and not event.notify:
return
if not self._client or not self._token: if not self._client or not self._token:
raise RuntimeError("WeChat client not initialized or not authenticated") raise RuntimeError("WeChat client not initialized or not authenticated")
self._assert_session_active() self._assert_session_active()
delivery_id = self._delivery_id(msg) delivery_id = self._delivery_id(msg)
delivery_state = self._delivery_state(delivery_id) delivery_state = self._delivery_state(delivery_id)
event = getattr(msg, "event", None)
progress_event = event if isinstance(event, ProgressEvent) else None progress_event = event if isinstance(event, ProgressEvent) else None
is_progress = progress_event is not None is_progress = progress_event is not None
+3
View File
@@ -23,6 +23,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_media_dir, get_runtime_subdir from nanobot.config.paths import get_media_dir, get_runtime_subdir
from nanobot.config.schema import Base from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
from nanobot.security.network import PinnedDNSAsyncTransport from nanobot.security.network import PinnedDNSAsyncTransport
@@ -459,6 +460,8 @@ class WhatsAppChannel(BaseChannel):
connect_task.add_done_callback(_on_done) connect_task.add_done_callback(_on_done)
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
client = self._client client = self._client
if client is None or not self._connected: if client is None or not self._connected:
raise RuntimeError("WhatsApp channel is not connected") raise RuntimeError("WhatsApp channel is not connected")
+1
View File
@@ -358,6 +358,7 @@ async def cmd_compact(ctx: CommandContext) -> None:
ctx.key, ctx.key,
runtime=runtime, runtime=runtime,
events=delivery.events, events=delivery.events,
notify=True,
) )
except Exception: except Exception:
logger.exception("Manual context compaction failed for {}", ctx.key) logger.exception("Manual context compaction failed for {}", ctx.key)
+1
View File
@@ -37,6 +37,7 @@ class ResponseSourceEvent(AgentEvent):
class ContextCompactionEvent(AgentEvent): class ContextCompactionEvent(AgentEvent):
compaction_id: str compaction_id: str
phase: Literal["started", "succeeded", "failed", "cancelled"] phase: Literal["started", "succeeded", "failed", "cancelled"]
notify: bool = False
@dataclass(frozen=True) @dataclass(frozen=True)
+2
View File
@@ -696,11 +696,13 @@ class TestCompactIdleSession:
"cli:events", "cli:events",
runtime=runtime, runtime=runtime,
events=EventSink(observe), events=EventSink(observe),
notify=True,
) )
assert result == "Summary." assert result == "Summary."
assert [event.phase for event in events] == ["started", "succeeded"] assert [event.phase for event in events] == ["started", "succeeded"]
assert events[0].compaction_id == events[1].compaction_id assert events[0].compaction_id == events[1].compaction_id
assert all(event.notify for event in events)
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_event_callback_failure_does_not_abort_compaction( async def test_event_callback_failure_does_not_abort_compaction(
+16 -11
View File
@@ -59,11 +59,14 @@ async def test_internal_compaction_never_reaches_its_result_destination(channel,
{"message_id": "reply", "thread_id": "root", "chat_type": "group"}), {"message_id": "reply", "thread_id": "root", "chat_type": "group"}),
("dingtalk:group:conversation:user", "dingtalk", "group:conversation", {}), ("dingtalk:group:conversation:user", "dingtalk", "group:conversation", {}),
]) ])
async def test_idle_compaction_uses_the_session_delivery_route( async def test_session_route_delivers_automatic_and_manual_compaction(
key, channel, chat_id, metadata, unified, key, channel, chat_id, metadata, unified,
) -> None: ) -> None:
factory = TurnDeliveryFactory(MessageBus()) factory = TurnDeliveryFactory(MessageBus())
event = ContextCompactionEvent(compaction_id="compact-1", phase="started") automatic = ContextCompactionEvent(compaction_id="auto-1", phase="started")
notified = ContextCompactionEvent(
compaction_id="notified-1", phase="started", notify=True,
)
key = "unified:default" if unified else key key = "unified:default" if unified else key
msg = InboundMessage( msg = InboundMessage(
channel=channel, sender_id="user", chat_id=chat_id, content="hello", channel=channel, sender_id="user", chat_id=chat_id, content="hello",
@@ -78,11 +81,14 @@ async def test_idle_compaction_uses_the_session_delivery_route(
sink = factory.session_events(key, session_metadata) sink = factory.session_events(key, session_metadata)
assert sink.publish is not None assert sink.publish is not None
await sink.emit(event) await sink.emit(automatic)
await sink.emit(notified)
outbound = factory.bus.outbound.get_nowait() outbounds = [factory.bus.outbound.get_nowait() for _ in range(2)]
assert (outbound.channel, outbound.chat_id, outbound.metadata) == (channel, chat_id, metadata) assert [(outbound.channel, outbound.chat_id, outbound.metadata) for outbound in outbounds] == [
assert outbound.event is event (channel, chat_id, metadata),
] * 2
assert [outbound.event for outbound in outbounds] == [automatic, notified]
async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() -> None: async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() -> None:
@@ -96,13 +102,13 @@ async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() ->
factory.create(original, key).remember_session_route(session_metadata) factory.create(original, key).remember_session_route(session_metadata)
sink = factory.session_events(key, session_metadata) sink = factory.session_events(key, session_metadata)
assert sink.publish is not None assert sink.publish is not None
await sink.emit(ContextCompactionEvent("compact-1", "started")) await sink.emit(ContextCompactionEvent("compact-1", "started", notify=True))
latest = InboundMessage( latest = InboundMessage(
channel="telegram", sender_id="user", chat_id="42", content="next question", channel="telegram", sender_id="user", chat_id="42", content="next question",
) )
factory.create(latest, key).remember_session_route(session_metadata) factory.create(latest, key).remember_session_route(session_metadata)
await sink.emit(ContextCompactionEvent("compact-1", "succeeded")) await sink.emit(ContextCompactionEvent("compact-1", "succeeded", notify=True))
events = [factory.bus.outbound.get_nowait() for _ in range(2)] events = [factory.bus.outbound.get_nowait() for _ in range(2)]
assert [(msg.channel, msg.chat_id, msg.metadata) for msg in events] == [ assert [(msg.channel, msg.chat_id, msg.metadata) for msg in events] == [
@@ -110,14 +116,13 @@ async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() ->
] * 2 ] * 2
async def test_idle_compaction_can_deliver_to_a_legacy_websocket_session() -> None: async def test_automatic_compaction_reaches_legacy_websocket_session() -> None:
factory = TurnDeliveryFactory(MessageBus()) factory = TurnDeliveryFactory(MessageBus())
event = ContextCompactionEvent(compaction_id="compact-1", phase="succeeded") event = ContextCompactionEvent(compaction_id="compact-1", phase="succeeded")
sink = factory.session_events("websocket:chat", {}) sink = factory.session_events("websocket:chat", {})
assert sink.publish is not None assert sink.publish is not None
await sink.emit(event) await sink.emit(event)
outbound = factory.bus.outbound.get_nowait() assert factory.bus.outbound.get_nowait().event is event
assert (outbound.channel, outbound.chat_id, outbound.event) == ("websocket", "chat", event)
@pytest.mark.asyncio @pytest.mark.asyncio
+22 -3
View File
@@ -80,7 +80,9 @@ async def test_output_consumer_capability_survives_callback_adaptation():
await events.emit(ProgressEvent(content="working")) await events.emit(ProgressEvent(content="working"))
await events.emit(ContextCompactionEvent("compact", "succeeded")) await events.emit(ContextCompactionEvent("compact", "succeeded"))
assert received == ["working"] assert received == ["working"]
assert bus.outbound.get_nowait().event == ContextCompactionEvent("compact", "succeeded") assert bus.outbound.get_nowait().event == ContextCompactionEvent(
"compact", "succeeded",
)
async def test_scope_snapshots_route_and_queues_events_in_order(): async def test_scope_snapshots_route_and_queues_events_in_order():
@@ -123,7 +125,7 @@ async def test_new_internal_event_needs_explicit_audience(monkeypatch):
assert project_notification("chat", event) is None assert project_notification("chat", event) is None
async def test_background_scope_keeps_retry_quiet_but_delivers_compaction(): async def test_background_scope_keeps_retry_quiet_and_delivers_compaction():
bus = MessageBus() bus = MessageBus()
factory = TurnDeliveryFactory(bus, factory = TurnDeliveryFactory(bus,
lambda *_: TurnRoute("websocket", "chat")) lambda *_: TurnRoute("websocket", "chat"))
@@ -137,6 +139,21 @@ async def test_background_scope_keeps_retry_quiet_but_delivers_compaction():
assert bus.outbound.get_nowait().event is event assert bus.outbound.get_nowait().event is event
@pytest.mark.parametrize("channel", ["websocket", "cli", "slack", "custom"])
async def test_automatic_and_manual_compaction_are_delivered_to_channels(channel):
bus = MessageBus()
delivery = TurnDeliveryFactory(bus).create(InboundMessage(
channel=channel, sender_id="u", chat_id="chat", content="",
), f"{channel}:chat")
await delivery.events.emit(ContextCompactionEvent("auto", "succeeded"))
assert bus.outbound.get_nowait().event == ContextCompactionEvent("auto", "succeeded")
event = ContextCompactionEvent("notified", "succeeded", notify=True)
await delivery.events.emit(event)
assert bus.outbound.get_nowait().event is event
@pytest.mark.parametrize("channel", ["websocket", "cli", "slack", "custom"]) @pytest.mark.parametrize("channel", ["websocket", "cli", "slack", "custom"])
async def test_bus_routes_arbitrary_events_and_text_through_one_queue(channel): async def test_bus_routes_arbitrary_events_and_text_through_one_queue(channel):
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -168,7 +185,9 @@ async def test_bus_event_preserves_existing_text_fallback():
@pytest.mark.parametrize("phase", ["started", "succeeded", "failed", "cancelled"]) @pytest.mark.parametrize("phase", ["started", "succeeded", "failed", "cancelled"])
def test_compaction_durability_is_independent_of_subscribers(phase): def test_compaction_durability_is_independent_of_subscribers(phase):
projection = project_notification("chat", ContextCompactionEvent("c1", phase)) projection = project_notification(
"chat", ContextCompactionEvent("c1", phase),
)
assert projection is not None assert projection is not None
assert projection.deliver_offline assert projection.deliver_offline
assert projection.attach_turn_metadata assert projection.attach_turn_metadata
@@ -1,11 +1,4 @@
"""Context-compaction lifecycle notices are delivered regardless of ``send_progress``. """Channel transports decide whether to render compaction lifecycle events."""
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 from __future__ import annotations
@@ -40,6 +33,8 @@ class _MockChannel(BaseChannel):
pass pass
async def send(self, msg): async def send(self, msg):
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
return await self._send_mock(msg) return await self._send_mock(msg)
@@ -71,12 +66,18 @@ def _sent_contents(manager: ChannelManager) -> list[str]:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_compaction_lifecycle_is_delivered_with_progress_off(manager: ChannelManager) -> None: async def test_channel_receives_automatic_compaction_but_does_not_render_it(
manager: ChannelManager,
) -> None:
manager.channels["mock"].send_progress = False manager.channels["mock"].send_progress = False
for event in ( for event in (
ProgressEvent(content="ordinary progress"), ProgressEvent(content="ordinary progress"),
ContextCompactionEvent(compaction_id="c1", phase="started"), ContextCompactionEvent(compaction_id="auto", phase="started"),
ContextCompactionEvent(compaction_id="c1", phase="succeeded"), ContextCompactionEvent(compaction_id="auto", phase="succeeded"),
ContextCompactionEvent(compaction_id="auto-failed", phase="failed"),
ContextCompactionEvent(compaction_id="auto-cancelled", phase="cancelled"),
ContextCompactionEvent(compaction_id="c1", phase="started", notify=True),
ContextCompactionEvent(compaction_id="c1", phase="succeeded", notify=True),
): ):
await manager.bus.publish_outbound( await manager.bus.publish_outbound(
outbound_message_for_event(channel="mock", chat_id="chat", event=event) outbound_message_for_event(channel="mock", chat_id="chat", event=event)
@@ -86,4 +87,4 @@ async def test_compaction_lifecycle_is_delivered_with_progress_off(manager: Chan
contents = _sent_contents(manager) contents = _sent_contents(manager)
assert "ordinary progress" not in contents assert "ordinary progress" not in contents
assert len(contents) == 2 assert contents == ["Compressing context…", "Context compacted."]
+1 -1
View File
@@ -50,7 +50,7 @@ async def test_compaction_notices_sent_when_enabled(monkeypatch) -> None:
await channel.send(outbound_message_for_event( await channel.send(outbound_message_for_event(
channel="qq", chat_id="chat", channel="qq", chat_id="chat",
event=ContextCompactionEvent(compaction_id="c1", phase="started"), event=ContextCompactionEvent(compaction_id="c1", phase="started", notify=True),
)) ))
send_text.assert_awaited_once() send_text.assert_awaited_once()
+2
View File
@@ -71,6 +71,8 @@ async def test_compact_emits_one_lifecycle_and_keeps_the_session(loop, command)
assert started.phase == "started" assert started.phase == "started"
assert completed.phase == "succeeded" assert completed.phase == "succeeded"
assert started.compaction_id == completed.compaction_id assert started.compaction_id == completed.compaction_id
assert started.notify is True
assert completed.notify is True
loop.sessions.invalidate("cli:test") loop.sessions.invalidate("cli:test")
reloaded = loop.sessions.get_or_create("cli:test") reloaded = loop.sessions.get_or_create("cli:test")