diff --git a/docs/configuration.md b/docs/configuration.md index 73b16cca0..0155fe07b 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -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 { diff --git a/docs/memory.md b/docs/memory.md index a39c3ca2a..d4cf71039 100644 --- a/docs/memory.md +++ b/docs/memory.md @@ -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. +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: - append-only diff --git a/nanobot/agent/turn_delivery.py b/nanobot/agent/turn_delivery.py index a4616c322..328e98d97 100644 --- a/nanobot/agent/turn_delivery.py +++ b/nanobot/agent/turn_delivery.py @@ -67,12 +67,7 @@ def _bind_events( ) async def publish(event: AgentEvent) -> None: - # 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, - ): + if not accepts(type(event)): return await bus.publish_event( event, channel=channel, chat_id=chat_id, metadata=deepcopy(metadata), diff --git a/nanobot/bus/notification_delivery.py b/nanobot/bus/notification_delivery.py index 6098328fa..a821849fc 100644 --- a/nanobot/bus/notification_delivery.py +++ b/nanobot/bus/notification_delivery.py @@ -33,10 +33,9 @@ NOTIFICATION_AUDIENCES: dict[type[AgentEvent], NotificationAudience] = { def notification_is_deliverable( - event: AgentEvent | type[AgentEvent], *, channel: str, publish_lifecycle: bool, + event_type: 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 diff --git a/nanobot/channels/linear/tests/test_linear.py b/nanobot/channels/linear/tests/test_linear.py index 68a674f3f..d850669ac 100644 --- a/nanobot/channels/linear/tests/test_linear.py +++ b/nanobot/channels/linear/tests/test_linear.py @@ -798,10 +798,12 @@ async def test_followups_only_repeat_issue_context_when_it_changes(tmp_path: Pat @pytest.mark.asyncio +@pytest.mark.parametrize("notify", [False, True]) @pytest.mark.parametrize("idle", [True, False]) @pytest.mark.parametrize("phase", ["succeeded", "failed", "cancelled"]) async def test_compaction_restores_issue_context_on_next_message( tmp_path: Path, idle: bool, phase: Literal["succeeded", "failed", "cancelled"], + notify: bool, ) -> None: channel, _ = _runtime(tmp_path) payload = _agent_webhook() @@ -815,7 +817,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, notify=True), + event=ContextCompactionEvent(compaction_id="compact", phase=phase, notify=notify), )) for delivery, include_context in (("after", phase == "succeeded"), ("again", False)): await channel._process_webhook(delivery, followup) # pyright: ignore[reportPrivateUsage] diff --git a/nanobot/channels/qq/runtime.py b/nanobot/channels/qq/runtime.py index 783842205..1f3fc8c4d 100644 --- a/nanobot/channels/qq/runtime.py +++ b/nanobot/channels/qq/runtime.py @@ -193,7 +193,7 @@ class QQConfig(Base): download_chunk_size: int = 1024 * 256 # 256KB 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; # set showCompactionNotices: true to post them anyway. show_compaction_notices: bool = False @@ -307,11 +307,11 @@ class QQChannel(BaseChannel): # Compaction notices assume the channel can update one message in place # (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 - # lifecycle is dropped here instead of posting two permanent messages - # (#5784); showCompactionNotices: true restores them. + # automatic lifecycle is quiet by default (#5784). Explicit opt-in + # restores it; manual /compact always retains its requested feedback. if ( 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 diff --git a/nanobot/channels/telegram/runtime.py b/nanobot/channels/telegram/runtime.py index f18aab4c9..25681580c 100644 --- a/nanobot/channels/telegram/runtime.py +++ b/nanobot/channels/telegram/runtime.py @@ -1058,6 +1058,8 @@ class TelegramChannel(BaseChannel): async def send(self, msg: OutboundMessage) -> None: """Send a message through Telegram.""" + if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify: + return app = await self._wait_for_app() if app is None: self.logger.warning("bot not running") @@ -1096,8 +1098,6 @@ 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, ) diff --git a/nanobot/channels/telegram/tests/test_telegram_channel.py b/nanobot/channels/telegram/tests/test_telegram_channel.py index acbcd7987..1178f9276 100644 --- a/nanobot/channels/telegram/tests/test_telegram_channel.py +++ b/nanobot/channels/telegram/tests/test_telegram_channel.py @@ -2,7 +2,7 @@ import asyncio from datetime import timedelta from pathlib import Path from types import SimpleNamespace -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, Mock import pytest @@ -3298,20 +3298,26 @@ async def test_compaction_terminal_phase_edits_started_notice_in_place() -> None @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( TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]), MessageBus(), ) _install_ready_app(channel) channel._app.bot.send_message = AsyncMock() + channel._stop_typing = Mock() + channel._remove_reaction = AsyncMock() await channel.send(OutboundMessage( 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._stop_typing.assert_not_called() + channel._remove_reaction.assert_not_awaited() @pytest.mark.asyncio diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py index b497063d2..5353cb3e7 100644 --- a/nanobot/channels/websocket/tests/test_websocket_channel.py +++ b/nanobot/channels/websocket/tests/test_websocket_channel.py @@ -3146,7 +3146,8 @@ async def test_failed_turn_end_exposes_safe_terminal_outcome() -> None: @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() channel = WebSocketChannel( {"enabled": True, "allowFrom": ["*"]}, @@ -3163,6 +3164,7 @@ async def test_context_compaction_started_is_live_only() -> None: event=ContextCompactionEvent( compaction_id="compact-started", phase="started", + notify=notify, ), )) @@ -3176,7 +3178,9 @@ async def test_context_compaction_started_is_live_only() -> None: @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() channel = WebSocketChannel( {"enabled": True, "allowFrom": ["*"]}, @@ -3192,7 +3196,8 @@ async def test_context_compaction_is_structured_persisted_and_summary_free() -> content="Context compacted · LLM summary", event=ContextCompactionEvent( 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", "chat_id": "chat-compaction", "compaction_id": "compact-1", - "phase": "succeeded", + "phase": phase, } assert _sent_ws_payloads(mock_ws) == [expected] [persisted] = read_transcript_lines("websocket:chat-compaction") diff --git a/nanobot/channels/wecom/tests/test_wecom_channel.py b/nanobot/channels/wecom/tests/test_wecom_channel.py index c0bf4b80e..dede0e5c0 100644 --- a/nanobot/channels/wecom/tests/test_wecom_channel.py +++ b/nanobot/channels/wecom/tests/test_wecom_channel.py @@ -20,7 +20,11 @@ if not WECOM_AVAILABLE: from wecom_aibot_sdk import UploadResult, WSClient 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.channels.wecom.runtime import ( WECOM_WEBSOCKET_HOST, @@ -171,6 +175,29 @@ async def test_download_and_save_failure() -> None: # ── 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 async def test_send_text_with_frame() -> None: """When frame is stored, send uses reply_stream for final text.""" diff --git a/nanobot/channels/weixin/runtime.py b/nanobot/channels/weixin/runtime.py index 1600aa4f1..dbcbb0256 100644 --- a/nanobot/channels/weixin/runtime.py +++ b/nanobot/channels/weixin/runtime.py @@ -37,8 +37,8 @@ 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.utils.logging_bridge import redirect_lib_logging from nanobot.events import ContextCompactionEvent +from nanobot.utils.logging_bridge import redirect_lib_logging # --------------------------------------------------------------------------- # Protocol constants (from openclaw-weixin types.ts) diff --git a/nanobot/events.py b/nanobot/events.py index bfb8a49e4..7d5397308 100644 --- a/nanobot/events.py +++ b/nanobot/events.py @@ -37,6 +37,8 @@ class ResponseSourceEvent(AgentEvent): class ContextCompactionEvent(AgentEvent): compaction_id: str 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 diff --git a/tests/channels/test_qq_compaction_notices.py b/tests/channels/test_qq_compaction_notices.py index 7369c5b52..4c46f2be7 100644 --- a/tests/channels/test_qq_compaction_notices.py +++ b/tests/channels/test_qq_compaction_notices.py @@ -2,8 +2,8 @@ QQ's C2C/group message API has no edit or recall endpoint, so the compaction lifecycle would land as two separate permanent messages. The -channel drops ``ContextCompactionEvent`` by default; ``showCompactionNotices: -true`` restores the notices for anyone who wants them (#5784). +channel drops automatic notices by default; ``showCompactionNotices: true`` +restores them (#5784). Manual requests keep their feedback independently. """ from __future__ import annotations @@ -20,16 +20,18 @@ from nanobot.bus.queue import MessageBus from nanobot.channels.qq.runtime import QQChannel, QQConfig -def _make_channel(**config_kwargs) -> QQChannel: - config = QQConfig(app_id="test_app", secret="test_secret", **config_kwargs) +def _make_channel(tmp_path, **config_kwargs) -> QQChannel: + config = QQConfig( + app_id="test_app", secret="test_secret", media_dir=str(tmp_path), **config_kwargs, + ) channel = QQChannel(config, MessageBus()) channel._client = object() # truthy: pass the initialized check return channel @pytest.mark.asyncio -async def test_compaction_notices_dropped_by_default(monkeypatch) -> None: - channel = _make_channel() +async def test_compaction_notices_dropped_by_default(monkeypatch, tmp_path) -> None: + channel = _make_channel(tmp_path) send_text = AsyncMock() 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 -async def test_compaction_notices_sent_when_enabled(monkeypatch) -> None: - channel = _make_channel(show_compaction_notices=True) +@pytest.mark.parametrize("notify", [False, 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() monkeypatch.setattr(channel, "_send_text_only", send_text) await channel.send(outbound_message_for_event( 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() - assert send_text.await_args.kwargs["content"] == "Compressing context…" + assert send_text.await_args.kwargs["content"] @pytest.mark.asyncio -async def test_ordinary_messages_unaffected(monkeypatch) -> None: - channel = _make_channel() +@pytest.mark.parametrize("phase", ["started", "succeeded", "failed", "cancelled"]) +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() monkeypatch.setattr(channel, "_send_text_only", send_text)