Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(im): hot reconcile platform runtime
cyhf3c30ebf4347
diff --git a/config/platform_registry.py b/config/platform_registry.pyindex 207bc58fd..48f29938e 100644--- a/config/platform_registry.py+++ b/config/platform_registry.py@@ -38,6 +38,7 @@ class PlatformDescriptor:formatter_class: strcredential_fields: tuple[str, ...]capabilities: PlatformCapabilities+ runtime_reconcile_fields: tuple[str, ...] = ()# Structural distinction between real IM transports ("im") and the# always-on in-process Avibe Workbench ("workbench"), which lives in the# same registry but is never a configurable IM platform. IM-only code paths@@ -88,6 +89,9 @@ class PlatformDescriptor:formatter_cls = _load_attr(self.formatter_module, self.formatter_class)return formatter_cls()+ def runtime_reconcile_field_names(self) -> tuple[str, ...]:+ return self.runtime_reconcile_fields or self.credential_fields+def to_public_dict(self) -> dict[str, Any]:return {"id": self.id,@@ -127,6 +131,7 @@ PLATFORM_REGISTRY: dict[str, PlatformDescriptor] = {formatter_module="modules.im.formatters",formatter_class="SlackFormatter",credential_fields=("bot_token",),+ runtime_reconcile_fields=("bot_token", "app_token", "proxy_url"),capabilities=PlatformCapabilities(supports_channels=True,supports_threads=True,@@ -148,6 +153,7 @@ PLATFORM_REGISTRY: dict[str, PlatformDescriptor] = {formatter_module="modules.im.formatters",formatter_class="DiscordFormatter",credential_fields=("bot_token",),+ runtime_reconcile_fields=("bot_token", "proxy_url"),capabilities=PlatformCapabilities(supports_channels=True,supports_threads=True,@@ -169,6 +175,7 @@ PLATFORM_REGISTRY: dict[str, PlatformDescriptor] = {formatter_module="modules.im.formatters",formatter_class="TelegramFormatter",credential_fields=("bot_token",),+ runtime_reconcile_fields=("bot_token", "use_webhook", "webhook_url", "webhook_secret_token", "proxy_url"),capabilities=PlatformCapabilities(supports_channels=True,supports_threads=False,@@ -192,6 +199,7 @@ PLATFORM_REGISTRY: dict[str, PlatformDescriptor] = {formatter_module="modules.im.formatters",formatter_class="FeishuFormatter",credential_fields=("app_id", "app_secret"),+ runtime_reconcile_fields=("app_id", "app_secret", "domain", "proxy_url"),capabilities=PlatformCapabilities(supports_channels=True,supports_threads=True,@@ -214,6 +222,7 @@ PLATFORM_REGISTRY: dict[str, PlatformDescriptor] = {formatter_module="modules.im.formatters",formatter_class="WeChatFormatter",credential_fields=("bot_token",),+ runtime_reconcile_fields=("bot_token", "base_url", "cdn_base_url", "proxy_url"),capabilities=PlatformCapabilities(supports_channels=False,supports_threads=False,diff --git a/core/controller.py b/core/controller.pyindex d9340f80b..77c3cb89d 100644--- a/core/controller.py+++ b/core/controller.py@@ -68,6 +68,7 @@ class Controller:self._im_run_exception: Optional[BaseException] = Noneself.enabled_platforms = list(getattr(config, "enabled_platforms", lambda: [config.platform])())self.primary_platform = getattr(getattr(config, "platforms", None), "primary", config.platform)+ self._reconcile_lock: Optional[asyncio.Lock] = None# Session tracking (must be initialized before handlers)self.claude_sessions: Dict[str, Any] = {}@@ -143,52 +144,25 @@ class Controller:def _init_modules(self):"""Initialize core modules"""- self.im_clients: Dict[str, BaseIMClient] = IMFactory.create_clients(self.config)-- # Workbench-only install: no external IM platform is enabled, so- # ``create_clients`` returns an empty map. Register the in-process- # Avibe (Web UI) client as the SOLE client BEFORE the snapshot/primary- # access below so ``self.im_client`` resolves to it, ``self.im_clients- # [self.primary_platform]`` (== "avibe") works, and avibe joins the- # single-client run loop (its ``run()`` fires on_ready + blocks to keep- # the service alive — see ``modules/im/avibe.py``). The has-IM path is- # unaffected: avibe is added there AFTER the snapshot (further below) and- # stays OUT of the MultiIMClient run loop.- if not self.im_clients:- from modules.im.avibe import AvibeBot, AvibeConfig-- self.primary_platform = "avibe"- self.im_clients["avibe"] = AvibeBot(AvibeConfig())-- for platform, client in self.im_clients.items():+ runtime_clients: Dict[str, BaseIMClient] = IMFactory.create_clients(self.config)+ for platform, client in runtime_clients.items():client.formatter = self._create_formatter(platform)+ self.primary_platform = self._derive_primary_platform(self.config)+ self.im_client = MultiIMClient(dict(runtime_clients), primary_platform=self.primary_platform)+ self.im_clients = dict(runtime_clients)- # Snapshot the platform map for the multi-runtime wrapper. ``avibe``- # is registered into ``self.im_clients`` later (for delivery routing- # via get_im_client_for_context) but must NOT join the MultiIMClient- # run/callback loop — it has no inbound runtime, so a shared reference- # would let it leak in and log a spurious "IM runtime for avibe- # exited" warning. The copy keeps the run loop to the real platforms.- self.im_client = (- self.im_clients[self.primary_platform]- if len(self.im_clients) == 1- else MultiIMClient(dict(self.im_clients), primary_platform=self.primary_platform)- )- formatter = self.im_clients[self.primary_platform].formatter+ from modules.im.avibe import AvibeBot, AvibeConfig++ self.im_clients["avibe"] = AvibeBot(AvibeConfig())+ formatter = self.im_clients.get(self.primary_platform, self.im_clients["avibe"]).formatterself.claude_client = ClaudeClient(self.config.claude, formatter)# Initialize managersself.session_manager = SessionManager()- # The settings manager must own a per-platform manager for the primary- # so ``get_settings_manager_for_context`` (and its primary fallback) can- # always resolve one. For has-IM the primary is already in- # ``enabled_platforms`` so this is a no-op; for workbench-only it adds- # the "avibe" manager that empty ``enabled_platforms`` would otherwise- # omit (which would KeyError on the very first settings lookup).- settings_platforms = list(self.enabled_platforms)- if self.primary_platform not in settings_platforms:- settings_platforms.append(self.primary_platform)- self.settings_manager = MultiSettingsManager(settings_platforms, primary_platform=self.primary_platform)+ self.settings_manager = MultiSettingsManager(+ self._settings_platforms_for(self.enabled_platforms, self.primary_platform),+ primary_platform=self.primary_platform,+ )self.platform_settings_managers = self.settings_manager.managersself.sessions = self.settings_manager.sessionsself.native_session_service = None@@ -205,26 +179,29 @@ class Controller:for platform in self.enabled_platforms:if platform not in self.agent_router.platform_routes:self.agent_router.platform_routes[platform] = self.agent_router.platform_routes[self.primary_platform]+ if "avibe" not in self.agent_router.platform_routes:+ self.agent_router.platform_routes["avibe"] = self.agent_router.platform_routes[self.primary_platform]# Inject settings_manager into IM client if supported- for platform, client in self.im_clients.items():+ for platform, client in runtime_clients.items():self._inject_runtime_dependencies(platform, client)- # Avibe (the workbench Web UI) is always available as an in-process- # delivery surface, independent of which external IM platforms are- # enabled. Register it here — after ``self.im_client`` / callbacks /- # injection are wired for the real platforms — so- # ``get_im_client_for_context("avibe")`` resolves to the SSE-backed- # client instead of silently falling back to the primary platform- # (which mis-delivered workbench chat replies to e.g. Slack, where- # the send fails with channel_not_found and the user sees nothing).- # Avibe needs no inbound runtime thread (ui_server REST owns inbound),- # no settings-manager injection (it inherits the primary's via- # get_settings_manager_for_context), and no callbacks.- if "avibe" not in self.im_clients:- from modules.im.avibe import AvibeBot, AvibeConfig-- self.im_clients["avibe"] = AvibeBot(AvibeConfig())+ @staticmethod+ def _derive_primary_platform(config) -> str:+ enabled = list(getattr(config, "enabled_platforms", lambda: [getattr(config, "platform", "slack")])())+ configured_primary = getattr(getattr(config, "platforms", None), "primary", getattr(config, "platform", "slack"))+ if enabled:+ return configured_primary if configured_primary in enabled else enabled[0]+ return "avibe"++ @staticmethod+ def _settings_platforms_for(enabled_platforms: list[str], primary_platform: str) -> list[str]:+ platforms = list(enabled_platforms)+ if primary_platform not in platforms:+ platforms.append(primary_platform)+ if "avibe" not in platforms:+ platforms.append("avibe")+ return platformsdef _enabled_agent_backends(self) -> list[str]:result: list[str] = []@@ -248,6 +225,120 @@ class Controller:def _create_formatter(self, platform: str):return get_platform_descriptor(platform).create_formatter()+ @staticmethod+ def _runtime_reconcile_signature(config, platform: str) -> tuple[Any, ...]:+ descriptor = get_platform_descriptor(platform)+ platform_config = descriptor.get_config(config)+ if platform_config is None:+ return ()+ return tuple(getattr(platform_config, field, None) for field in descriptor.runtime_reconcile_field_names())++ def _ensure_agent_route_for_platform(self, platform: str) -> None:+ if platform in self.agent_router.platform_routes:+ return+ fallback = self.agent_router.platform_routes.get(self.primary_platform)+ if fallback is None:+ from modules.agent_router import PlatformRoute++ fallback = PlatformRoute(default=self.agent_router.global_default)+ self.agent_router.platform_routes[platform] = fallback++ def _register_client_runtime(self, platform: str, client: BaseIMClient) -> None:+ client.formatter = self._create_formatter(platform)+ if platform not in self.platform_settings_managers:+ self.settings_manager.add_platform(platform)+ self.platform_settings_managers = self.settings_manager.managers+ self._ensure_agent_route_for_platform(platform)+ self._inject_runtime_dependencies(platform, client)++ def _build_platform_client(self, platform: str, config) -> BaseIMClient:+ descriptor = get_platform_descriptor(platform)+ client = descriptor.create_client(config)+ self._register_client_runtime(platform, client)+ return client++ def _sync_config_references(self, new_config) -> None:+ self.config = new_config+ self.processing_indicator.config = new_config+ self.audio_asr_service.config = new_config+ for handler_name in ("command_handler", "settings_handler", "message_handler", "session_handler"):+ handler = getattr(self, handler_name, None)+ if handler is not None:+ handler.config = new_config+ handler.im_client = self.im_client+ handler.settings_manager = self.settings_manager+ handler.sessions = self.sessions+ for agent in getattr(getattr(self, "agent_service", None), "agents", {}).values():+ agent.config = new_config+ agent.im_client = self.im_client+ agent.settings_manager = self.settings_manager+ agent.sessions = self.sessions+ self.claude_client.config = new_config.claude+ primary_formatter = self.im_clients.get(self.primary_platform, self.im_clients["avibe"]).formatter+ if primary_formatter is not None:+ self.claude_client.formatter = primary_formatter++ async def reconcile_platforms(self, new_config) -> dict[str, Any]:+ """Hot-apply IM platform enablement and runtime credential changes."""+ if self._reconcile_lock is None:+ self._reconcile_lock = asyncio.Lock()++ async with self._reconcile_lock:+ current_enabled = list(self.enabled_platforms)+ next_enabled = list(getattr(new_config, "enabled_platforms", lambda: [])())+ current_set = set(current_enabled)+ next_set = set(next_enabled)+ removed = [platform for platform in current_enabled if platform not in next_set]+ added = [platform for platform in next_enabled if platform not in current_set]+ rebuilt = [+ platform+ for platform in next_enabled+ if platform in current_set+ and self._runtime_reconcile_signature(self.config, platform)+ != self._runtime_reconcile_signature(new_config, platform)+ ]+ next_primary = self._derive_primary_platform(new_config)++ for platform in removed + rebuilt:+ await asyncio.to_thread(self.im_client.remove_client, platform)+ self.im_clients.pop(platform, None)++ self.enabled_platforms = next_enabled+ self.primary_platform = next_primary+ self.settings_manager.set_primary_platform(next_primary)+ self.platform_settings_managers = self.settings_manager.managers+ for platform in removed:+ self.settings_manager.remove_platform(platform)+ self.agent_router.platform_routes.pop(platform, None)++ for platform in next_enabled:+ self._ensure_agent_route_for_platform(platform)+ self._ensure_agent_route_for_platform("avibe")++ for platform in rebuilt + added:+ client = self._build_platform_client(platform, new_config)+ self.im_clients[platform] = client+ self.im_client.add_client(platform, client)++ self.im_client.set_primary_platform(next_primary)+ self._sync_config_references(new_config)++ logger.info(+ "Hot-reconciled IM platforms: added=%s removed=%s rebuilt=%s primary=%s",+ added,+ removed,+ rebuilt,+ next_primary,+ )+ return {+ "ok": True,+ "added": added,+ "removed": removed,+ "rebuilt": rebuilt,+ "enabled": next_enabled,+ "primary": next_primary,+ }+def _migrate_discord_guild_scope_from_config(self) -> None:if "discord" not in self.platform_settings_managers:returndiff --git a/docs/plans/hot-platform-reconcile.md b/docs/plans/hot-platform-reconcile.mdindex ec1b60b64..17390a9c9 100644--- a/docs/plans/hot-platform-reconcile.md+++ b/docs/plans/hot-platform-reconcile.md@@ -29,14 +29,17 @@ platform's background task**, not bounce the whole service.1. **`MultiIMClient.add_client(platform, client)` / `remove_client(platform)`** —start one new daemon thread / signal-stop + join one thread, mutating`self.clients` + `self._threads` under a lock (routing reads must not see a- half-removed client).+ half-removed client). `run()` idles until explicit stop, even when the+ runtime client set is empty.2. **`Controller.reconcile_platforms(new_config)`** (async, on the loop) — diffthe new enabled set vs running and:- removed → `remove_client` + drop its settings manager;- added → build client via `IMFactory`/descriptor, formatter, settingsmanager, agent route, register callbacks, `add_client` (start its thread);+ - enabled + runtime credential/signature change → `remove_client` ++ `add_client` rebuild;- recompute `enabled_platforms` + the derived `primary_platform`;- - rebuild the single-vs-multi `im_client` wrapper if topology changed.+ - keep the single `MultiIMClient` wrapper alive for all topologies.Sync `stop()` calls wrapped in `asyncio.to_thread`/`call_soon_threadsafe`.3. **`POST /internal/reconcile-platforms`** on the internal server → calls`controller.reconcile_platforms`.@@ -44,6 +47,20 @@ platform's background task**, not bounce the whole service.changed, send the internal reconcile command instead of scheduling a restart.The platforms page stops calling `control('restart')` for enable/disable.+### Always-wrap / workbench-only shape++The controller and `IMFactory.create_client()` now always expose a+`MultiIMClient` runtime wrapper:++- 4-platform / 1-platform configs: wrapper owns those external IM clients.+- Workbench-only / disabled-all configs: wrapper owns zero external IM clients+ and idles; `AvibeBot` stays registered separately in `controller.im_clients`+ as the in-process delivery target.++This avoids single-vs-multi branching during reconcile and prevents disabling+all IM platforms from making `im_client.run()` return, which would otherwise+stop the controller loop.+## Per-adapter hot-stop verdict| Platform | Clean single-stop? | Notes |@@ -52,7 +69,7 @@ platform's background task**, not bounce the whole service.| Discord | ✅ | discord.py `client.close()` || Telegram | ✅ | polling loop breaks on event || WeChat | ✅ | poll-task cancel + stop event |-| **Feishu/Lark** | ⚠️ **No** | `run()` spawns a nested lark-SDK WS **daemon thread** with no exposed stop; hot-remove would leak that thread until process exit |+| **Feishu/Lark** | ✅ | lark-oapi exposes no public stop, so `FeishuBot.stop()` uses the SDK client's private async `_disconnect()`, then stops the SDK module event loop to release its infinite `_select()` sleep and joins the nested `feishu-ws` thread |## Decisions (locked — full scope, "一次到位")@@ -79,22 +96,9 @@ platform's background task**, not bounce the whole service.before its thread starts so early inbound isn't dropped.- Settings-manager file lifecycle for a newly added platform: lazy-load onfirst access (existing pattern).--## Incremental plan--- **Phase 2a** (this PR): MultiIMClient add/remove + reconcile for the 4 clean- adapters; Feishu + credential changes fall back to service-only restart;- internal command + `/api/config` trigger; tests (reconcile diff, add/remove,- fallback selection).-- **Phase 2b** (follow-up): Feishu adapter clean WS stop; hot credential- reconnect.--## Todo (2a)--- [ ] `MultiIMClient.add_client` / `remove_client` (+ lock around `clients`)-- [ ] `Controller.reconcile_platforms` + add/remove/update helpers-- [ ] `/internal/reconcile-platforms` endpoint + `internal_client` method-- [ ] `POST /api/config`: diff platform fields → reconcile (clean adapters) or- service-only restart (Feishu / credential change) fallback-- [ ] platforms page: skip restart when the change is hot-reconcilable-- [ ] tests + regression on all 5 IM platforms+- Feishu stop relies on lark-oapi private internals because the SDK has no+ public close API. Keep the test coverage around `_disconnect()` + loop stop so+ SDK upgrades fail loudly if those internals change.+- If the internal reconcile socket is unavailable after saving platform config,+ `/api/config` schedules the existing service-only restart fallback instead of+ leaving the persisted config unapplied.diff --git a/modules/im/avibe.py b/modules/im/avibe.pyindex febf59aed..b6be944f9 100644--- a/modules/im/avibe.py+++ b/modules/im/avibe.py@@ -12,7 +12,7 @@ This module ships the platform-side contract that the``core/handlers`` / ``message_dispatcher`` layer can call uniformlyacross every platform. The REST + SSE wiring lands in later commits andwill register itself with the ``AvibeBot`` instance held by the-controller (see ``IMFactory.create_client``).+controller (see ``Controller._init_modules``)."""from __future__ import annotationsdiff --git a/modules/im/factory.py b/modules/im/factory.pyindex e65cf5412..8c56ffa14 100644--- a/modules/im/factory.py+++ b/modules/im/factory.py@@ -14,19 +14,8 @@ class IMFactory:@staticmethoddef create_client(config) -> BaseIMClient:clients = IMFactory.create_clients(config)- # Workbench-only config (``platforms.enabled`` empty, or a legacy- # ``["avibe"]``): ``create_clients`` skips the in-process workbench, so- # the built map is empty. Return the in-process ``AvibeBot`` directly —- # mirroring the controller's avibe fallback (``_init_modules``) — instead- # of constructing ``MultiIMClient(clients={}, "avibe")``, which would- # raise because the primary is absent from the empty map.- if not clients:- from modules.im.avibe import AvibeBot, AvibeConfig-- return AvibeBot(AvibeConfig())- primary = getattr(getattr(config, "platforms", None), "primary", getattr(config, "platform", "slack"))- if len(clients) == 1 and primary in clients:- return clients[primary]+ configured_primary = getattr(getattr(config, "platforms", None), "primary", getattr(config, "platform", "slack"))+ primary = configured_primary if configured_primary in clients else (next(iter(clients)) if clients else "avibe")return MultiIMClient(clients, primary_platform=primary)@staticmethoddiff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex 3723c10d0..d87d8d95a 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -5,6 +5,7 @@ import ioimport jsonimport loggingimport os+import threadingimport timefrom typing import Any, Callable, Dict, List, Optional@@ -111,6 +112,7 @@ class FeishuBot(BaseIMClient):self._routing_cache: Dict[str, Dict[str, Any]] = {}self._stop_event: Optional[asyncio.Event] = Noneself._loop: Optional[asyncio.AbstractEventLoop] = None+ self._ws_thread: Optional[threading.Thread] = Noneself._recent_event_ids: Dict[str, float] = {}self._cached_token: Optional[str] = Noneself._token_expires_at: Optional[float] = None@@ -3252,8 +3254,6 @@ class FeishuBot(BaseIMClient):domain=self._get_sdk_domain(),)- import threading-def _ws_thread_target():try:logger.info("Feishu WS thread starting, domain=%s", self._get_sdk_domain())@@ -3262,6 +3262,7 @@ class FeishuBot(BaseIMClient):logger.error("Feishu WS thread crashed: %s", exc, exc_info=True)ws_thread = threading.Thread(target=_ws_thread_target, daemon=True, name="feishu-ws")+ self._ws_thread = ws_threadws_thread.start()logger.info("Feishu WebSocket client started")@@ -3283,17 +3284,56 @@ class FeishuBot(BaseIMClient):def stop(self) -> None:"""Signal the bot to stop."""- if self._stop_event is None:- return- if self._loop and self._loop.is_running():+ self._stop_ws_client()+ if self._loop and self._loop.is_running() and self._stop_event is not None:self._loop.call_soon_threadsafe(self._stop_event.set)- else:+ elif self._stop_event is not None:self._stop_event.set()+ self._join_ws_thread(timeout=5.0)++ def _stop_ws_client(self) -> None:+ ws_client = self._ws_client+ if ws_client is None:+ return+ disconnect = getattr(ws_client, "_disconnect", None)+ if not callable(disconnect):+ logger.warning("Feishu WS client has no disconnect hook; nested WS thread may leak")+ return+ try:+ import lark_oapi.ws.client as ws_client_module++ ws_loop = getattr(ws_client_module, "loop", None)+ if ws_loop is not None and ws_loop.is_running():+ future = asyncio.run_coroutine_threadsafe(disconnect(), ws_loop)+ future.result(timeout=5.0)+ # lark-oapi keeps the nested thread inside module-level+ # _select(), which is just an infinite sleep loop. Stopping the+ # SDK loop is the only available way to release Client.start().+ ws_loop.call_soon_threadsafe(ws_loop.stop)+ else:+ loop = ws_loop if ws_loop is not None and not ws_loop.is_closed() else asyncio.new_event_loop()+ if ws_loop is None:+ ws_client_module.loop = loop+ loop.run_until_complete(disconnect())+ except Exception:+ logger.exception("Failed to disconnect Feishu WS client")++ def _join_ws_thread(self, timeout: float) -> None:+ thread = self._ws_thread+ if thread is None or thread is threading.current_thread():+ return+ thread.join(timeout=timeout)+ if thread.is_alive():+ logger.warning("Feishu WS thread did not stop within %.1fs", timeout)+ else:+ self._ws_thread = Noneasync def shutdown(self) -> None:"""Best-effort async shutdown."""+ self._stop_ws_client()if self._stop_event is not None:self._stop_event.set()+ await asyncio.to_thread(self._join_ws_thread, 5.0)# ------------------------------------------------------------------# Misc required implementationsdiff --git a/modules/im/multi.py b/modules/im/multi.pyindex 45b416582..3c6bbeb7b 100644--- a/modules/im/multi.py+++ b/modules/im/multi.py@@ -19,11 +19,12 @@ class MultiIMClient(BaseIMClient):"""Delegate inbound/outbound messaging across multiple IM clients."""def __init__(self, clients: Dict[str, BaseIMClient], primary_platform: str):- if primary_platform not in clients:+ if clients and primary_platform not in clients:raise ValueError(f"Primary platform '{primary_platform}' is not in enabled clients")self.clients = clientsself.primary_platform = primary_platformself._threads: Dict[str, threading.Thread] = {}+ self._run_started = threading.Event()# Guards mutations of ``clients`` / ``_threads`` so the run() monitor# loop (IM worker thread) and runtime add/remove_client calls (the# reconcile path, on the asyncio loop) can't see a half-updated map.@@ -32,8 +33,38 @@ class MultiIMClient(BaseIMClient):self._ready_lock = threading.Lock()self._ready_platforms: set[str] = set()self._ready_emitted = False- super().__init__(clients[primary_platform].config)- self.formatter = clients[primary_platform].formatter+ self._registered_callbacks: Optional[tuple[Optional[Callable], Optional[Dict[str, Callable]], Optional[Callable], Dict[str, Any]]] = None+ if clients:+ super().__init__(clients[primary_platform].config)+ self.formatter = clients[primary_platform].formatter+ else:+ from config.v2_config import AvibeConfig++ super().__init__(AvibeConfig())+ self.formatter = None++ def _client_snapshot(self) -> Dict[str, BaseIMClient]:+ with self._clients_lock:+ return dict(self.clients)++ def _primary_client(self) -> BaseIMClient:+ with self._clients_lock:+ client = self.clients.get(self.primary_platform)+ if client is not None:+ return client+ if self.clients:+ return next(iter(self.clients.values()))+ raise ValueError("No IM platforms are enabled")++ def set_primary_platform(self, primary_platform: str) -> None:+ with self._clients_lock:+ if self.clients and primary_platform not in self.clients:+ raise ValueError(f"Primary platform '{primary_platform}' is not in enabled clients")+ self.primary_platform = primary_platform+ client = self.clients.get(primary_platform)+ if client is not None:+ self.config = client.config+ self.formatter = client.formatterdef _resolve_platform(self, context: Optional[MessageContext] = None) -> str:if context is not None:@@ -71,18 +102,27 @@ class MultiIMClient(BaseIMClient):return self.get_client(self._resolve_platform(context))def get_default_parse_mode(self) -> Optional[str]:- return self.clients[self.primary_platform].get_default_parse_mode()+ try:+ return self._primary_client().get_default_parse_mode()+ except ValueError:+ return Nonedef should_use_thread_for_reply(self) -> bool:+ clients = self._client_snapshot()+ if not clients:+ return Falsereturn (- len({client.should_use_thread_for_reply() for client in self.clients.values()}) == 1- and self.clients[self.primary_platform].should_use_thread_for_reply()+ len({client.should_use_thread_for_reply() for client in clients.values()}) == 1+ and self._primary_client().should_use_thread_for_reply())def should_use_thread_for_dm_session(self) -> bool:+ clients = self._client_snapshot()+ if not clients:+ return Falsereturn (- len({client.should_use_thread_for_dm_session() for client in self.clients.values()}) == 1- and self.clients[self.primary_platform].should_use_thread_for_dm_session()+ len({client.should_use_thread_for_dm_session() for client in clients.values()}) == 1+ and self._primary_client().should_use_thread_for_dm_session())def register_callbacks(@@ -96,22 +136,29 @@ class MultiIMClient(BaseIMClient):on_message=on_message, on_command=on_command, on_callback_query=on_callback_query, **kwargs)- for platform, client in self.clients.items():- wrapped_kwargs = {key: self._wrap_additional_callback(platform, value) for key, value in kwargs.items()}- wrapped_kwargs["on_ready"] = self._wrap_on_ready(platform, kwargs.get("on_ready"))- wrapped_commands: Optional[Dict[str, Callable]] = None- if on_command is not None:- wrapped_commands = {}- for name, handler in on_command.items():- wrapped = self._wrap_context_callback(platform, handler)- if wrapped is not None:- wrapped_commands[name] = cast(Callable, wrapped)- client.register_callbacks(- on_message=self._wrap_context_callback(platform, on_message),- on_command=wrapped_commands,- on_callback_query=self._wrap_callback_query(platform, on_callback_query),- **wrapped_kwargs,- )+ self._registered_callbacks = (on_message, on_command, on_callback_query, dict(kwargs))+ for platform, client in self._client_snapshot().items():+ self._register_client_callbacks(platform, client)++ def _register_client_callbacks(self, platform: str, client: BaseIMClient) -> None:+ if self._registered_callbacks is None:+ return+ on_message, on_command, on_callback_query, kwargs = self._registered_callbacks+ wrapped_kwargs = {key: self._wrap_additional_callback(platform, value) for key, value in kwargs.items()}+ wrapped_kwargs["on_ready"] = self._wrap_on_ready(platform, kwargs.get("on_ready"))+ wrapped_commands: Optional[Dict[str, Callable]] = None+ if on_command is not None:+ wrapped_commands = {}+ for name, handler in on_command.items():+ wrapped = self._wrap_context_callback(platform, handler)+ if wrapped is not None:+ wrapped_commands[name] = cast(Callable, wrapped)+ client.register_callbacks(+ on_message=self._wrap_context_callback(platform, on_message),+ on_command=wrapped_commands,+ on_callback_query=self._wrap_callback_query(platform, on_callback_query),+ **wrapped_kwargs,+ )def _wrap_additional_callback(self, platform: str, callback: Optional[Callable]) -> Optional[Callable]:if callback is None:@@ -164,9 +211,10 @@ class MultiIMClient(BaseIMClient):"Platform '%s' ready (%d/%d)",platform,len(self._ready_platforms),- len(self.clients),+ len(self._client_snapshot()),)- if not self._ready_emitted and len(self._ready_platforms) >= len(self.clients):+ client_count = len(self._client_snapshot())+ if client_count > 0 and not self._ready_emitted and len(self._ready_platforms) >= client_count:self._ready_emitted = Trueshould_fire = Trueif should_fire:@@ -174,6 +222,25 @@ class MultiIMClient(BaseIMClient):return _wrapped+ def _emit_empty_ready_once(self) -> None:+ callback = getattr(self, "on_ready_callback", None)+ if callback is None:+ return+ with self._ready_lock:+ if self._ready_emitted or self.clients:+ return+ self._ready_emitted = True++ async def _call_ready() -> None:+ result = callback()+ if inspect.isawaitable(result):+ await result++ try:+ asyncio.run(_call_ready())+ except Exception:+ logger.exception("MultiIMClient empty-runtime on_ready callback failed")+@staticmethoddef _annotate_context(platform: str, context: MessageContext) -> None:context.platform = platform@@ -205,7 +272,8 @@ class MultiIMClient(BaseIMClient):def supports_message_editing(self, context: Optional[MessageContext] = None) -> bool:if context is None:- return all(client.supports_message_editing() for client in self.clients.values())+ clients = self._client_snapshot()+ return bool(clients) and all(client.supports_message_editing() for client in clients.values())return self.get_client_for_context(context).supports_message_editing(context)async def upload_markdown(@@ -280,10 +348,11 @@ class MultiIMClient(BaseIMClient):return await self.clients[self.primary_platform].answer_callback(callback_id, text=text, show_alert=show_alert)def register_handlers(self):- for client in self.clients.values():+ for client in self._client_snapshot().values():client.register_handlers()def run(self):+ self._run_started.set()self._stop_requested.clear()with self._clients_lock:self._threads = {}@@ -291,6 +360,8 @@ class MultiIMClient(BaseIMClient):thread = threading.Thread(target=self._run_client, args=(platform, client), daemon=True)thread.start()self._threads[platform] = thread+ if not self.clients:+ self._emit_empty_ready_once()try:# Idle-loop until an explicit stop. The runtime stays alive even when@@ -312,6 +383,7 @@ class MultiIMClient(BaseIMClient):self.stop()for thread in list(self._threads.values()):thread.join(timeout=1.0)+ self._run_started.clear()@staticmethoddef _run_client(platform: str, client: BaseIMClient) -> None:@@ -331,10 +403,15 @@ class MultiIMClient(BaseIMClient):if platform in self.clients:logger.warning("add_client: platform %s already present; skipping", platform)return+ self._register_client_callbacks(platform, client)self.clients[platform] = client+ if self.primary_platform not in self.clients:+ self.primary_platform = platform+ self.config = client.config+ self.formatter = client.formatter# If the runtime isn't looping yet (pre-run / stopped), just register# the client — run() will start its thread. Otherwise start it now.- if not self._stop_requested.is_set():+ if self._run_started.is_set() and not self._stop_requested.is_set():thread = threading.Thread(target=self._run_client, args=(platform, client), daemon=True)thread.start()self._threads[platform] = thread@@ -350,8 +427,15 @@ class MultiIMClient(BaseIMClient):with self._clients_lock:client = self.clients.pop(platform, None)thread = self._threads.pop(platform, None)+ if platform == self.primary_platform and self.clients:+ next_platform, next_client = next(iter(self.clients.items()))+ self.primary_platform = next_platform+ self.config = next_client.config+ self.formatter = next_client.formatterif client is None:return None+ with self._ready_lock:+ self._ready_platforms.discard(platform)stop_attr = getattr(client, "stop", None)if callable(stop_attr) and not inspect.iscoroutinefunction(stop_attr):@@ -369,13 +453,13 @@ class MultiIMClient(BaseIMClient):async def get_user_info(self, user_id: str) -> Dict[str, Any]:platform, raw_user_id = _split_scoped_key(str(user_id))platform = platform or _infer_user_platform(user_id)- client = self.clients.get(platform, self.clients[self.primary_platform])+ client = self.clients.get(platform) or self._primary_client()return await client.get_user_info(raw_user_id)async def get_channel_info(self, channel_id: str) -> Dict[str, Any]:platform, raw_channel_id = _split_scoped_key(str(channel_id))platform = platform or _infer_channel_platform(channel_id)- client = self.clients.get(platform, self.clients[self.primary_platform])+ client = self.clients.get(platform) or self._primary_client()return await client.get_channel_info(raw_channel_id)async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:@@ -390,15 +474,21 @@ class MultiIMClient(BaseIMClient):async def clear_typing_indicator(self, context: MessageContext) -> bool:return await self.get_client_for_context(context).clear_typing_indicator(context)+ async def delete_message(self, context: MessageContext, message_id: str) -> bool:+ delete = getattr(self.get_client_for_context(context), "delete_message", None)+ if not callable(delete):+ return False+ return await delete(context, message_id)+async def send_dm(self, user_id: str, text: str, **kwargs):platform, raw_user_id = _split_scoped_key(str(user_id))platform = platform or _infer_user_platform(user_id)- client = self.clients.get(platform, self.clients[self.primary_platform])+ client = self.clients.get(platform) or self._primary_client()return await client.send_dm(raw_user_id, text, **kwargs)def stop(self):self._stop_requested.set()- for client in self.clients.values():+ for client in self._client_snapshot().values():stop_attr = getattr(client, "stop", None)if callable(stop_attr) and not inspect.iscoroutinefunction(stop_attr):try:@@ -412,7 +502,7 @@ class MultiIMClient(BaseIMClient):for thread in list(self._threads.values()):await asyncio.to_thread(thread.join, 2.0)- for client in self.clients.values():+ for client in self._client_snapshot().values():if any(thread.is_alive() for thread in self._threads.values()):breakshutdown_attr = getattr(client, "shutdown", None)@@ -426,4 +516,7 @@ class MultiIMClient(BaseIMClient):logger.exception("Failed to shutdown IM client")def format_markdown(self, text: str) -> str:- return self.clients[self.primary_platform].format_markdown(text)+ try:+ return self._primary_client().format_markdown(text)+ except ValueError:+ return textdiff --git a/modules/settings_manager.py b/modules/settings_manager.pyindex 56c7bc6c8..3fedf46f0 100644--- a/modules/settings_manager.py+++ b/modules/settings_manager.py@@ -484,6 +484,7 @@ class MultiSettingsManager:"""Route settings operations to per-platform managers using scoped keys."""def __init__(self, platforms: list[str], settings_file: Optional[str] = None, primary_platform: str = "slack"):+ self.settings_file = settings_fileself.platform = primary_platformself.primary_platform = primary_platformself.sessions_store = SessionsStore()@@ -500,6 +501,34 @@ class MultiSettingsManager:)for platform in platforms}+ if primary_platform not in self.managers:+ self.managers[primary_platform] = self._create_platform_manager(primary_platform)++ def _create_platform_manager(self, platform: str) -> SettingsManager:+ return SettingsManager(+ settings_file=self.settings_file,+ platform=platform,+ sessions_store=self.sessions_store,+ sessions_facade=self.sessions,+ )++ def add_platform(self, platform: str) -> SettingsManager:+ manager = self.managers.get(platform)+ if manager is None:+ manager = self._create_platform_manager(platform)+ self.managers[platform] = manager+ return manager++ def remove_platform(self, platform: str) -> None:+ if platform == self.primary_platform:+ return+ self.managers.pop(platform, None)++ def set_primary_platform(self, platform: str) -> None:+ if platform not in self.managers:+ self.add_platform(platform)+ self.platform = platform+ self.primary_platform = platformdef get_store(self) -> SettingsStore:return self.managers[self.primary_platform].get_store()diff --git a/tests/test_controller_platform_reconcile.py b/tests/test_controller_platform_reconcile.pynew file mode 100644index 000000000..6091e7524--- /dev/null+++ b/tests/test_controller_platform_reconcile.py@@ -0,0 +1,239 @@+from __future__ import annotations++import asyncio+from dataclasses import dataclass+from types import SimpleNamespace++from config.v2_config import DiscordConfig, LarkConfig, SlackConfig+from core.controller import Controller+from modules.agent_router import AgentRouter+from modules.im.base import BaseIMClient, BaseIMConfig, MessageContext+from modules.im.multi import MultiIMClient+from modules.settings_manager import MultiSettingsManager+++@dataclass+class _StubConfig(BaseIMConfig):+ name: str = ""++ def validate(self) -> None:+ return None+++class _Formatter:+ def format_error(self, text: str) -> str:+ return text+++class _Client(BaseIMClient):+ def __init__(self, name: str, config: BaseIMConfig | None = None):+ super().__init__(config or _StubConfig(name=name))+ self.name = name+ self.stopped = False+ self.settings_manager = None+ self.controller = None++ def set_settings_manager(self, settings_manager):+ self.settings_manager = settings_manager++ def set_controller(self, controller):+ self.controller = controller++ async def send_message(self, context, text, parse_mode=None, reply_to=None):+ return self.name++ async def send_message_with_buttons(self, context, text, keyboard, parse_mode=None):+ return self.name++ async def edit_message(self, context, message_id, text=None, keyboard=None, parse_mode=None):+ return True++ async def answer_callback(self, callback_id, text=None, show_alert=False):+ return True++ def register_handlers(self):+ return None++ def run(self):+ return None++ def stop(self):+ self.stopped = True++ async def get_user_info(self, user_id: str):+ return {"id": user_id}++ async def get_channel_info(self, channel_id: str):+ return {"id": channel_id}++ def format_markdown(self, text: str) -> str:+ return text+++async def _noop(*args, **kwargs):+ return None+++def _handler(**overrides):+ methods = {+ "handle_start",+ "handle_new",+ "handle_cwd",+ "handle_set_cwd",+ "handle_resume",+ "handle_setup",+ "handle_stop",+ "handle_bind",+ "handle_change_cwd_submission",+ "handle_settings",+ "handle_settings_update",+ "handle_routing_update",+ "handle_routing_modal_update",+ "handle_callback_query",+ "handle_resume_session_submission",+ }+ values = {name: _noop for name in methods}+ values.update(overrides)+ return SimpleNamespace(**values)+++class _Descriptor:+ def __init__(self, platform: str):+ self.id = platform+ self.config_key = platform+ self.credential_fields = ("bot_token",)++ def runtime_reconcile_field_names(self):+ if self.id == "lark":+ return ("app_id", "app_secret", "domain")+ return ("bot_token",)++ def get_config(self, config):+ return getattr(config, self.id)++ def create_client(self, config):+ return _Client(self.id, self.get_config(config))++ def create_formatter(self):+ return _Formatter()+++def _config(+ enabled: list[str],+ *,+ primary: str | None = None,+ slack_token: str = "xoxb-old",+ discord_token: str = "discord-old-token",+ lark_secret: str = "lark-old-secret",+):+ primary = primary or (enabled[0] if enabled else "avibe")+ return SimpleNamespace(+ platform=primary,+ platforms=SimpleNamespace(enabled=enabled, primary=primary),+ enabled_platforms=lambda: list(enabled),+ slack=SlackConfig(bot_token=slack_token),+ discord=DiscordConfig(bot_token=discord_token),+ lark=LarkConfig(app_id="cli_a", app_secret=lark_secret, domain="feishu"),+ claude=SimpleNamespace(),+ language="en",+ )+++def _controller(config):+ controller = Controller.__new__(Controller)+ controller.config = config+ controller.enabled_platforms = list(config.enabled_platforms())+ controller.primary_platform = Controller._derive_primary_platform(config)+ clients = {platform: _Client(platform, getattr(config, platform)) for platform in controller.enabled_platforms}+ for platform, client in clients.items():+ client.formatter = _Formatter()+ controller.im_client = MultiIMClient(dict(clients), controller.primary_platform)+ controller.im_clients = dict(clients)+ controller.im_clients["avibe"] = _Client("avibe")+ controller.settings_manager = MultiSettingsManager(+ Controller._settings_platforms_for(controller.enabled_platforms, controller.primary_platform),+ primary_platform=controller.primary_platform,+ )+ controller.platform_settings_managers = controller.settings_manager.managers+ controller.sessions = controller.settings_manager.sessions+ controller.agent_router = AgentRouter.from_file(None, platform=controller.primary_platform, default_backend="opencode")+ controller.processing_indicator = SimpleNamespace(config=config)+ controller.audio_asr_service = SimpleNamespace(config=config)+ controller.claude_client = SimpleNamespace(config=config.claude, formatter=None)+ controller.command_handler = _handler()+ controller.settings_handler = _handler()+ controller.message_handler = _handler()+ controller.session_handler = _handler()+ controller.agent_service = SimpleNamespace(agents={})+ controller._reconcile_lock = None+ controller._loop = None+ return controller+++def test_reconcile_adds_platform_with_callbacks_before_start(monkeypatch):+ monkeypatch.setattr("core.controller.get_platform_descriptor", lambda platform: _Descriptor(platform))+ controller = _controller(_config(["slack"]))+ controller._setup_callbacks()++ result = asyncio.run(controller.reconcile_platforms(_config(["slack", "discord"])))++ assert result["added"] == ["discord"]+ assert "discord" in controller.im_client.clients+ assert "discord" in controller.platform_settings_managers+ assert controller.im_client.clients["discord"].on_message_callback is not None+ assert controller.im_client.clients["discord"].settings_manager.platform == "discord"+++def test_reconcile_removes_platform_and_keeps_workbench_delivery(monkeypatch):+ monkeypatch.setattr("core.controller.get_platform_descriptor", lambda platform: _Descriptor(platform))+ controller = _controller(_config(["slack", "discord"]))+ removed_client = controller.im_clients["discord"]++ result = asyncio.run(controller.reconcile_platforms(_config(["slack"])))++ assert result["removed"] == ["discord"]+ assert removed_client.stopped is True+ assert "discord" not in controller.im_client.clients+ assert "discord" not in controller.im_clients+ assert "avibe" in controller.im_clients+++def test_reconcile_rebuilds_enabled_platform_on_credential_change(monkeypatch):+ monkeypatch.setattr("core.controller.get_platform_descriptor", lambda platform: _Descriptor(platform))+ controller = _controller(_config(["slack"]))+ old_client = controller.im_clients["slack"]++ result = asyncio.run(controller.reconcile_platforms(_config(["slack"], slack_token="xoxb-new")))++ assert result["rebuilt"] == ["slack"]+ assert old_client.stopped is True+ assert controller.im_clients["slack"] is not old_client+ assert controller.im_clients["slack"].config.bot_token == "xoxb-new"+++def test_reconcile_noop_when_runtime_fields_do_not_change(monkeypatch):+ monkeypatch.setattr("core.controller.get_platform_descriptor", lambda platform: _Descriptor(platform))+ controller = _controller(_config(["slack"]))+ original_client = controller.im_clients["slack"]++ result = asyncio.run(controller.reconcile_platforms(_config(["slack"])))++ assert result["added"] == []+ assert result["removed"] == []+ assert result["rebuilt"] == []+ assert controller.im_clients["slack"] is original_client+++def test_reconcile_disable_all_keeps_empty_multi_runtime(monkeypatch):+ monkeypatch.setattr("core.controller.get_platform_descriptor", lambda platform: _Descriptor(platform))+ controller = _controller(_config(["slack"]))++ result = asyncio.run(controller.reconcile_platforms(_config([])))++ assert result["removed"] == ["slack"]+ assert result["enabled"] == []+ assert result["primary"] == "avibe"+ assert controller.primary_platform == "avibe"+ assert controller.im_client.clients == {}+ assert "avibe" in controller.im_clients+ assert controller.get_im_client_for_context(MessageContext(user_id="u", channel_id="c", platform="avibe")).name == "avibe"diff --git a/tests/test_feishu_hot_stop.py b/tests/test_feishu_hot_stop.pynew file mode 100644index 000000000..d1076ccd0--- /dev/null+++ b/tests/test_feishu_hot_stop.py@@ -0,0 +1,65 @@+from __future__ import annotations++import asyncio++from config.v2_config import LarkConfig+from modules.im.feishu import FeishuBot+++def test_feishu_stop_disconnects_nested_ws_client(monkeypatch):+ import lark_oapi.ws.client as ws_client_module++ loop = asyncio.new_event_loop()+ disconnected = []++ class _WsClient:+ async def _disconnect(self):+ disconnected.append(True)++ bot = FeishuBot(LarkConfig(app_id="cli_a", app_secret="secret"))+ bot._ws_client = _WsClient()+ bot._loop = loop+ monkeypatch.setattr(ws_client_module, "loop", loop)++ try:+ bot.stop()+ finally:+ loop.close()++ assert disconnected == [True]+++def test_feishu_stop_stops_running_lark_ws_loop(monkeypatch):+ import lark_oapi.ws.client as ws_client_module++ loop = asyncio.new_event_loop()+ disconnected = []++ class _WsClient:+ async def _disconnect(self):+ disconnected.append(True)++ def _run_loop() -> None:+ asyncio.set_event_loop(loop)+ loop.run_forever()++ import threading++ thread = threading.Thread(target=_run_loop, daemon=True)+ thread.start()+ try:+ assert thread.is_alive()+ bot = FeishuBot(LarkConfig(app_id="cli_a", app_secret="secret"))+ bot._ws_client = _WsClient()+ monkeypatch.setattr(ws_client_module, "loop", loop)++ bot.stop()+ thread.join(timeout=2)+ finally:+ if thread.is_alive():+ loop.call_soon_threadsafe(loop.stop)+ thread.join(timeout=2)+ loop.close()++ assert disconnected == [True]+ assert thread.is_alive() is Falsediff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex 2be2bfc5e..089e6d848 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -2,6 +2,8 @@ from __future__ import annotationsimport asyncioimport sys+import threading+import timefrom dataclasses import dataclassfrom pathlib import Path@@ -31,6 +33,7 @@ class _StubClient(BaseIMClient):self.sent = []self.removed = []self.dismissed = []+ self.stopped = Falseasync def send_message(self, context, text, parse_mode=None, reply_to=None):self.sent.append((context.platform, context.channel_id, text))@@ -61,6 +64,9 @@ class _StubClient(BaseIMClient):def run(self):return None+ def stop(self):+ self.stopped = True+async def get_user_info(self, user_id: str):return {"id": user_id, "name": self.name}@@ -118,6 +124,59 @@ def test_multi_im_client_routes_send_by_context_platform():assert wechat.sent == [("wechat", "c", "hello")]+def test_multi_im_client_add_client_registers_callbacks_before_start():+ client = MultiIMClient({}, primary_platform="avibe")+ added = _StubClient("slack")+ captured: list[str | None] = []++ async def on_message(context: MessageContext, text: str):+ captured.append(context.platform)++ client.register_callbacks(on_message=on_message)+ client.add_client("slack", added)++ assert client.clients["slack"] is added+ assert added.on_message_callback is not None+ asyncio.run(added.on_message_callback(MessageContext(user_id="u", channel_id="c"), "hello"))+ assert captured == ["slack"]+++def test_multi_im_client_remove_client_stops_and_drops_platform():+ slack = _StubClient("slack")+ wechat = _StubClient("wechat")+ client = MultiIMClient({"slack": slack, "wechat": wechat}, primary_platform="slack")++ removed = client.remove_client("slack")++ assert removed is slack+ assert slack.stopped is True+ assert "slack" not in client.clients+ assert client.primary_platform == "wechat"+++def test_multi_im_client_empty_runtime_stays_alive_until_stop():+ client = MultiIMClient({}, primary_platform="avibe")+ returned: list[bool] = []++ def _run() -> None:+ client.run()+ returned.append(True)++ thread = threading.Thread(target=_run, daemon=True)+ thread.start()++ assert client._run_started.wait(timeout=2)+ time.sleep(0.05)+ assert thread.is_alive() is True+ assert returned == []++ client.stop()+ thread.join(timeout=2)++ assert thread.is_alive() is False+ assert returned == [True]++def test_multi_im_client_routes_message_edit_capability_by_context_platform():slack = _StubClient("slack")wechat = _StubClient("wechat", supports_editing=False)diff --git a/tests/test_platform_registry.py b/tests/test_platform_registry.pyindex 5af1c9f21..97e3e4f17 100644--- a/tests/test_platform_registry.py+++ b/tests/test_platform_registry.py@@ -14,6 +14,7 @@ from config.platform_registry import (from config.v2_config import PlatformsConfig, SlackConfig, V2Configfrom modules.im.avibe import AvibeBotfrom modules.im.factory import IMFactory+from modules.im.multi import MultiIMClientfrom modules.im.slack import SlackBot@@ -136,35 +137,37 @@ def test_create_clients_builds_real_platforms_but_skips_workbench() -> None:def test_create_client_returns_avibe_for_workbench_only_empty_enabled() -> None:- # Workbench-only config: no external IM platform is enabled, so the built- # client map is empty. ``create_client`` must return the in-process- # ``AvibeBot`` (mirroring the controller's avibe fallback) rather than- # constructing ``MultiIMClient({}, "avibe")``, which would raise because the- # primary is absent from the empty map.+ # Workbench-only config: no external IM platform is enabled, so the IM+ # runtime wrapper is empty and idles until stop.config = _config_with_enabled([])config.platforms = SimpleNamespace(enabled=[], primary="avibe")client = IMFactory.create_client(config)- assert isinstance(client, AvibeBot)+ assert isinstance(client, MultiIMClient)+ assert client.clients == {}+ assert client.primary_platform == "avibe"def test_create_client_returns_avibe_for_legacy_avibe_only_enabled() -> None:# Older configs persisted the workbench-only state as ``["avibe"]`` instead# of an empty list. ``create_clients`` skips the workbench either way, so the- # singular helper must still resolve to the in-process ``AvibeBot``.+ # singular helper must still resolve to an empty runtime wrapper.client = IMFactory.create_client(_config_with_enabled(["avibe"]))- assert isinstance(client, AvibeBot)+ assert isinstance(client, MultiIMClient)+ assert client.clients == {}+ assert client.primary_platform == "avibe"def test_create_client_returns_single_real_client_when_one_platform_enabled() -> None:- # Sanity guard that the workbench-only short-circuit does not regress the- # ordinary single-platform path: a lone enabled platform returns that- # client directly (not wrapped in MultiIMClient).+ # The runtime always uses the wrapper now, even for a lone enabled platform,+ # so hot reconcile has one uniform add/remove surface.config = _config_with_enabled(["slack"])config.platforms = SimpleNamespace(enabled=["slack"], primary="slack")client = IMFactory.create_client(config)- assert isinstance(client, SlackBot)+ assert isinstance(client, MultiIMClient)+ assert isinstance(client.clients["slack"], SlackBot)+ assert client.primary_platform == "slack"diff --git a/tests/test_workbench_only_runtime.py b/tests/test_workbench_only_runtime.pyindex 014998d76..ff4f99586 100644--- a/tests/test_workbench_only_runtime.py+++ b/tests/test_workbench_only_runtime.py@@ -4,13 +4,11 @@ A workbench-only install enables no Slack/Discord/Telegram/Lark/WeChatplatform. The Avibe Workbench (in-process Web UI) is the sole inbound surface.These tests cover the two delicate seams that make that work end-to-end:-1. Controller ``_init_modules`` must register the in-process ``AvibeBot`` as the- SOLE IM client, anchor the primary platform to "avibe", and wire a settings- manager for it — without crashing on the empty enabled-platform set.-2. ``AvibeBot.run`` must fire ``on_ready`` exactly once (so the controller starts- poll-restore / scheduled tasks / update checker) and then BLOCK so the- IM-runtime thread does not return, keeping the controller's ``run_forever``- alive until ``stop`` is called.+1. Controller ``_init_modules`` must always use ``MultiIMClient`` for the IM+ runtime, even when no external IM platforms are enabled. In workbench-only+ mode that wrapper has zero runtime clients and stays alive via its idle loop.+2. ``AvibeBot`` remains registered separately as the in-process delivery client+ for Web UI replies, with a settings manager for "avibe".The has-IM path is exercised by the broader multi-platform suite; here we onlyassert the workbench-only behavior that previously raised.@@ -22,6 +20,7 @@ import asyncioimport sysimport threadingimport time+from dataclasses import dataclassfrom pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -30,7 +29,55 @@ from config.v2_compat import to_app_configfrom config.v2_config import V2Configfrom core.controller import Controllerfrom modules.im.avibe import AvibeBot, AvibeConfig-from modules.im.base import MessageContext+from modules.im.base import BaseIMClient, BaseIMConfig, MessageContext+from modules.im.multi import MultiIMClient+++@dataclass+class _BootConfig(BaseIMConfig):+ def validate(self) -> None:+ return None+++class _BootClient(BaseIMClient):+ def __init__(self, platform: str):+ super().__init__(_BootConfig())+ self.platform = platform+ self.settings_manager = None+ self.controller = None++ def set_settings_manager(self, settings_manager):+ self.settings_manager = settings_manager++ def set_controller(self, controller):+ self.controller = controller++ async def send_message(self, context, text, parse_mode=None, reply_to=None):+ return self.platform++ async def send_message_with_buttons(self, context, text, keyboard, parse_mode=None):+ return self.platform++ async def edit_message(self, context, message_id, text=None, keyboard=None, parse_mode=None):+ return True++ async def answer_callback(self, callback_id, text=None, show_alert=False):+ return True++ def register_handlers(self):+ return None++ def run(self):+ return None++ async def get_user_info(self, user_id: str):+ return {"id": user_id}++ async def get_channel_info(self, channel_id: str):+ return {"id": channel_id}++ def format_markdown(self, text: str) -> str:+ return textdef _workbench_only_app_config():@@ -49,20 +96,48 @@ def _workbench_only_app_config():return to_app_config(V2Config.from_payload(payload))-def test_init_modules_registers_avibe_as_sole_client_for_workbench_only():- app_config = _workbench_only_app_config()- # The compat view of a workbench-only config exposes no enabled platforms.- assert app_config.enabled_platforms() == []+def _boot_app_config(enabled: list[str]):+ primary = enabled[0] if enabled else "avibe"+ payload = {+ "platform": primary,+ "platforms": {"enabled": enabled, "primary": primary},+ "mode": "self_host",+ "version": "v2",+ "runtime": {"default_cwd": "_tmp", "log_level": "INFO"},+ "agents": {+ "default_backend": "opencode",+ "opencode": {"enabled": True, "cli_path": "opencode"},+ },+ "setup_completed": True,+ "slack": {"bot_token": "xoxb-test", "app_token": "xapp-test"},+ "discord": {"bot_token": "discord-token"},+ "telegram": {"bot_token": "123456:test-token"},+ "lark": {"app_id": "cli_a", "app_secret": "secret", "domain": "feishu"},+ "wechat": {"bot_token": "wechat-token"},+ }+ return to_app_config(V2Config.from_payload(payload))++def _init_controller_modules(app_config):controller = Controller.__new__(Controller)controller.config = app_configcontroller.enabled_platforms = list(app_config.enabled_platforms())controller.primary_platform = getattr(getattr(app_config, "platforms", None), "primary", app_config.platform)-controller._init_modules()+ return controller+++def test_init_modules_uses_empty_multi_runtime_for_workbench_only():+ app_config = _workbench_only_app_config()+ # The compat view of a workbench-only config exposes no enabled platforms.+ assert app_config.enabled_platforms() == []++ controller = _init_controller_modules(app_config)assert list(controller.im_clients.keys()) == ["avibe"]- assert isinstance(controller.im_client, AvibeBot)+ assert isinstance(controller.im_clients["avibe"], AvibeBot)+ assert isinstance(controller.im_client, MultiIMClient)+ assert controller.im_client.clients == {}assert controller.primary_platform == "avibe"# The primary-anchored settings manager resolves (no KeyError on an empty# enabled-platform set) for both the no-context and avibe-context cases.@@ -73,6 +148,36 @@ def test_init_modules_registers_avibe_as_sole_client_for_workbench_only():assert "avibe" in controller.agent_router.platform_routes+def test_init_modules_boots_single_platform_with_multi_runtime(monkeypatch):+ app_config = _boot_app_config(["slack"])+ monkeypatch.setattr("core.controller.IMFactory.create_clients", lambda config: {"slack": _BootClient("slack")})++ controller = _init_controller_modules(app_config)++ assert isinstance(controller.im_client, MultiIMClient)+ assert list(controller.im_client.clients.keys()) == ["slack"]+ assert controller.primary_platform == "slack"+ assert "avibe" in controller.im_clients+ assert "slack" in controller.agent_router.platform_routes+++def test_init_modules_boots_four_platforms_with_multi_runtime(monkeypatch):+ enabled = ["slack", "discord", "telegram", "lark"]+ app_config = _boot_app_config(enabled)+ monkeypatch.setattr(+ "core.controller.IMFactory.create_clients",+ lambda config: {platform: _BootClient(platform) for platform in enabled},+ )++ controller = _init_controller_modules(app_config)++ assert isinstance(controller.im_client, MultiIMClient)+ assert list(controller.im_client.clients.keys()) == enabled+ assert controller.primary_platform == "slack"+ assert "avibe" in controller.im_clients+ assert set(enabled) <= set(controller.agent_router.platform_routes)++def test_avibe_run_fires_on_ready_once_then_blocks_until_stop():# Stand-in for the controller event loop + its _dispatch_to_controller_loop# bridge, so we exercise the real cross-loop hand-off AvibeBot.run relies on.