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

+1 -6
View File
@@ -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),
+1 -2
View File
@@ -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
+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.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]
+4 -4
View File
@@ -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
+2 -2
View File
@@ -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,
)
@@ -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
@@ -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")
@@ -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."""
+1 -1
View File
@@ -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)
+2
View File
@@ -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