Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(channels): apply noop config edits in place without reconnecting

shadowinlifeaa814430bb8e
diff --git a/agent/src/api/channels_config_routes.py b/agent/src/api/channels_config_routes.py
index edc849be7..b974c3eb3 100644
--- a/agent/src/api/channels_config_routes.py
+++ b/agent/src/api/channels_config_routes.py
@@ -357,7 +357,13 @@ async def _hot_apply(name: str, section: dict[str, Any] | None) -> str:
async def _apply_update(name: str, payload: ChannelConfigUpdateRequest) -> dict[str, Any]:
- """Validate → optional enable-transition probe → write → hot apply."""
+ """Validate → optional enable-transition probe → write → apply.
+
+ The response ``applied`` field reports how the edit reached the runtime:
+ ``refreshed`` (a noop-key edit applied in place, no reconnect),
+ ``hot_swapped`` (adapter stop+start), ``reset`` (full runtime rebuild), or
+ ``deferred`` (no runtime yet; the next start reads disk).
+ """
stored = _stored_section(name)
patch = _normalize_nullable_blanks(name, _patch_of(name, payload.config))
clears = _clear_flags(payload.model_extra)
@@ -402,6 +408,20 @@ async def _apply_update(name: str, payload: ChannelConfigUpdateRequest) -> dict[
) from None
fresh = _stored_section(name)
+ # Noop-key edits (declared keys + manager bool overrides) are read live per
+ # message, so refresh in place; ``enabled`` never qualifies (start/stop, #1625).
+ changed = set(patch) | set(clears)
+ noop_keys = cls.hot_reload_noop_keys | _MANAGER_OVERRIDE_KEYS
+ runtime = getattr(_host(), "_channel_runtime", None)
+ if (
+ changed
+ and changed <= noop_keys
+ and runtime is not None
+ and runtime.status().get("running")
+ and runtime.manager.get_channel(name) is not None
+ and await runtime.manager.refresh_channel_config(name, fresh)
+ ):
+ return {"channel": _fresh_entry(name), "applied": "refreshed"}
applied = await _hot_apply(name, fresh or None)
return {"channel": _fresh_entry(name), "applied": applied}
diff --git a/agent/src/channels/base.py b/agent/src/channels/base.py
index 36f957049..0a822265a 100644
--- a/agent/src/channels/base.py
+++ b/agent/src/channels/base.py
@@ -33,6 +33,12 @@ class BaseChannel(ABC):
supports_connection_test: ClassVar[bool] = False
+ # Config keys a running adapter absorbs in place (no stop+start): those read
+ # live per message (``self.config.X``) rather than captured into the SDK
+ # client at ``start()``. Empty default keeps undeclared channels on the full
+ # reload path; ``enabled``/connection keys are never declared (#1625).
+ hot_reload_noop_keys: ClassVar[frozenset[str]] = frozenset()
+
# Scheduled delivery is channel-agnostic at the scheduler layer. Adapters
# describe the address they accept so generic UIs never need to hard-code
# channel names or ask users to guess provider-specific target formats.
@@ -82,6 +88,25 @@ class BaseChannel(ABC):
"""
return {"ok": False, "code": "unsupported"}
+ def refresh_config(self, section: dict[str, Any]) -> bool:
+ """Swap in *section* without reconnecting; False if validation fails.
+
+ Re-validates via the same path ``__init__`` used (the config model's
+ ``model_validate``, else a dict copy). Only ``hot_reload_noop_keys``
+ reach here, so live reads see new values while the connection stays up;
+ on error the old config is kept and the caller does a full reload.
+ """
+ try:
+ model_cls = type(self.config)
+ if hasattr(model_cls, "model_validate"):
+ self.config = model_cls.model_validate(section)
+ else:
+ self.config = dict(section)
+ except Exception: # noqa: BLE001 - a rejected section must not strand the adapter
+ logger.debug("refresh_config rejected section for %s", self.name, exc_info=True)
+ return False
+ return True
+
@abstractmethod
async def start(self) -> None:
"""Start the channel and begin listening for messages.
diff --git a/agent/src/channels/dingtalk.py b/agent/src/channels/dingtalk.py
index 50ed594dd..42551c83f 100644
--- a/agent/src/channels/dingtalk.py
+++ b/agent/src/channels/dingtalk.py
@@ -191,6 +191,7 @@ class DingTalkChannel(BaseChannel):
name = "dingtalk"
display_name = "DingTalk"
supports_connection_test = True
+ hot_reload_noop_keys = frozenset({"allow_from"})
_ZIP_BEFORE_UPLOAD_EXTS = {".htm", ".html"}
@classmethod
diff --git a/agent/src/channels/discord.py b/agent/src/channels/discord.py
index db2065b4f..d80c27e49 100644
--- a/agent/src/channels/discord.py
+++ b/agent/src/channels/discord.py
@@ -358,6 +358,7 @@ class DiscordChannel(BaseChannel):
delivery_target_label = "Discord channel"
delivery_target_kind = "channel"
delivery_target_placeholder = "Channel ID"
+ hot_reload_noop_keys = frozenset({"allow_from", "read_receipt_emoji", "working_emoji", "working_emoji_delay"})
_STREAM_EDIT_INTERVAL = 0.8
@classmethod
diff --git a/agent/src/channels/email.py b/agent/src/channels/email.py
index e499b383d..f97e9e236 100644
--- a/agent/src/channels/email.py
+++ b/agent/src/channels/email.py
@@ -122,6 +122,7 @@ class EmailChannel(BaseChannel):
delivery_target_placeholder = "[email protected]"
delivery_target_input_type = "email"
supports_connection_test = True
+ hot_reload_noop_keys = frozenset({"allow_from"})
_IMAP_MONTHS = (
"Jan",
"Feb",
diff --git a/agent/src/channels/feishu.py b/agent/src/channels/feishu.py
index ece3e3d71..bbc86be0d 100644
--- a/agent/src/channels/feishu.py
+++ b/agent/src/channels/feishu.py
@@ -616,6 +616,7 @@ class FeishuChannel(BaseChannel):
name = "feishu"
display_name = "Feishu"
supports_connection_test = True
+ hot_reload_noop_keys = frozenset({"allow_from", "react_emoji", "done_emoji", "tool_hint_prefix"})
_STREAM_EDIT_INTERVAL = 0.5 # throttle between CardKit streaming updates
_WS_CLOSE_TIMEOUT_S = 3.0 # bound for the best-effort socket close in stop()
diff --git a/agent/src/channels/manager.py b/agent/src/channels/manager.py
index 26dda0f1d..cf1f937bd 100644
--- a/agent/src/channels/manager.py
+++ b/agent/src/channels/manager.py
@@ -299,6 +299,26 @@ class ChannelManager:
async with self._reload_locks[name]:
return await self._reload_channel_locked(name, section)
+ async def refresh_channel_config(self, name: str, section: dict) -> bool:
+ """Apply a noop-key config edit in place; False if not built or rejected."""
+ # Same lock as reload_channel: a refresh and a reload of one channel
+ # must not interleave (the reason _reload_locks exists).
+ async with self._reload_locks[name]:
+ channel = self.channels.get(name)
+ if channel is None or not channel.refresh_config(section):
+ return False
+ channel.send_progress = self._resolve_bool_override(
+ section, "send_progress", self._global_bool("send_progress", True),
+ )
+ channel.send_tool_hints = self._resolve_bool_override(
+ section, "send_tool_hints", self._global_bool("send_tool_hints", False),
+ )
+ channel.show_reasoning = self._resolve_bool_override(
+ section, "show_reasoning", self._global_bool("show_reasoning", True),
+ )
+ self._store_channel_section(name, section)
+ return True
+
async def _reload_channel_locked(self, name: str, section: dict | None) -> dict[str, Any]:
old = self.channels.get(name)
if old is not None:
diff --git a/agent/src/channels/matrix.py b/agent/src/channels/matrix.py
index 1d0cdf800..5c11b0241 100644
--- a/agent/src/channels/matrix.py
+++ b/agent/src/channels/matrix.py
@@ -217,6 +217,7 @@ class MatrixChannel(BaseChannel):
name = "matrix"
display_name = "Matrix"
+ hot_reload_noop_keys = frozenset({"allow_from"})
_STREAM_EDIT_INTERVAL = 2 # min seconds between edit_message_text calls
monotonic_time = time.monotonic
diff --git a/agent/src/channels/mochat.py b/agent/src/channels/mochat.py
index e2c907b1f..77fdabcb4 100644
--- a/agent/src/channels/mochat.py
+++ b/agent/src/channels/mochat.py
@@ -261,6 +261,7 @@ class MochatChannel(BaseChannel):
name = "mochat"
display_name = "Mochat"
+ hot_reload_noop_keys = frozenset({"allow_from"})
@classmethod
def default_config(cls) -> dict[str, Any]:
diff --git a/agent/src/channels/msteams.py b/agent/src/channels/msteams.py
index de60f6397..e79a2974e 100644
--- a/agent/src/channels/msteams.py
+++ b/agent/src/channels/msteams.py
@@ -136,6 +136,7 @@ class MSTeamsChannel(BaseChannel):
name = "msteams"
display_name = "Microsoft Teams"
+ hot_reload_noop_keys = frozenset({"allow_from"})
@classmethod
def default_config(cls) -> dict[str, Any]:
diff --git a/agent/src/channels/napcat.py b/agent/src/channels/napcat.py
index a5ff17375..de6b4e7b5 100644
--- a/agent/src/channels/napcat.py
+++ b/agent/src/channels/napcat.py
@@ -58,6 +58,7 @@ class NapcatChannel(BaseChannel):
name = "napcat"
display_name = "Napcat (QQ)"
+ hot_reload_noop_keys = frozenset({"allow_from"})
@classmethod
def default_config(cls) -> dict[str, Any]:
diff --git a/agent/src/channels/qq.py b/agent/src/channels/qq.py
index cb122ab04..3870feed7 100644
--- a/agent/src/channels/qq.py
+++ b/agent/src/channels/qq.py
@@ -152,6 +152,7 @@ class QQChannel(BaseChannel):
name = "qq"
display_name = "QQ"
supports_connection_test = True
+ hot_reload_noop_keys = frozenset({"allow_from"})
@classmethod
def default_config(cls) -> dict[str, Any]:
diff --git a/agent/src/channels/signal.py b/agent/src/channels/signal.py
index a5d9e1ef0..4109e2c20 100644
--- a/agent/src/channels/signal.py
+++ b/agent/src/channels/signal.py
@@ -369,6 +369,7 @@ class SignalChannel(BaseChannel):
name = "signal"
display_name = "Signal"
+ hot_reload_noop_keys = frozenset({"allow_from"})
_TYPING_REFRESH_SECONDS = 10.0
_MAX_MESSAGE_LEN = 64_000 # signal-cli practical limit (protocol max ~64 KB)
_HTTP_TIMEOUT_SECONDS = 60.0
diff --git a/agent/src/channels/slack.py b/agent/src/channels/slack.py
index bc574f2ef..e0b5d1ada 100644
--- a/agent/src/channels/slack.py
+++ b/agent/src/channels/slack.py
@@ -76,6 +76,7 @@ class SlackChannel(BaseChannel):
delivery_target_label = "Slack destination"
delivery_target_kind = "slack_destination"
delivery_target_placeholder = "#channel, @user, or conversation ID"
+ hot_reload_noop_keys = frozenset({"allow_from", "react_emoji", "done_emoji"})
_SLACK_ID_RE = re.compile(r"^[CDGUW][A-Z0-9]{2,}$")
_SLACK_CHANNEL_REF_RE = re.compile(r"^<#([A-Z0-9]+)(?:\|[^>]+)?>$")
_SLACK_USER_REF_RE = re.compile(r"^<@([A-Z0-9]+)(?:\|[^>]+)?>$")
diff --git a/agent/src/channels/telegram.py b/agent/src/channels/telegram.py
index 508fb3ea9..97ef6f205 100644
--- a/agent/src/channels/telegram.py
+++ b/agent/src/channels/telegram.py
@@ -433,6 +433,7 @@ class TelegramChannel(BaseChannel):
delivery_target_label = "Telegram chat"
delivery_target_kind = "chat"
delivery_target_placeholder = "Chat, group, or user ID"
+ hot_reload_noop_keys = frozenset({"allow_from", "react_emoji"})
def delivery_target_suggestions(self) -> list[dict[str, str]]:
"""Suggest numeric private chats already authorized in allow_from."""
diff --git a/agent/src/channels/websocket.py b/agent/src/channels/websocket.py
index 2e614b615..3707fd4dc 100644
--- a/agent/src/channels/websocket.py
+++ b/agent/src/channels/websocket.py
@@ -268,6 +268,7 @@ class WebSocketChannel(BaseChannel):
name = "websocket"
display_name = "WebSocket"
supports_connection_test = True
+ hot_reload_noop_keys = frozenset({"allow_from"})
def __init__(
self,
diff --git a/agent/src/channels/wecom.py b/agent/src/channels/wecom.py
index 2068a72d4..4850b5de7 100644
--- a/agent/src/channels/wecom.py
+++ b/agent/src/channels/wecom.py
@@ -82,6 +82,7 @@ class WecomChannel(BaseChannel):
name = "wecom"
display_name = "WeCom"
+ hot_reload_noop_keys = frozenset({"allow_from"})
@classmethod
def default_config(cls) -> dict[str, Any]:
diff --git a/agent/src/channels/weixin.py b/agent/src/channels/weixin.py
index 4d1286434..fcbcbd42f 100644
--- a/agent/src/channels/weixin.py
+++ b/agent/src/channels/weixin.py
@@ -142,6 +142,7 @@ class WeixinChannel(BaseChannel):
name = "weixin"
display_name = "WeChat"
+ hot_reload_noop_keys = frozenset({"allow_from"})
@classmethod
def default_config(cls) -> dict[str, Any]:
diff --git a/agent/src/channels/whatsapp.py b/agent/src/channels/whatsapp.py
index 0562b1025..f01720e0d 100644
--- a/agent/src/channels/whatsapp.py
+++ b/agent/src/channels/whatsapp.py
@@ -271,6 +271,7 @@ class WhatsAppChannel(BaseChannel):
name = "whatsapp"
display_name = "WhatsApp"
+ hot_reload_noop_keys = frozenset({"allow_from"})
@classmethod
def default_config(cls) -> dict[str, Any]:
diff --git a/agent/tests/test_channel_authoring_contract.py b/agent/tests/test_channel_authoring_contract.py
index 614d838e6..2cfbf7721 100644
--- a/agent/tests/test_channel_authoring_contract.py
+++ b/agent/tests/test_channel_authoring_contract.py
@@ -16,14 +16,14 @@ from pathlib import Path
import pytest
-from src.channels.config_meta import channel_field_hints, split_values_secrets
+from src.channels.config_meta import channel_field_hints, is_secret_key, split_values_secrets
from src.channels.registry import discover_channel_names, load_channel_class
[email protected]("name", discover_channel_names())
-def test_every_discovered_channel_satisfies_the_authoring_contract(name) -> None:
+def _load_channel_class_or_skip(name: str):
+ """Load a discovered channel; skip only on a genuine missing-dependency envelope."""
try:
- cls = load_channel_class(name)
+ return load_channel_class(name)
except ImportError as exc:
# Only the adapter's explicit missing-dependency envelope can skip.
# An arbitrary import or missing BaseChannel subclass must fail.
@@ -36,6 +36,11 @@ def test_every_discovered_channel_satisfies_the_authoring_contract(name) -> None
raise
pytest.skip(str(exc))
+
[email protected]("name", discover_channel_names())
+def test_every_discovered_channel_satisfies_the_authoring_contract(name) -> None:
+ cls = _load_channel_class_or_skip(name)
+
# A concrete adapter: start/stop/send are abstract on BaseChannel.
assert not cls.__abstractmethods__, f"{name} leaves BaseChannel abstracts unset"
@@ -72,3 +77,19 @@ def test_test_connection_envelope_shape_is_documented_by_default() -> None:
assert "test_connection" not in BaseChannel.__abstractmethods__
assert asyncio.run(BaseChannel.test_connection(None)) == {"ok": False, "code": "unsupported"}
+
+
[email protected]("name", discover_channel_names())
+def test_declared_noop_keys_are_real_non_secret_non_enabled(name) -> None:
+ """Every ``hot_reload_noop_keys`` entry is a real, non-secret, non-enabled key.
+
+ A noop key is applied to a running adapter without reconnecting, so it must
+ be an ordinary config field the adapter reads live — never ``enabled`` (a
+ start/stop transition) nor a secret (which must not be applied in place).
+ """
+ cls = _load_channel_class_or_skip(name)
+ defaults = cls.default_config()
+ for key in cls.hot_reload_noop_keys:
+ assert key in defaults, f"{name} declares noop key '{key}' absent from default_config()"
+ assert not is_secret_key(name, key), f"{name} declares secret '{key}' as a noop key"
+ assert key != "enabled", f"{name} declares 'enabled' noop (it drives start/stop)"
diff --git a/agent/tests/test_channel_noop_refresh.py b/agent/tests/test_channel_noop_refresh.py
new file mode 100644
index 000000000..3e4d7fb34
--- /dev/null
+++ b/agent/tests/test_channel_noop_refresh.py
@@ -0,0 +1,288 @@
+"""Contracts for noop-key in-place config refresh (F1, #1625).
+
+A PUT that changes only keys a channel declares in ``hot_reload_noop_keys``
+(or the manager bool overrides) is applied in place through
+``ChannelManager.refresh_channel_config`` — the adapter is never stopped — and
+the route reports ``applied: "refreshed"``. Any other key, the ``enabled``
+transition, or a rejected refresh falls back to the full hot-swap path.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi.testclient import TestClient
+
+import api_server
+import src.channels.manager as manager_module
+from src.api import channels_config_routes as routes
+from src.channels.base import BaseChannel
+from src.channels.bus.queue import MessageBus
+from src.channels.feishu import FeishuChannel, FeishuConfig
+from src.channels.manager import ChannelManager
+
+CLIENT_ID = "ding-client-id-1234567890"
+STORED_SECRET = "stored-secret-abcdefghij"
+
+
+# --------------------------------------------------------------------------- #
+# BaseChannel.refresh_config (planbook tests 1 + 2)
+# --------------------------------------------------------------------------- #
+
+
+def test_refresh_config_swaps_values_on_real_adapter() -> None:
+ """A valid section re-validates and swaps in place, keeping the model type."""
+ section_a = FeishuChannel.default_config()
+ channel = FeishuChannel(section_a, MessageBus())
+ assert channel.config.react_emoji == "THUMBSUP"
+
+ section_b = dict(section_a, react_emoji="DONE", done_emoji="OK", tool_hint_prefix="*")
+ assert channel.refresh_config(section_b) is True
+
+ assert channel.config.react_emoji == "DONE"
+ assert channel.config.done_emoji == "OK"
+ assert channel.config.tool_hint_prefix == "*"
+ assert type(channel.config) is FeishuConfig
+
+
+def test_refresh_config_rejects_invalid_section_preserving_old() -> None:
+ """A section that fails validation returns False and leaves the old config."""
+ section = FeishuChannel.default_config()
+ channel = FeishuChannel(section, MessageBus())
+ assert channel.refresh_config(dict(section, react_emoji="DONE")) is True
+ before = channel.config
+
+ # A list where a str field is declared fails model_validate.
+ assert channel.refresh_config(dict(section, react_emoji=[])) is False
+
+ assert channel.config is before
+ assert channel.config.react_emoji == "DONE"
+
+
+# --------------------------------------------------------------------------- #
+# ChannelManager.refresh_channel_config (planbook test 3)
+# --------------------------------------------------------------------------- #
+
+
+class _FakeChannel(BaseChannel):
+ """Concrete adapter stand-in; inherits the real ``refresh_config``."""
+
+ name = "fake"
+ display_name = "Fake"
+
+ def __init__(self, config: Any, bus: MessageBus, **kwargs: Any) -> None:
+ del kwargs
+ super().__init__(config, bus)
+ self.stop_calls = 0
+
+ async def start(self) -> None:
+ self._running = True
+
+ async def stop(self) -> None:
+ self.stop_calls += 1
+ self._running = False
+
+ async def send(self, msg: Any) -> None:
+ del msg
+
+
+def _fake_inspect_channels(config: Any) -> dict[str, dict[str, Any]]:
+ statuses: dict[str, dict[str, Any]] = {}
+ if not isinstance(config, dict):
+ return statuses
+ for name, section in config.items():
+ if not isinstance(section, dict):
+ continue
+ statuses[name] = {
+ "name": name,
+ "available": True,
+ "display_name": name.title(),
+ "install_hint": "",
+ "error": "",
+ "configured": True,
+ "enabled": bool(section.get("enabled")),
+ "loaded": False,
+ "running": False,
+ }
+ return statuses
+
+
+def _build_manager(monkeypatch: pytest.MonkeyPatch, config: dict[str, Any]) -> ChannelManager:
+ monkeypatch.setattr(manager_module, "discover_channel_names", lambda: ["fake"])
+ monkeypatch.setattr(manager_module, "load_channel_class", lambda name: _FakeChannel)
+ monkeypatch.setattr(manager_module, "inspect_channels", _fake_inspect_channels)
+ return ChannelManager(config, MessageBus())
+
+
+def test_manager_refresh_channel_config_reresolves_bool_overrides(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A refresh re-resolves the manager bool overrides without stopping the adapter."""
+
+ async def scenario() -> None:
+ manager = _build_manager(
+ monkeypatch, {"fake": {"enabled": True, "send_progress": True}}
+ )
+ channel = manager.channels["fake"]
+ assert channel.send_progress is True
+
+ result = await manager.refresh_channel_config(
+ "fake", {"enabled": True, "send_progress": False}
+ )
+
+ assert result is True
+ assert channel.send_progress is False
+ assert channel.stop_calls == 0
+ assert manager.config["fake"] == {"enabled": True, "send_progress": False}
+
+ # An unknown / not-built channel cannot be refreshed.
+ empty = _build_manager(monkeypatch, {})
+ assert await empty.refresh_channel_config("fake", {"enabled": True}) is False
+
+ asyncio.run(scenario())
+
+
+# --------------------------------------------------------------------------- #
+# PUT /channels/config/{name} routing (planbook test 4)
+# --------------------------------------------------------------------------- #
+
+
+class _FakeManager:
+ """Records refresh/reload calls; ``get_channel`` gates the refresh path."""
+
+ def __init__(self, *, refresh_ok: bool = True, live: bool = True) -> None:
+ self.refresh_calls: list[tuple[str, dict]] = []
+ self.reload_calls: list[tuple[str, dict | None]] = []
+ self._refresh_ok = refresh_ok
+ self._live = live
+
+ def get_channel(self, name: str) -> Any:
+ return object() if self._live else None
+
+ async def refresh_channel_config(self, name: str, section: dict) -> bool:
+ self.refresh_calls.append((name, section))
+ return self._refresh_ok
+
+ async def reload_channel(self, name: str, section: dict | None) -> dict[str, Any]:
+ self.reload_calls.append((name, section))
+ return {"loaded": bool(section and section.get("enabled"))}
+
+
+class _FakeRuntime:
+ """An authoritative running flag + manager, matching ChannelRuntime's surface."""
+
+ def __init__(self, *, running: bool, manager: _FakeManager) -> None:
+ self._running = running
+ self.manager = manager
+
+ def status(self) -> dict[str, Any]:
+ return {"running": self._running, "channels": {}}
+
+ async def start(self, *, start_manager: bool = True) -> None:
+ del start_manager
+
+ async def stop(self) -> None:
+ self._running = False
+
+
+def _write_agent_config(tmp_path: Path, channels: dict[str, Any]) -> Path:
+ path = tmp_path / "agent.json"
+ path.write_text(json.dumps({"channels": channels}), encoding="utf-8")
+ return path
+
+
+def _client(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ channels: dict[str, Any],
+ runtime: Any,
+) -> TestClient:
+ _write_agent_config(tmp_path, channels)
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path))
+ monkeypatch.setattr(api_server, "_channel_runtime", runtime)
+ monkeypatch.setattr(api_server, "_channel_bus", None)
+ monkeypatch.setattr(api_server, "_channel_manager", None)
+ monkeypatch.setattr(api_server, "_get_session_service", lambda: object())
+ return TestClient(api_server.app, client=("127.0.0.1", 50000))
+
+
[email protected](autouse=True)
+def _fresh_locks():
+ """Give every test unbound locks (asyncio.Lock binds to a loop on contention)."""
+ routes._channel_locks.clear()
+ routes._runtime_lock = asyncio.Lock()
+ yield
+ routes._channel_locks.clear()
+ routes._runtime_lock = asyncio.Lock()
+
+
+def _dingtalk_section(**overrides: Any) -> dict[str, Any]:
+ section: dict[str, Any] = {
+ "enabled": True,
+ "client_id": CLIENT_ID,
+ "client_secret": STORED_SECRET,
+ "allow_from": ["*"],
+ }
+ section.update(overrides)
+ return section
+
+
+def test_route_noop_only_edit_applies_refreshed_without_reload(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A noop-key-only PUT refreshes in place; the stop+start path never runs."""
+ manager = _FakeManager(refresh_ok=True, live=True)
+ runtime = _FakeRuntime(running=True, manager=manager)
+ client = _client(
+ tmp_path,
+ monkeypatch,
+ channels={"dingtalk": _dingtalk_section()},
+ runtime=runtime,
+ )
+
+ response = client.put(
+ "/channels/config/dingtalk", json={"config": {"allow_from": ["alice"]}}
+ )
+
+ assert response.status_code == 200
+ assert response.json()["applied"] == "refreshed"
+ assert [name for name, _ in manager.refresh_calls] == ["dingtalk"]
+ assert manager.reload_calls == []
+
+
+ "put_config, refresh_ok, expect_refresh_called",
+ [
+ ({"client_secret": "rotated-secret"}, True, False), # connection key
+ ({"enabled": False}, True, False), # start/stop transition
+ ({"allow_from": ["bob"]}, False, True), # refresh rejected -> fail-safe
+ ],
+)
+def test_route_falls_back_to_hot_apply(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ put_config: dict[str, Any],
+ refresh_ok: bool,
+ expect_refresh_called: bool,
+) -> None:
+ """A non-noop key, the enabled transition, or a rejected refresh hot-swaps."""
+ manager = _FakeManager(refresh_ok=refresh_ok, live=True)
+ runtime = _FakeRuntime(running=True, manager=manager)
+ client = _client(
+ tmp_path,
+ monkeypatch,
+ channels={"dingtalk": _dingtalk_section()},
+ runtime=runtime,
+ )
+
+ response = client.put("/channels/config/dingtalk", json={"config": put_config})
+
+ assert response.status_code == 200
+ assert response.json()["applied"] == "hot_swapped"
+ assert [name for name, _ in manager.reload_calls] == ["dingtalk"]
+ assert bool(manager.refresh_calls) is expect_refresh_called