feat(channels): add inherited global compaction notice policy

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

No files matched your search

+2
View File
@@ -18,6 +18,7 @@ def field(
default: Any = None,
writable: bool = True,
snapshot: bool = True,
inheritable: bool = False,
) -> ChannelFieldSpec:
return ChannelFieldSpec(
kind=kind,
@@ -25,6 +26,7 @@ def field(
default=default,
writable=writable,
snapshot=snapshot,
inheritable=inheritable,
)
+1
View File
@@ -31,6 +31,7 @@ class BaseChannel(ABC):
send_progress: bool = True
send_tool_hints: bool = True
show_reasoning: bool = True
show_compaction_notices: bool = False
def __init__(self, config: Any, bus: MessageBus):
"""
+6
View File
@@ -118,6 +118,8 @@ class ChannelFieldSpec:
default: Any = None
writable: bool = True
snapshot: bool = True
# An omitted/null override inherits host policy instead of materializing a default.
inheritable: bool = False
@property
def route_type(self) -> RouteFieldType:
@@ -210,6 +212,8 @@ class ChannelSetupSpec:
}
if field.default is not None:
public_field["default_value"] = stringify_channel_value(field.default)
if field.inheritable:
public_field["inheritable"] = True
fields.append(public_field)
payload: dict[str, Any] = {
"fields": fields,
@@ -283,6 +287,8 @@ def channel_default_config(plugin: ChannelPlugin) -> dict[str, Any]:
defaults: dict[str, Any] = {"enabled": plugin.default_enabled}
if plugin.setup is not None:
for name, field in plugin.setup.fields.items():
if field.inheritable:
continue
value: Any = field.default
if value is None:
fallback_defaults: dict[str, Any] = {
+3 -1
View File
@@ -736,7 +736,9 @@ 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:
if isinstance(msg.event, ContextCompactionEvent) and not (
msg.event.notify or self.show_compaction_notices
):
return
token = await self._get_access_token()
if not token:
+3 -1
View File
@@ -261,7 +261,9 @@ 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:
if compaction is not None and not (
compaction.notify or self._channel.show_compaction_notices
):
return
# A compaction's outcome replaces its own start notice in place, so
# the lifecycle stays visible as one message instead of two (#5719).
+3 -1
View File
@@ -240,7 +240,9 @@ class EmailChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
"""Send email via SMTP."""
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
if isinstance(msg.event, ContextCompactionEvent) and not (
msg.event.notify or self.show_compaction_notices
):
return
if not self.config.consent_granted:
self.logger.warning("Skip email send: consent_granted is false")
+3 -1
View File
@@ -2441,7 +2441,9 @@ 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:
if isinstance(msg.event, ContextCompactionEvent) and not (
msg.event.notify or self.show_compaction_notices
):
return
if not self._client:
self.logger.warning("client not initialized")
+1 -1
View File
@@ -130,7 +130,7 @@ class LinearChannel(BaseChannel):
if isinstance(event, ContextCompactionEvent):
if event.phase == "succeeded":
self._issue_contexts.pop(msg.chat_id, None)
if not event.notify:
if not (event.notify or self.show_compaction_notices):
return
# Idle notifications have no originating Linear turn. Sending a thought
# through the cached route would reactivate an already completed session.
+8
View File
@@ -68,6 +68,7 @@ _BOOL_CAMEL_ALIASES: dict[str, str] = {
"send_progress": "sendProgress",
"send_tool_hints": "sendToolHints",
"show_reasoning": "showReasoning",
"show_compaction_notices": "showCompactionNotices",
}
def _default_channel_config(name: str) -> dict[str, Any] | None:
@@ -229,6 +230,13 @@ class ChannelManager:
channel.show_reasoning = self._resolve_bool_override(
section, "show_reasoning", self.config.channels.show_reasoning,
)
# Retain adapter-validated legacy values (QQ already owned this option).
notice_default = self._resolve_bool_override(
channel.config, "show_compaction_notices", self.config.channels.show_compaction_notices,
)
channel.show_compaction_notices = self._resolve_bool_override(
section, "show_compaction_notices", notice_default,
)
return channel
def _init_channels(self) -> None:
+3 -1
View File
@@ -616,7 +616,9 @@ 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:
if isinstance(msg.event, ContextCompactionEvent) and not (
msg.event.notify or self.show_compaction_notices
):
return
if not self.client:
raise RuntimeError("Matrix client not initialized")
+3 -1
View File
@@ -493,7 +493,9 @@ class MattermostChannel(BaseChannel):
# Send ---------------------------------------------------------------------
async def send(self, msg: OutboundMessage) -> None:
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
if isinstance(msg.event, ContextCompactionEvent) and not (
msg.event.notify or self.show_compaction_notices
):
return
if not self._http_client:
self.logger.warning("client not initialized")
+3 -1
View File
@@ -351,7 +351,9 @@ 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:
if isinstance(msg.event, ContextCompactionEvent) and not (
msg.event.notify or self.show_compaction_notices
):
return
if not self.config.claw_token:
self.logger.warning("claw_token missing, skip send")
+3 -1
View File
@@ -251,7 +251,9 @@ 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:
if isinstance(msg.event, ContextCompactionEvent) and not (
msg.event.notify or self.show_compaction_notices
):
return
if not self._http:
raise RuntimeError("MSTeams HTTP client not initialized")
+3 -1
View File
@@ -438,7 +438,9 @@ class NapcatChannel(BaseChannel):
# ------------------------------------------------------------------
async def send(self, msg: OutboundMessage) -> None:
if isinstance(msg.event, ContextCompactionEvent) and not msg.event.notify:
if isinstance(msg.event, ContextCompactionEvent) and not (
msg.event.notify or self.show_compaction_notices
):
return
if self._ws is None:
raise RuntimeError("napcat: not connected")
+1 -1
View File
@@ -11,7 +11,7 @@ SETUP_SPEC = ChannelSetupSpec(
"allowFrom": field("list"),
"msgFormat": field("enum", choices={"plain", "markdown"}, default="plain"),
"ackMessage": field(default="⏳ Processing..."),
"showCompactionNotices": field("bool", default=False),
"showCompactionNotices": field("bool", inheritable=True),
"mediaDir": field(),
"downloadChunkSize": field("int", default=1024 * 256),
"downloadMaxBytes": field("int", default=1024 * 1024 * 200),
+8 -5
View File
@@ -194,9 +194,9 @@ class QQConfig(Base):
download_max_bytes: int = 1024 * 1024 * 200 # 200MB safety limit
# 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
# notices would land as separate permanent messages (#5784). Unset inherits
# the global policy (off by default); explicit legacy true/false still override it.
show_compaction_notices: bool | None = None
class QQChannel(BaseChannel):
@@ -207,13 +207,16 @@ class QQChannel(BaseChannel):
@classmethod
def default_config(cls) -> dict[str, Any]:
return QQConfig().model_dump(by_alias=True)
return QQConfig().model_dump(by_alias=True, exclude_none=True)
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = QQConfig.model_validate(config)
super().__init__(config, bus)
self.config: QQConfig = config
# Preserve explicitly configured notices for standalone channel callers.
# ChannelManager resolves global inheritance from the original section.
self.show_compaction_notices = bool(config.show_compaction_notices)
self._client: Any | None = None
self._http: aiohttp.ClientSession | None = None
@@ -311,7 +314,7 @@ class QQChannel(BaseChannel):
# restores it; manual /compact always retains its requested feedback.
if (
isinstance(msg.event, ContextCompactionEvent)
and not (msg.event.notify or self.config.show_compaction_notices)
and not (msg.event.notify or self.show_compaction_notices)
):
return
+3 -1
View File
@@ -565,7 +565,9 @@ 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:
if isinstance(msg.event, ContextCompactionEvent) and not (
msg.event.notify or self.show_compaction_notices
):
return
is_progress_message = isinstance(msg.event, ProgressEvent)
try:
+3 -1
View File
@@ -202,7 +202,9 @@ 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:
if isinstance(msg.event, ContextCompactionEvent) and not (
msg.event.notify or self.show_compaction_notices
):
return
if not self._web_client:
self.logger.warning("client not running")
+3 -1
View File
@@ -1058,7 +1058,9 @@ 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:
if isinstance(msg.event, ContextCompactionEvent) and not (
msg.event.notify or self.show_compaction_notices
):
return
app = await self._wait_for_app()
if app is None:
@@ -3147,7 +3147,8 @@ async def test_failed_turn_end_exposes_safe_terminal_outcome() -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize("notify", [False, True])
async def test_context_compaction_started_is_live_only(notify) -> None:
@pytest.mark.parametrize("show_notices", [False, True])
async def test_context_compaction_started_is_live_only(notify, show_notices) -> None:
bus = MagicMock()
channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]},
@@ -3156,6 +3157,7 @@ async def test_context_compaction_started_is_live_only(notify) -> None:
)
mock_ws = AsyncMock()
channel._attach(mock_ws, "chat-compaction-started")
channel.show_compaction_notices = show_notices
await channel.send(OutboundMessage(
channel="websocket",
@@ -3179,8 +3181,9 @@ async def test_context_compaction_started_is_live_only(notify) -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize("notify", [False, True])
@pytest.mark.parametrize("show_notices", [False, True])
@pytest.mark.parametrize("phase", ["succeeded", "failed", "cancelled"])
async def test_context_compaction_is_structured_persisted_and_summary_free(notify, phase) -> None:
async def test_context_compaction_is_structured_persisted_and_summary_free(notify, show_notices, phase) -> None:
bus = MagicMock()
channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]},
@@ -3189,6 +3192,7 @@ async def test_context_compaction_is_structured_persisted_and_summary_free(notif
)
mock_ws = AsyncMock()
channel._attach(mock_ws, "chat-compaction")
channel.show_compaction_notices = show_notices
await channel.send(OutboundMessage(
channel="websocket",
+3 -1
View File
@@ -411,7 +411,9 @@ 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:
if isinstance(msg.event, ContextCompactionEvent) and not (
msg.event.notify or self.show_compaction_notices
):
return
if not self._client:
raise RuntimeError("WeCom client not initialized")
@@ -178,9 +178,11 @@ async def test_download_and_save_failure() -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize("has_frame", [False, True])
@pytest.mark.parametrize("notify", [False, True])
@pytest.mark.parametrize("show_notices", [False, True])
@pytest.mark.parametrize("phase", ["started", "succeeded", "failed", "cancelled"])
async def test_compaction_notice_policy(has_frame, notify, phase) -> None:
async def test_compaction_notice_policy(has_frame, notify, show_notices, phase) -> None:
channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus())
channel.show_compaction_notices = show_notices
client = _FakeWeComClient()
channel._client = client
channel._generate_req_id = lambda x: f"req_{x}"
@@ -192,8 +194,8 @@ async def test_compaction_notice_policy(has_frame, notify, phase) -> None:
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)
assert client.reply_stream.await_count == int((notify or show_notices) and has_frame)
assert client.send_message.await_count == int((notify or show_notices) 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
+3 -1
View File
@@ -1885,7 +1885,9 @@ class WeixinChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
event = getattr(msg, "event", None)
if isinstance(event, ContextCompactionEvent) and not event.notify:
if isinstance(event, ContextCompactionEvent) and not (
event.notify or self.show_compaction_notices
):
return
if not self._client or not self._token:
raise RuntimeError("WeChat client not initialized or not authenticated")
+3 -1
View File
@@ -460,7 +460,9 @@ 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:
if isinstance(msg.event, ContextCompactionEvent) and not (
msg.event.notify or self.show_compaction_notices
):
return
client = self._client
if client is None or not self._connected:
+1
View File
@@ -33,6 +33,7 @@ class ChannelsConfig(Base):
send_progress: bool = True # stream agent's text progress to the channel
send_tool_hints: bool = True # stream tool-call hints (e.g. read_file("…"))
show_reasoning: bool = True # surface model reasoning when channel implements it
show_compaction_notices: bool = False # automatic compaction chat notices, not UI lifecycle events
extract_document_text: bool = True # Deprecated and ignored; documents are read on demand
send_max_retries: int = Field(default=3, ge=0, le=10) # Max delivery attempts (initial send included)
transcription_provider: str = "groq" # Deprecated: use top-level transcription.provider
+20 -3
View File
@@ -13,6 +13,8 @@ from pathlib import Path
from typing import TYPE_CHECKING, Any, TypedDict, cast
from zoneinfo import ZoneInfo
from pydantic.alias_generators import to_snake
from nanobot.channels._setup import channel_setup_spec
from nanobot.channels.connect import ChannelConnectError
from nanobot.channels.contracts import (
@@ -231,10 +233,15 @@ def save_channel_config_values(
value_type = field_types.get(field)
if value_type is None:
raise WebUISettingsError(f"'{raw_key}' cannot be configured from WebUI")
value = coerce_channel_value(raw_key, raw_value, value_type)
if setup_spec.fields[field].inheritable and raw_value in (None, ""):
value = None
else:
value = coerce_channel_value(raw_key, raw_value, value_type)
if value is _SKIP_FIELD:
continue
assign_channel_config_value(channel_config, field, value)
assign_channel_config_value(
channel_config, field, value, inheritable=setup_spec.fields[field].inheritable,
)
saved.append(raw_key)
try:
@@ -339,6 +346,8 @@ def assign_channel_config_value(
channel_config: dict[str, Any],
field: str,
value: Any,
*,
inheritable: bool = False,
) -> None:
target = channel_config
parts = field.split(".")
@@ -348,7 +357,15 @@ def assign_channel_config_value(
current = {}
target[part] = current
target = cast(dict[str, Any], current)
target[parts[-1]] = value
key = parts[-1]
if inheritable:
# Do not leave an older snake_case override shadowing this UI edit.
target.pop(to_snake(key), None)
if value is None:
# Absence restores inheritance and remains readable by older configs.
target.pop(key, None)
return
target[key] = value
def pairing_payload(