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,
max_suffix: int = 0,
events: EventSink = NO_EVENTS,
notify: bool = False,
) -> str | None:
"""Replace archived history with a summary checkpoint.
@@ -1267,7 +1268,7 @@ class Consolidator:
compaction_id = uuid4().hex
await events.emit(
ContextCompactionEvent(compaction_id=compaction_id, phase="started"),
ContextCompactionEvent(compaction_id=compaction_id, phase="started", notify=notify),
)
last_active = session.updated_at
archive_end = archive_start + len(messages_to_archive)
@@ -1288,12 +1289,13 @@ class Consolidator:
ContextCompactionEvent(
compaction_id=compaction_id,
phase="cancelled" if isinstance(exc, asyncio.CancelledError) else "failed",
notify=notify,
),
)
raise
if not summary:
await events.emit(
ContextCompactionEvent(compaction_id=compaction_id, phase="failed"),
ContextCompactionEvent(compaction_id=compaction_id, phase="failed", notify=notify),
)
return None
@@ -1301,6 +1303,7 @@ class Consolidator:
ContextCompactionEvent(
compaction_id=compaction_id,
phase="succeeded",
notify=notify,
),
)
+6 -1
View File
@@ -67,7 +67,12 @@ def _bind_events(
)
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
await bus.publish_event(
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(
event_type: type[AgentEvent], *, channel: str, publish_lifecycle: bool,
event: AgentEvent | type[AgentEvent], *, channel: str, publish_lifecycle: bool,
) -> bool:
"""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)
if audience is None:
return False
+3
View File
@@ -21,6 +21,7 @@ from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
from nanobot.security.network import validate_resolved_url, validate_url_target
DINGTALK_MAX_REMOTE_MEDIA_BYTES = 20 * 1024 * 1024
@@ -735,6 +736,8 @@ class DingTalkChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
"""Send a message through DingTalk."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
token = await self._get_access_token()
if not token:
raise RuntimeError("DingTalk access token unavailable")
+2
View File
@@ -261,6 +261,8 @@ 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
if compaction is not None and not compaction.notify:
return
# 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.
@@ -1787,7 +1787,9 @@ def _compaction_message(
channel="discord",
chat_id=chat_id,
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 == {}
@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
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.
+3
View File
@@ -29,6 +29,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_media_dir
from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
from nanobot.utils.helpers import safe_filename
@@ -239,6 +240,8 @@ class EmailChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
"""Send email via SMTP."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if not self.config.consent_granted:
self.logger.warning("Skip email send: consent_granted is false")
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.command.router import normalize_command_text
from nanobot.config.paths import get_media_dir
from nanobot.events import ContextCompactionEvent
from nanobot.pairing import clear_channel
from nanobot.utils.helpers import safe_filename
from nanobot.utils.logging_bridge import redirect_lib_logging
@@ -2440,6 +2441,8 @@ class FeishuChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
"""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:
self.logger.warning("client not initialized")
return
+2
View File
@@ -130,6 +130,8 @@ class LinearChannel(BaseChannel):
if isinstance(event, ContextCompactionEvent):
if event.phase == "succeeded":
self._issue_contexts.pop(msg.chat_id, None)
if not event.notify:
return
# Idle notifications have no originating Linear turn. Sending a thought
# through the cached route would reactivate an already completed session.
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(
channel="linear", chat_id=inbound.chat_id,
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)):
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",
chat_id="session-1",
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"] == {
"type": "thought", "body": "Compressing context\u2026",
@@ -1222,7 +1224,7 @@ async def test_compaction_uses_temporary_progress_and_a_persistent_outcome(
channel="linear",
chat_id="session-1",
metadata=metadata,
event=ContextCompactionEvent(compaction_id="compaction-1", phase=phase),
event=ContextCompactionEvent(compaction_id="compaction-1", phase=phase, notify=True),
)
await channel.send(outcome)
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.config.paths import get_data_dir, get_media_dir
from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
from nanobot.utils.helpers import safe_filename
from nanobot.utils.logging_bridge import redirect_lib_logging
@@ -615,6 +616,8 @@ class MatrixChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
"""Send outbound content; clear typing for non-progress messages."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if not self.client:
raise RuntimeError("Matrix client not initialized")
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.config.paths import get_media_dir
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.utils.helpers import safe_filename, split_message
@@ -492,6 +493,8 @@ class MattermostChannel(BaseChannel):
# Send ---------------------------------------------------------------------
async def send(self, msg: OutboundMessage) -> None:
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if not self._http_client:
self.logger.warning("client not initialized")
return
+3
View File
@@ -20,6 +20,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_runtime_subdir
from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
try:
import socketio
@@ -350,6 +351,8 @@ class MochatChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
"""Send outbound message to session or panel."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if not self.config.claw_token:
self.logger.warning("claw_token missing, skip send")
return
+3
View File
@@ -40,6 +40,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_workspace_path
from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
MSTEAMS_AVAILABLE = (
importlib.util.find_spec("jwt") is not None
@@ -250,6 +251,8 @@ class MSTeamsChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
"""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:
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.config.paths import get_media_dir
from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
from nanobot.security.network import validate_url_target
from nanobot.utils.helpers import safe_filename
@@ -437,6 +438,8 @@ class NapcatChannel(BaseChannel):
# ------------------------------------------------------------------
async def send(self, msg: OutboundMessage) -> None:
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if self._ws is None:
raise RuntimeError("napcat: not connected")
+1 -1
View File
@@ -311,7 +311,7 @@ class QQChannel(BaseChannel):
# (#5784); showCompactionNotices: true restores them.
if (
isinstance(msg.event, ContextCompactionEvent)
and not self.config.show_compaction_notices
and (not msg.event.notify or not self.config.show_compaction_notices)
):
return
+3
View File
@@ -23,6 +23,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_media_dir
from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
from nanobot.pairing import is_approved
from nanobot.utils.helpers import safe_filename, split_message
@@ -564,6 +565,8 @@ class SignalChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
"""Send a message through Signal."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
is_progress_message = isinstance(msg.event, ProgressEvent)
try:
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.config.paths import get_media_dir
from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
from nanobot.pairing import is_approved
from nanobot.security.network import (
PinnedDNSAsyncTransport,
@@ -201,6 +202,8 @@ class SlackChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
"""Send a message through Slack."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if not self._web_client:
self.logger.warning("client not running")
return
+2
View File
@@ -1096,6 +1096,8 @@ class TelegramChannel(BaseChannel):
# Compaction notices collapse into one message: the started phase sends
# it, a terminal phase edits it in place instead of posting a new one.
if isinstance(msg.event, ContextCompactionEvent):
if not msg.event.notify:
return
await self._send_compaction_notice(
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.",
"cancelled": "Context compaction cancelled.",
}[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
@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
async def test_compaction_edit_failure_falls_back_to_new_message() -> None:
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.config.paths import get_media_dir
from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
WECOM_AVAILABLE = importlib.util.find_spec("wecom_aibot_sdk") is not None
WECOM_WEBSOCKET_HOST = "openws.work.weixin.qq.com"
@@ -410,6 +411,8 @@ class WecomChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
"""Send a message through WeCom."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
if not self._client:
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.schema import Base
from nanobot.utils.logging_bridge import redirect_lib_logging
from nanobot.events import ContextCompactionEvent
# ---------------------------------------------------------------------------
# Protocol constants (from openclaw-weixin types.ts)
@@ -1883,13 +1884,15 @@ class WeixinChannel(BaseChannel):
self._record_context_send(context_token)
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:
raise RuntimeError("WeChat client not initialized or not authenticated")
self._assert_session_active()
delivery_id = self._delivery_id(msg)
delivery_state = self._delivery_state(delivery_id)
event = getattr(msg, "event", None)
progress_event = event if isinstance(event, ProgressEvent) else 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.config.paths import get_media_dir, get_runtime_subdir
from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
from nanobot.security.network import PinnedDNSAsyncTransport
@@ -459,6 +460,8 @@ class WhatsAppChannel(BaseChannel):
connect_task.add_done_callback(_on_done)
async def send(self, msg: OutboundMessage) -> None:
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
client = self._client
if client is None or not self._connected:
raise RuntimeError("WhatsApp channel is not connected")
+1
View File
@@ -358,6 +358,7 @@ async def cmd_compact(ctx: CommandContext) -> None:
ctx.key,
runtime=runtime,
events=delivery.events,
notify=True,
)
except Exception:
logger.exception("Manual context compaction failed for {}", ctx.key)
+1
View File
@@ -37,6 +37,7 @@ class ResponseSourceEvent(AgentEvent):
class ContextCompactionEvent(AgentEvent):
compaction_id: str
phase: Literal["started", "succeeded", "failed", "cancelled"]
notify: bool = False
@dataclass(frozen=True)