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

+9 -3
View File
@@ -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 Behavior
+1 -1
View File
@@ -33,7 +33,7 @@ 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`.
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:
+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(
@@ -33,7 +33,9 @@ class _MockChannel(BaseChannel):
pass
async 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
):
return
return 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 contents
assert contents == ["Compressing context…", "Context compacted."]
@pytest.mark.parametrize("global_value", [False, True])
@pytest.mark.parametrize("override", [None, False, True])
@pytest.mark.parametrize("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_notices
@@ -17,7 +17,9 @@ pytest.importorskip("botpy")
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ContextCompactionEvent, outbound_message_for_event
from nanobot.bus.queue import MessageBus
from nanobot.channels.manager import ChannelManager
from nanobot.channels.qq.runtime import QQChannel, QQConfig
from nanobot.config.schema import Config
def _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
@pytest.mark.parametrize("global_value", [False, True])
@pytest.mark.parametrize("override", [None, False, True])
@pytest.mark.parametrize("typed", [False, True])
@pytest.mark.parametrize("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)
+50
View File
@@ -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 ChannelManager
from nanobot.channels.registry import load_channel_plugin
from nanobot.config.loader import load_config, save_config
from nanobot.config.schema import Config
from 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"] == ""
@pytest.mark.parametrize("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 None
@@ -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,
};
+1
View File
@@ -1018,6 +1018,7 @@ export interface ChannelSetupContractField {
choices: string[];
required: boolean;
default_value?: string;
inheritable?: boolean;
}
export interface ChannelSetupContract {
@@ -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(
+26
View File
@@ -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: {