fix(channels): preserve explicit compaction feedback and silent delivery

This commit is contained in:
Xubin Ren committed 2026-09-30 13:44:42 +08:00
1 parent 0b402d0414
commit 7644d845b4
13 files changed
+96 -37

No files matched your search

+3 -1
View File
@@ -1655,7 +1655,9 @@ Normal tool workspace and media access rules still apply to attachment paths.
} }
``` ```
QQ `showCompactionNotices` defaults to `false`. It controls the context-compaction lifecycle notices ("Compressing context…" / "Context compacted."). Telegram, Discord and WebSocket present that lifecycle as one in-place-updated message or status, but QQ's C2C/group message API has no edit or recall endpoint, so each phase would land as a separate permanent message; the QQ channel therefore drops the notices by default (#5784). Set `channels.qq.showCompactionNotices: true` to post them anyway: Automatic context-compaction notices are quiet by default in the built-in chat channels, including WeCom, Telegram and Discord. Compaction still runs, and WebUI/TUI structured status and history remain available. Manual `/compact` keeps its start and outcome feedback, including failure or cancellation. `sendProgress` remains independent of this policy.
QQ `showCompactionNotices` defaults to `false`. Set `channels.qq.showCompactionNotices: true` to also post automatic compaction notices ("Compressing context…" / "Context compacted."). QQ's C2C/group message API has no edit or recall endpoint, so each phase lands as a separate permanent message. Manual `/compact` feedback is shown regardless of this setting:
```json ```json
{ {
+2
View File
@@ -33,6 +33,8 @@ When a conversation grows large, nanobot summarizes the conversation covered by
Compaction also runs after a configured period of inactivity, or when you send `/compact`. See [Auto Compact](./configuration.md#auto-compact) for idle timing and how to disable automatic idle compaction. Compaction also runs after a configured period of inactivity, or when you send `/compact`. See [Auto Compact](./configuration.md#auto-compact) for idle timing and how to disable automatic idle compaction.
Automatic compaction does not post lifecycle notices to built-in chat channels by default. This only silences chat messages: compaction still runs, and WebUI/TUI retain structured status and history. Manual `/compact` keeps its start and outcome feedback. QQ users can opt back into automatic notices with `channels.qq.showCompactionNotices: true`.
This file is: This file is:
- append-only - append-only
+1 -6
View File
@@ -67,12 +67,7 @@ def _bind_events(
) )
async def publish(event: AgentEvent) -> None: async def publish(event: AgentEvent) -> None:
# A maintenance result destination does not own the internal context. if not accepts(type(event)):
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),
+1 -2
View File
@@ -33,10 +33,9 @@ NOTIFICATION_AUDIENCES: dict[type[AgentEvent], NotificationAudience] = {
def notification_is_deliverable( def notification_is_deliverable(
event: AgentEvent | type[AgentEvent], *, channel: str, publish_lifecycle: bool, event_type: 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 -1
View File
@@ -798,10 +798,12 @@ async def test_followups_only_repeat_issue_context_when_it_changes(tmp_path: Pat
@pytest.mark.asyncio @pytest.mark.asyncio
@pytest.mark.parametrize("notify", [False, True])
@pytest.mark.parametrize("idle", [True, False]) @pytest.mark.parametrize("idle", [True, False])
@pytest.mark.parametrize("phase", ["succeeded", "failed", "cancelled"]) @pytest.mark.parametrize("phase", ["succeeded", "failed", "cancelled"])
async def test_compaction_restores_issue_context_on_next_message( async def test_compaction_restores_issue_context_on_next_message(
tmp_path: Path, idle: bool, phase: Literal["succeeded", "failed", "cancelled"], tmp_path: Path, idle: bool, phase: Literal["succeeded", "failed", "cancelled"],
notify: bool,
) -> None: ) -> None:
channel, _ = _runtime(tmp_path) channel, _ = _runtime(tmp_path)
payload = _agent_webhook() payload = _agent_webhook()
@@ -815,7 +817,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, notify=True), event=ContextCompactionEvent(compaction_id="compact", phase=phase, notify=notify),
)) ))
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]
+4 -4
View File
@@ -193,7 +193,7 @@ class QQConfig(Base):
download_chunk_size: int = 1024 * 256 # 256KB download_chunk_size: int = 1024 * 256 # 256KB
download_max_bytes: int = 1024 * 1024 * 200 # 200MB safety limit download_max_bytes: int = 1024 * 1024 * 200 # 200MB safety limit
# QQ's C2C/group message API has no edit or recall endpoint, so compaction # QQ's C2C/group message API has no edit or recall endpoint, so automatic
# notices would land as separate permanent messages (#5784). Off by default; # notices would land as separate permanent messages (#5784). Off by default;
# set showCompactionNotices: true to post them anyway. # set showCompactionNotices: true to post them anyway.
show_compaction_notices: bool = False show_compaction_notices: bool = False
@@ -307,11 +307,11 @@ class QQChannel(BaseChannel):
# Compaction notices assume the channel can update one message in place # Compaction notices assume the channel can update one message in place
# (Telegram/Discord edit their notice; WebSocket projects it as status). # (Telegram/Discord edit their notice; WebSocket projects it as status).
# QQ's C2C/group API has no edit or recall endpoint, so by default the # QQ's C2C/group API has no edit or recall endpoint, so by default the
# lifecycle is dropped here instead of posting two permanent messages # automatic lifecycle is quiet by default (#5784). Explicit opt-in
# (#5784); showCompactionNotices: true restores them. # restores it; manual /compact always retains its requested feedback.
if ( if (
isinstance(msg.event, ContextCompactionEvent) isinstance(msg.event, ContextCompactionEvent)
and (not msg.event.notify or not self.config.show_compaction_notices) and not (msg.event.notify or self.config.show_compaction_notices)
): ):
return return
+2 -2
View File
@@ -1058,6 +1058,8 @@ class TelegramChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
"""Send a message through Telegram.""" """Send a message through Telegram."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
return
app = await self._wait_for_app() app = await self._wait_for_app()
if app is None: if app is None:
self.logger.warning("bot not running") self.logger.warning("bot not running")
@@ -1096,8 +1098,6 @@ 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,
) )
@@ -2,7 +2,7 @@ import asyncio
from datetime import timedelta from datetime import timedelta
from pathlib import Path from pathlib import Path
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import AsyncMock from unittest.mock import AsyncMock, Mock
import pytest import pytest
@@ -3298,20 +3298,26 @@ async def test_compaction_terminal_phase_edits_started_notice_in_place() -> None
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_automatic_compaction_is_received_but_not_sent() -> None: @pytest.mark.parametrize("phase", ["started", "succeeded", "failed", "cancelled"])
async def test_automatic_compaction_is_received_but_not_sent(phase) -> None:
channel = TelegramChannel( channel = TelegramChannel(
TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]), TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]),
MessageBus(), MessageBus(),
) )
_install_ready_app(channel) _install_ready_app(channel)
channel._app.bot.send_message = AsyncMock() channel._app.bot.send_message = AsyncMock()
channel._stop_typing = Mock()
channel._remove_reaction = AsyncMock()
await channel.send(OutboundMessage( await channel.send(OutboundMessage(
channel="telegram", chat_id="999", content="Compressing context…", channel="telegram", chat_id="999", content="Compressing context…",
event=ContextCompactionEvent(compaction_id="c1", phase="started"), metadata={"message_id": "42"},
event=ContextCompactionEvent(compaction_id="c1", phase=phase),
)) ))
channel._app.bot.send_message.assert_not_awaited() channel._app.bot.send_message.assert_not_awaited()
channel._stop_typing.assert_not_called()
channel._remove_reaction.assert_not_awaited()
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -3146,7 +3146,8 @@ async def test_failed_turn_end_exposes_safe_terminal_outcome() -> None:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_context_compaction_started_is_live_only() -> None: @pytest.mark.parametrize("notify", [False, True])
async def test_context_compaction_started_is_live_only(notify) -> None:
bus = MagicMock() bus = MagicMock()
channel = WebSocketChannel( channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]}, {"enabled": True, "allowFrom": ["*"]},
@@ -3163,6 +3164,7 @@ async def test_context_compaction_started_is_live_only() -> None:
event=ContextCompactionEvent( event=ContextCompactionEvent(
compaction_id="compact-started", compaction_id="compact-started",
phase="started", phase="started",
notify=notify,
), ),
)) ))
@@ -3176,7 +3178,9 @@ async def test_context_compaction_started_is_live_only() -> None:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_context_compaction_is_structured_persisted_and_summary_free() -> None: @pytest.mark.parametrize("notify", [False, True])
@pytest.mark.parametrize("phase", ["succeeded", "failed", "cancelled"])
async def test_context_compaction_is_structured_persisted_and_summary_free(notify, phase) -> None:
bus = MagicMock() bus = MagicMock()
channel = WebSocketChannel( channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]}, {"enabled": True, "allowFrom": ["*"]},
@@ -3192,7 +3196,8 @@ async def test_context_compaction_is_structured_persisted_and_summary_free() ->
content="Context compacted · LLM summary", content="Context compacted · LLM summary",
event=ContextCompactionEvent( event=ContextCompactionEvent(
compaction_id="compact-1", compaction_id="compact-1",
phase="succeeded", phase=phase,
notify=notify,
), ),
)) ))
@@ -3200,7 +3205,7 @@ async def test_context_compaction_is_structured_persisted_and_summary_free() ->
"event": "context_compaction", "event": "context_compaction",
"chat_id": "chat-compaction", "chat_id": "chat-compaction",
"compaction_id": "compact-1", "compaction_id": "compact-1",
"phase": "succeeded", "phase": phase,
} }
assert _sent_ws_payloads(mock_ws) == [expected] assert _sent_ws_payloads(mock_ws) == [expected]
[persisted] = read_transcript_lines("websocket:chat-compaction") [persisted] = read_transcript_lines("websocket:chat-compaction")
@@ -20,7 +20,11 @@ if not WECOM_AVAILABLE:
from wecom_aibot_sdk import UploadResult, WSClient from wecom_aibot_sdk import UploadResult, WSClient
from nanobot.bus.events import OutboundMessage from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent from nanobot.bus.outbound_events import (
ContextCompactionEvent,
ProgressEvent,
outbound_message_for_event,
)
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.channels.wecom.runtime import ( from nanobot.channels.wecom.runtime import (
WECOM_WEBSOCKET_HOST, WECOM_WEBSOCKET_HOST,
@@ -171,6 +175,29 @@ async def test_download_and_save_failure() -> None:
# ── send() ────────────────────────────────────────────────────────── # ── send() ──────────────────────────────────────────────────────────
@pytest.mark.asyncio
@pytest.mark.parametrize("has_frame", [False, True])
@pytest.mark.parametrize("notify", [False, True])
@pytest.mark.parametrize("phase", ["started", "succeeded", "failed", "cancelled"])
async def test_compaction_notice_policy(has_frame, notify, phase) -> None:
channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus())
client = _FakeWeComClient()
channel._client = client
channel._generate_req_id = lambda x: f"req_{x}"
if has_frame:
channel._chat_frames["chat1"] = _FakeFrame()
await channel.send(outbound_message_for_event(
channel="wecom", chat_id="chat1",
event=ContextCompactionEvent("compact", phase, notify=notify),
))
assert client.reply_stream.await_count == int(notify and has_frame)
assert client.send_message.await_count == int(notify and not has_frame)
# A quiet event must not consume the response route for the actual answer.
assert ("chat1" in channel._chat_frames) is has_frame
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_send_text_with_frame() -> None: async def test_send_text_with_frame() -> None:
"""When frame is stored, send uses reply_stream for final text.""" """When frame is stored, send uses reply_stream for final text."""
+1 -1
View File
@@ -37,8 +37,8 @@ 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.utils.logging_bridge import redirect_lib_logging
from nanobot.events import ContextCompactionEvent from nanobot.events import ContextCompactionEvent
from nanobot.utils.logging_bridge import redirect_lib_logging
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Protocol constants (from openclaw-weixin types.ts) # Protocol constants (from openclaw-weixin types.ts)
+2
View File
@@ -37,6 +37,8 @@ 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"]
# Request a chat notice (e.g. /compact), not event delivery or persistence.
# Interactive clients still consume every phase when this is false.
notify: bool = False notify: bool = False
+31 -12
View File
@@ -2,8 +2,8 @@
QQ's C2C/group message API has no edit or recall endpoint, so the QQ's C2C/group message API has no edit or recall endpoint, so the
compaction lifecycle would land as two separate permanent messages. The compaction lifecycle would land as two separate permanent messages. The
channel drops ``ContextCompactionEvent`` by default; ``showCompactionNotices: channel drops automatic notices by default; ``showCompactionNotices: true``
true`` restores the notices for anyone who wants them (#5784). restores them (#5784). Manual requests keep their feedback independently.
""" """
from __future__ import annotations from __future__ import annotations
@@ -20,16 +20,18 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.qq.runtime import QQChannel, QQConfig from nanobot.channels.qq.runtime import QQChannel, QQConfig
def _make_channel(**config_kwargs) -> QQChannel: def _make_channel(tmp_path, **config_kwargs) -> QQChannel:
config = QQConfig(app_id="test_app", secret="test_secret", **config_kwargs) config = QQConfig(
app_id="test_app", secret="test_secret", media_dir=str(tmp_path), **config_kwargs,
)
channel = QQChannel(config, MessageBus()) channel = QQChannel(config, MessageBus())
channel._client = object() # truthy: pass the initialized check channel._client = object() # truthy: pass the initialized check
return channel return channel
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_compaction_notices_dropped_by_default(monkeypatch) -> None: async def test_compaction_notices_dropped_by_default(monkeypatch, tmp_path) -> None:
channel = _make_channel() channel = _make_channel(tmp_path)
send_text = AsyncMock() send_text = AsyncMock()
monkeypatch.setattr(channel, "_send_text_only", send_text) monkeypatch.setattr(channel, "_send_text_only", send_text)
@@ -43,23 +45,40 @@ async def test_compaction_notices_dropped_by_default(monkeypatch) -> None:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_compaction_notices_sent_when_enabled(monkeypatch) -> None: @pytest.mark.parametrize("notify", [False, True])
channel = _make_channel(show_compaction_notices=True) @pytest.mark.parametrize("phase", ["started", "succeeded", "failed", "cancelled"])
async def test_compaction_notices_sent_when_enabled(monkeypatch, tmp_path, notify, phase) -> None:
channel = _make_channel(tmp_path, show_compaction_notices=True)
send_text = AsyncMock() send_text = AsyncMock()
monkeypatch.setattr(channel, "_send_text_only", send_text) monkeypatch.setattr(channel, "_send_text_only", send_text)
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", notify=True), event=ContextCompactionEvent(compaction_id="c1", phase=phase, notify=notify),
)) ))
send_text.assert_awaited_once() send_text.assert_awaited_once()
assert send_text.await_args.kwargs["content"] == "Compressing context…" assert send_text.await_args.kwargs["content"]
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_ordinary_messages_unaffected(monkeypatch) -> None: @pytest.mark.parametrize("phase", ["started", "succeeded", "failed", "cancelled"])
channel = _make_channel() async def test_manual_compaction_has_feedback_with_default_config(monkeypatch, tmp_path, phase) -> None:
channel = _make_channel(tmp_path)
send_text = AsyncMock()
monkeypatch.setattr(channel, "_send_text_only", send_text)
await channel.send(outbound_message_for_event(
channel="qq", chat_id="chat",
event=ContextCompactionEvent(compaction_id="manual", phase=phase, notify=True),
))
send_text.assert_awaited_once()
@pytest.mark.asyncio
async def test_ordinary_messages_unaffected(monkeypatch, tmp_path) -> None:
channel = _make_channel(tmp_path)
send_text = AsyncMock() send_text = AsyncMock()
monkeypatch.setattr(channel, "_send_text_only", send_text) monkeypatch.setattr(channel, "_send_text_only", send_text)