Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
feat(channels): add inherited global compaction notice policy
Xubin Renab6d5f1d3c54
diff --git a/docs/configuration.md b/docs/configuration.mdindex 0155fe07b..f0d057565 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -1623,6 +1623,7 @@ Global settings that apply to all channels. Configure under the `channels` secti|---------|---------|-------------|| `sendProgress` | `true` | Stream agent's text progress to the channel || `sendToolHints` | `true` | Stream tool-call hints (e.g. `read_file("…")`) |+| `showCompactionNotices` | `false` | Post automatic context-compaction lifecycle notices in built-in chat channels. Each channel can override this global default. Does not hide manual `/compact` feedback or WebUI/TUI structured events. || `showReasoning` | `true` | Allow channels to surface model reasoning/thinking content (DeepSeek-R1 `reasoning_content`, Anthropic `thinking_blocks`, inline `<think>` tags). Reasoning flows as a dedicated stream with `_reasoning_delta` / `_reasoning_end` markers — channels override `send_reasoning_delta` / `send_reasoning_end` to render in-place updates. Even with `true`, channels without those overrides stay no-op silently. Currently surfaced on CLI and WebSocket/WebUI (italic shimmer header, auto-collapses after the stream ends); Telegram / Slack / Discord / Feishu / WeChat / Matrix / Mattermost keep the base no-op until their bubble UI is adapted. Independent of `sendProgress`. || `sendMaxRetries` | `3` | Max delivery attempts per outbound message, including the initial send (0-10 configured, minimum 1 actual attempt) |@@ -1657,18 +1658,23 @@ Normal tool workspace and media access rules still apply to attachment paths.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:+Set `channels.showCompactionNotices: true` in `config.json` to enable automatic notices globally ("Compressing context…" / "Context compacted.", including failure and cancellation outcomes). A channel's explicit `true` or `false` overrides the global default; an omitted or `null` value inherits it. Like the global progress settings, this global option is configured in `config.json`. QQ's existing WebUI advanced setting also supports **Default** to inherit the global value; saving unrelated settings preserves inheritance. Restart the gateway after editing `config.json`.++For example, enable notices globally but keep WeCom quiet:```json{"channels": {- "qq": {- "showCompactionNotices": true+ "showCompactionNotices": true,+ "wecom": {+ "showCompactionNotices": false}}}```+Existing QQ `showCompactionNotices: true` or `false` settings remain explicit overrides. QQ's C2C/group message API has no edit or recall endpoint, so enabled notices land as separate permanent messages. This setting controls only automatic chat notices, not compaction execution, saved history, structured WebUI/TUI status, or manual command feedback. Third-party channel plugins must implement the same rendering policy to honor this option.+Telegram `richMessages` defaults to `false`. Enable it only to opt in to Bot API 10.1 `sendRichMessage` rendering; leave it disabled for Telegram Web clients that show unsupported-message errors for rich messages.### Retry Behaviordiff --git a/docs/memory.md b/docs/memory.mdindex d4cf71039..8671b1857 100644--- a/docs/memory.md+++ b/docs/memory.md@@ -33,7 +33,7 @@ When a conversation grows large, nanobot summarizes the conversation covered byCompaction 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`.+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. Set `channels.showCompactionNotices: true` to enable automatic notices globally, or set `showCompactionNotices` in a channel's configuration to override that default. Omitted or `null` channel overrides inherit the global value; existing explicit QQ overrides are preserved.This file is:diff --git a/nanobot/channels/_manifest.py b/nanobot/channels/_manifest.pyindex 2d8f6ee24..44f0bdc62 100644--- a/nanobot/channels/_manifest.py+++ b/nanobot/channels/_manifest.py@@ -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,)diff --git a/nanobot/channels/base.py b/nanobot/channels/base.pyindex ed2fb7774..9a245a5a3 100644--- a/nanobot/channels/base.py+++ b/nanobot/channels/base.py@@ -31,6 +31,7 @@ class BaseChannel(ABC):send_progress: bool = Truesend_tool_hints: bool = Trueshow_reasoning: bool = True+ show_compaction_notices: bool = Falsedef __init__(self, config: Any, bus: MessageBus):"""diff --git a/nanobot/channels/contracts.py b/nanobot/channels/contracts.pyindex 0b9319a56..9bb8a6324 100644--- a/nanobot/channels/contracts.py+++ b/nanobot/channels/contracts.py@@ -118,6 +118,8 @@ class ChannelFieldSpec:default: Any = Nonewritable: bool = Truesnapshot: bool = True+ # An omitted/null override inherits host policy instead of materializing a default.+ inheritable: bool = False@propertydef 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"] = Truefields.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:+ continuevalue: Any = field.defaultif value is None:fallback_defaults: dict[str, Any] = {diff --git a/nanobot/channels/dingtalk/runtime.py b/nanobot/channels/dingtalk/runtime.pyindex 32723e3d2..9018d7271 100644--- a/nanobot/channels/dingtalk/runtime.py+++ b/nanobot/channels/dingtalk/runtime.py@@ -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+ ):returntoken = await self._get_access_token()if not token:diff --git a/nanobot/channels/discord/runtime.py b/nanobot/channels/discord/runtime.pyindex f8dccbc21..e74ec97d5 100644--- a/nanobot/channels/discord/runtime.py+++ b/nanobot/channels/discord/runtime.py@@ -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).diff --git a/nanobot/channels/email/runtime.py b/nanobot/channels/email/runtime.pyindex 3b55f4608..fb34dcbdf 100644--- a/nanobot/channels/email/runtime.py+++ b/nanobot/channels/email/runtime.py@@ -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+ ):returnif not self.config.consent_granted:self.logger.warning("Skip email send: consent_granted is false")diff --git a/nanobot/channels/feishu/runtime.py b/nanobot/channels/feishu/runtime.pyindex f2aefa1b2..867bb97ba 100644--- a/nanobot/channels/feishu/runtime.py+++ b/nanobot/channels/feishu/runtime.py@@ -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+ ):returnif not self._client:self.logger.warning("client not initialized")diff --git a/nanobot/channels/linear/runtime.py b/nanobot/channels/linear/runtime.pyindex 885256a05..3929d2904 100644--- a/nanobot/channels/linear/runtime.py+++ b/nanobot/channels/linear/runtime.py@@ -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.diff --git a/nanobot/channels/manager.py b/nanobot/channels/manager.pyindex 9d6a7f1e1..dddb5a646 100644--- a/nanobot/channels/manager.py+++ b/nanobot/channels/manager.py@@ -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 channeldef _init_channels(self) -> None:diff --git a/nanobot/channels/matrix/runtime.py b/nanobot/channels/matrix/runtime.pyindex 02fc5a09b..f208ce8c0 100644--- a/nanobot/channels/matrix/runtime.py+++ b/nanobot/channels/matrix/runtime.py@@ -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+ ):returnif not self.client:raise RuntimeError("Matrix client not initialized")diff --git a/nanobot/channels/mattermost/runtime.py b/nanobot/channels/mattermost/runtime.pyindex 154ca94d0..9b024e825 100644--- a/nanobot/channels/mattermost/runtime.py+++ b/nanobot/channels/mattermost/runtime.py@@ -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+ ):returnif not self._http_client:self.logger.warning("client not initialized")diff --git a/nanobot/channels/mochat/runtime.py b/nanobot/channels/mochat/runtime.pyindex 0578d471c..477e491f8 100644--- a/nanobot/channels/mochat/runtime.py+++ b/nanobot/channels/mochat/runtime.py@@ -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+ ):returnif not self.config.claw_token:self.logger.warning("claw_token missing, skip send")diff --git a/nanobot/channels/msteams/runtime.py b/nanobot/channels/msteams/runtime.pyindex 204bcfd05..a298f4a09 100644--- a/nanobot/channels/msteams/runtime.py+++ b/nanobot/channels/msteams/runtime.py@@ -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+ ):returnif not self._http:raise RuntimeError("MSTeams HTTP client not initialized")diff --git a/nanobot/channels/napcat/runtime.py b/nanobot/channels/napcat/runtime.pyindex 4f86c78f4..4df45357c 100644--- a/nanobot/channels/napcat/runtime.py+++ b/nanobot/channels/napcat/runtime.py@@ -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+ ):returnif self._ws is None:raise RuntimeError("napcat: not connected")diff --git a/nanobot/channels/qq/manifest.py b/nanobot/channels/qq/manifest.pyindex 28ada5680..13dbffa5d 100644--- a/nanobot/channels/qq/manifest.py+++ b/nanobot/channels/qq/manifest.py@@ -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),diff --git a/nanobot/channels/qq/runtime.py b/nanobot/channels/qq/runtime.pyindex 1f3fc8c4d..da72a8068 100644--- a/nanobot/channels/qq/runtime.py+++ b/nanobot/channels/qq/runtime.py@@ -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 = Noneclass QQChannel(BaseChannel):@@ -207,13 +207,16 @@ class QQChannel(BaseChannel):@classmethoddef 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 = Noneself._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)):returndiff --git a/nanobot/channels/signal/runtime.py b/nanobot/channels/signal/runtime.pyindex ff9c7c98d..5dfd1aaa9 100644--- a/nanobot/channels/signal/runtime.py+++ b/nanobot/channels/signal/runtime.py@@ -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+ ):returnis_progress_message = isinstance(msg.event, ProgressEvent)try:diff --git a/nanobot/channels/slack/runtime.py b/nanobot/channels/slack/runtime.pyindex 778a03a80..df73e923e 100644--- a/nanobot/channels/slack/runtime.py+++ b/nanobot/channels/slack/runtime.py@@ -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+ ):returnif not self._web_client:self.logger.warning("client not running")diff --git a/nanobot/channels/telegram/runtime.py b/nanobot/channels/telegram/runtime.pyindex 25681580c..76103c942 100644--- a/nanobot/channels/telegram/runtime.py+++ b/nanobot/channels/telegram/runtime.py@@ -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+ ):returnapp = await self._wait_for_app()if app is None:diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.pyindex 5353cb3e7..803436257 100644--- a/nanobot/channels/websocket/tests/test_websocket_channel.py+++ b/nanobot/channels/websocket/tests/test_websocket_channel.py@@ -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:[email protected]("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_noticesawait 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])[email protected]("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_noticesawait channel.send(OutboundMessage(channel="websocket",diff --git a/nanobot/channels/wecom/runtime.py b/nanobot/channels/wecom/runtime.pyindex 832efaedd..d4bdfdf15 100644--- a/nanobot/channels/wecom/runtime.py+++ b/nanobot/channels/wecom/runtime.py@@ -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+ ):returnif not self._client:raise RuntimeError("WeCom client not initialized")diff --git a/nanobot/channels/wecom/tests/test_wecom_channel.py b/nanobot/channels/wecom/tests/test_wecom_channel.pyindex dede0e5c0..3dea1982b 100644--- a/nanobot/channels/wecom/tests/test_wecom_channel.py+++ b/nanobot/channels/wecom/tests/test_wecom_channel.py@@ -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])[email protected]("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_noticesclient = _FakeWeComClient()channel._client = clientchannel._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_framediff --git a/nanobot/channels/weixin/runtime.py b/nanobot/channels/weixin/runtime.pyindex dbcbb0256..a61e65780 100644--- a/nanobot/channels/weixin/runtime.py+++ b/nanobot/channels/weixin/runtime.py@@ -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+ ):returnif not self._client or not self._token:raise RuntimeError("WeChat client not initialized or not authenticated")diff --git a/nanobot/channels/whatsapp/runtime.py b/nanobot/channels/whatsapp/runtime.pyindex 4478373e0..458e0b160 100644--- a/nanobot/channels/whatsapp/runtime.py+++ b/nanobot/channels/whatsapp/runtime.py@@ -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+ ):returnclient = self._clientif client is None or not self._connected:diff --git a/nanobot/config/schema.py b/nanobot/config/schema.pyindex c3e75dcaf..7d12da8b3 100644--- a/nanobot/config/schema.py+++ b/nanobot/config/schema.py@@ -33,6 +33,7 @@ class ChannelsConfig(Base):send_progress: bool = True # stream agent's text progress to the channelsend_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 eventsextract_document_text: bool = True # Deprecated and ignored; documents are read on demandsend_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.providerdiff --git a/nanobot/webui/settings_system.py b/nanobot/webui/settings_system.pyindex 02f9ab119..5267c3636 100644--- a/nanobot/webui/settings_system.py+++ b/nanobot/webui/settings_system.py@@ -13,6 +13,8 @@ from pathlib import Pathfrom typing import TYPE_CHECKING, Any, TypedDict, castfrom zoneinfo import ZoneInfo+from pydantic.alias_generators import to_snake+from nanobot.channels._setup import channel_setup_specfrom nanobot.channels.connect import ChannelConnectErrorfrom 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_configparts = field.split(".")@@ -348,7 +357,15 @@ def assign_channel_config_value(current = {}target[part] = currenttarget = 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] = valuedef pairing_payload(diff --git a/tests/channels/test_channel_manager_compaction_notices.py b/tests/channels/test_channel_manager_compaction_notices.pyindex 7a325caa0..6d34e6551 100644--- a/tests/channels/test_channel_manager_compaction_notices.py+++ b/tests/channels/test_channel_manager_compaction_notices.py@@ -33,7 +33,9 @@ class _MockChannel(BaseChannel):passasync def send(self, msg):- 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+ ):returnreturn await self._send_mock(msg)@@ -88,3 +90,37 @@ async def test_channel_receives_automatic_compaction_but_does_not_render_it(contents = _sent_contents(manager)assert "ordinary progress" not in contentsassert contents == ["Compressing context…", "Context compacted."]++[email protected]("global_value", [False, True])[email protected]("override", [None, False, True])[email protected]("key", ["show_compaction_notices", "showCompactionNotices"])+async def test_global_notice_policy_and_channel_override(manager, global_value, override, key):+ manager.config.channels.show_compaction_notices = global_value+ section = {} if override is None else {key: override}+ channel = manager._build_channel("mock", _MockChannel, section)+ assert channel.show_compaction_notices is (global_value if override is None else override)+ channel.send_progress = False # Ordinary progress and compaction are independent policies.+ manager.channels["mock"] = channel++ for phase in ("started", "succeeded", "failed", "cancelled"):+ for notify in (False, True):+ await channel.send(outbound_message_for_event(+ channel="mock", chat_id="chat",+ event=ContextCompactionEvent("compact", phase, notify=notify),+ ))++ assert channel._send_mock.await_count == (8 if channel.show_compaction_notices else 4)+++def test_global_notice_config_round_trip_and_rebuild(manager):+ assert Config().channels.show_compaction_notices is False+ manager.config = Config.model_validate({"channels": {"showCompactionNotices": True}})+ manager.config = Config.model_validate_json(manager.config.model_dump_json(by_alias=True))+ assert manager._build_channel("mock", _MockChannel, {}).show_compaction_notices is True+ # Rebuilding an adapter after a config change must resolve the new default.+ manager.config.channels.show_compaction_notices = False+ assert manager._build_channel("mock", _MockChannel, {}).show_compaction_notices is False+ assert manager._build_channel(+ "mock", _MockChannel, {"showCompactionNotices": True},+ ).show_compaction_noticesdiff --git a/tests/channels/test_qq_compaction_notices.py b/tests/channels/test_qq_compaction_notices.pyindex 4c46f2be7..59418578b 100644--- a/tests/channels/test_qq_compaction_notices.py+++ b/tests/channels/test_qq_compaction_notices.py@@ -17,7 +17,9 @@ pytest.importorskip("botpy")from nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ContextCompactionEvent, outbound_message_for_eventfrom nanobot.bus.queue import MessageBus+from nanobot.channels.manager import ChannelManagerfrom nanobot.channels.qq.runtime import QQChannel, QQConfig+from nanobot.config.schema import Configdef _make_channel(tmp_path, **config_kwargs) -> QQChannel:@@ -90,3 +92,23 @@ async def test_ordinary_messages_unaffected(monkeypatch, tmp_path) -> None:def test_config_accepts_camel_case_override() -> None:config = QQConfig.model_validate({"appId": "a", "secret": "s", "showCompactionNotices": True})assert config.show_compaction_notices is True++[email protected]("global_value", [False, True])[email protected]("override", [None, False, True])[email protected]("typed", [False, True])[email protected]("legacy_string", [False, True])+def test_qq_inherits_global_unless_legacy_override_is_explicit(+ tmp_path, global_value, override, typed, legacy_string,+):+ manager = ChannelManager.__new__(ChannelManager)+ manager.config = Config()+ manager.config.channels.show_compaction_notices = global_value+ manager.bus = MessageBus()+ section = {"appId": "a", "secret": "s", "mediaDir": str(tmp_path)}+ if override is not None:+ section["showCompactionNotices"] = str(override).lower() if legacy_string else override+ if typed:+ section = QQConfig.model_validate(section)+ channel = manager._build_channel("qq", QQChannel, section)+ assert channel.show_compaction_notices is (global_value if override is None else override)diff --git a/tests/webui/test_settings_system.py b/tests/webui/test_settings_system.pyindex 353e92765..f7affe5a7 100644--- a/tests/webui/test_settings_system.py+++ b/tests/webui/test_settings_system.py@@ -1,6 +1,11 @@from __future__ import annotations+import pytest++from nanobot.channels.contracts import channel_default_config, channel_instance_specs+from nanobot.channels.manager import ChannelManagerfrom nanobot.channels.registry import load_channel_plugin+from nanobot.config.loader import load_config, save_configfrom nanobot.config.schema import Configfrom nanobot.webui.settings_system import (coerce_channel_value,@@ -65,3 +70,48 @@ def test_channel_secret_is_cleared_only_by_explicit_null() -> None:assert saved == ["channels.matrix.password"]assert config.channels.matrix["password"] == ""++[email protected]("existing_key", ["showCompactionNotices", "show_compaction_notices"])+def test_compaction_notice_webui_contract_and_config_round_trip(existing_key, tmp_path):+ name = "qq"+ plugin = load_channel_plugin(name)+ spec = plugin.setup+ field = next(item for item in spec.to_public_dict(name)["fields"]+ if item["field"] == "showCompactionNotices")+ assert field["kind"] == "bool"+ assert field["inheritable"] is True+ assert "default_value" not in field+ assert channel_default_config(plugin).get("showCompactionNotices") is None+ config = Config.model_validate({+ "channels": {"showCompactionNotices": True, name: {existing_key: False}},+ })+ key = f"channels.{name}.showCompactionNotices"+ manager = ChannelManager.__new__(ChannelManager)+ # The generic settings route must preserve false, true and a return to inheritance.+ for submitted, expected in [("false", False), ("true", True), ("", None), (None, None)]:+ save_channel_config_values(+ config, name, {key: submitted}, load_channel_plugin=load_channel_plugin,+ )+ config_path = tmp_path / "config.json"+ save_config(config, config_path)+ config = load_config(config_path)+ assert config.channels.show_compaction_notices is True+ section = getattr(config.channels, name)+ [instance] = channel_instance_specs(plugin, section, enabled_only=False)+ assert instance.config.get("showCompactionNotices") is expected+ assert "show_compaction_notices" not in instance.config+ if expected is None:+ # Inheritance is persisted as absence, also readable by older QQ versions.+ assert "showCompactionNotices" not in instance.config+ assert manager._resolve_bool_override(+ instance.config, "show_compaction_notices", True,+ ) is (True if expected is None else expected)+++def test_saving_other_qq_settings_does_not_pin_the_global_notice_policy():+ config = Config.model_validate({"channels": {"showCompactionNotices": True}})+ save_channel_config_values(+ config, "qq", {"appId": "a", "secret": "s"}, load_channel_plugin=load_channel_plugin,+ )+ assert config.channels.qq.get("showCompactionNotices") is Nonediff --git a/webui/src/components/settings/channels/ChannelIdentity.tsx b/webui/src/components/settings/channels/ChannelIdentity.tsxindex 6a1f84393..f578b228c 100644--- a/webui/src/components/settings/channels/ChannelIdentity.tsx+++ b/webui/src/components/settings/channels/ChannelIdentity.tsx@@ -1,3 +1,4 @@+import i18n from "i18next";import { useMemo, type ReactNode } from "react";import { useTranslation } from "react-i18next";@@ -80,7 +81,9 @@ export function channelSetup(const choiceLabels = setupMessages?.fields?.[channelFieldMessageKey(feature.name, field.key)]?.choices ?? {};- const choices = field.kind === "bool" ? ["true", "false"] : field.choices;+ const choices = field.kind === "bool"+ ? (field.inheritable ? ["", "true", "false"] : ["true", "false"])+ : field.choices;return {...copy,key: field.key,@@ -95,7 +98,9 @@ export function channelSetup(field.kind === "enum" || field.kind === "bool"? choices.map((choice) => ({value: choice,- label: choiceLabels[choice] ?? fieldLabel(choice),+ label: choiceLabels[choice] ?? (choice === ""+ ? i18n.t("settings.values.default", { lng: locale, ns: "common" })+ : fieldLabel(choice)),})): undefined,};diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.tsindex e62a4025b..5140e2e0b 100644--- a/webui/src/lib/types.ts+++ b/webui/src/lib/types.ts@@ -1018,6 +1018,7 @@ export interface ChannelSetupContractField {choices: string[];required: boolean;default_value?: string;+ inheritable?: boolean;}export interface ChannelSetupContract {diff --git a/webui/src/tests/channel-credential-form.test.tsx b/webui/src/tests/channel-credential-form.test.tsxindex 1904b3a91..53237bf50 100644--- a/webui/src/tests/channel-credential-form.test.tsx+++ b/webui/src/tests/channel-credential-form.test.tsx@@ -4,7 +4,9 @@ import { describe, expect, it, vi } from "vitest";import {CredentialForm,channelValuesForSubmit,+ defaultChannelFieldValues,} from "@/components/settings/channels/CredentialForm";+import { channelSetup } from "@/components/settings/channels/ChannelIdentity";import type { ChannelConfigField } from "@/components/settings/channels/catalog";const fields: ChannelConfigField[] = [@@ -24,6 +26,34 @@ const fields: ChannelConfigField[] = [];describe("CredentialForm", () => {+ it("preserves inherited notices and lets an explicit override return to the default", () => {+ const key = "channels.qq.showCompactionNotices";+ const setup = channelSetup({+ name: "qq", display_name: "QQ", type: "channel", enabled: false,+ installed: true, ready: false, status: "not_enabled",+ install_supported: true, requires_restart: false,+ setup: { fields: [{+ key, field: "showCompactionNotices", kind: "bool", choices: [],+ required: false, inheritable: true,+ }] },+ });+ const noticeFields = setup.fields!;+ expect(defaultChannelFieldValues(noticeFields)).toEqual({ [key]: "" });+ expect(channelValuesForSubmit(noticeFields, {}, new Set())).toEqual({});+ expect(defaultChannelFieldValues(noticeFields, { [key]: "false" })).toEqual({ [key]: "false" });+ expect(channelValuesForSubmit(noticeFields, { [key]: "true" }, new Set([key])))+ .toEqual({ [key]: "true" });+ expect(channelValuesForSubmit(noticeFields, { [key]: "" }, new Set([key])))+ .toEqual({ [key]: "" });++ const onChange = vi.fn();+ render(<CredentialForm fields={noticeFields} values={{ [key]: "false" }}+ visibleSecrets={{}} onChange={onChange} onToggleSecret={vi.fn()} />);+ expect(screen.getByRole("radio", { name: "Off" })).toBeChecked();+ fireEvent.click(screen.getByRole("radio", { name: "Default" }));+ expect(onChange).toHaveBeenCalledWith(key, "");+ });+it("uses native radio semantics for option fields", () => {const onChange = vi.fn();render(diff --git a/webui/src/tests/channel-identity.test.ts b/webui/src/tests/channel-identity.test.tsindex 80267811d..33a9e0271 100644--- a/webui/src/tests/channel-identity.test.ts+++ b/webui/src/tests/channel-identity.test.ts@@ -24,6 +24,32 @@ function feature(overrides: Partial<NanobotFeatureInfo>): NanobotFeatureInfo {}describe("channelSetup", () => {+ it("offers a localized inherited option without changing ordinary booleans", () => {+ const setup = channelSetup(feature({ setup: { fields: [+ {+ key: "channels.plugin-chat.showCompactionNotices",+ field: "showCompactionNotices",+ kind: "bool",+ choices: [],+ required: false,+ inheritable: true,+ },+ {+ key: "channels.plugin-chat.sendProgress",+ field: "sendProgress",+ kind: "bool",+ choices: [],+ required: false,+ },+ ] } }), "zh-CN");+ expect(setup.fields?.[0]?.options).toEqual([+ { value: "", label: "默认" },+ { value: "true", label: "True" },+ { value: "false", label: "False" },+ ]);+ expect(setup.fields?.[1]?.options?.map((option) => option.value)).toEqual(["true", "false"]);+ });+it("builds editable fields for a plugin-owned backend contract", () => {const setup = channelSetup(feature({setup: {