Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat(im): MultiIMClient per-platform add/remove_client + idle-stable run loop

cyh0ee684e030dc
diff --git a/docs/plans/hot-platform-reconcile.md b/docs/plans/hot-platform-reconcile.md
new file mode 100644
index 000000000..ec1b60b64
--- /dev/null
+++ b/docs/plans/hot-platform-reconcile.md
@@ -0,0 +1,100 @@
+# Phase 2 — Hot platform reconcile (apply platform changes with no service restart)
+
+## Background
+
+Phase 1 (PR #566) made platform config changes do a **service-only restart** that
+keeps the Web UI process alive. Phase 2 removes the restart entirely for the
+common case: enabling/disabling a platform should just start/stop **that one
+platform's background task**, not bounce the whole service.
+
+## Current mechanics (verified)
+
+- `MultiIMClient` (`modules/im/multi.py`) runs **one daemon thread per platform**;
+ each thread calls the adapter's blocking `client.run()`. It has only
+ all-or-nothing `stop()`/`shutdown()` — no per-platform start/stop.
+- The IM runtime blocks on a worker thread (`Controller._run_im_runtime`,
+ `core/controller.py:513`), spawned from `controller.run()`; the main thread
+ owns the asyncio loop.
+- `IMFactory.create_clients()` builds `im_clients` **once** in
+ `Controller._init_modules` (`controller.py:144-227`). `_refresh_config_from_disk`
+ hot-reloads a SUBSET (message filters/i18n/require_mention) but NOT platform
+ enablement, credentials, settings managers, or agent routes.
+- Internal command channel: `core/internal_server.py` serves HTTP over a unix
+ socket (`dispatch.sock`) on the controller's loop; `vibe/internal_client.py` is
+ the client. Existing commands: dispatch_async, dispatch, turn-state, cancel,
+ health. The UI process already calls it (e.g. bootstrap → turn_state).
+
+## Design
+
+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).
+2. **`Controller.reconcile_platforms(new_config)`** (async, on the loop) — diff
+ the new enabled set vs running and:
+ - removed → `remove_client` + drop its settings manager;
+ - added → build client via `IMFactory`/descriptor, formatter, settings
+ manager, agent route, register callbacks, `add_client` (start its thread);
+ - recompute `enabled_platforms` + the derived `primary_platform`;
+ - rebuild the single-vs-multi `im_client` wrapper if topology changed.
+ Sync `stop()` calls wrapped in `asyncio.to_thread`/`call_soon_threadsafe`.
+3. **`POST /internal/reconcile-platforms`** on the internal server → calls
+ `controller.reconcile_platforms`.
+4. **`POST /api/config`** (UI process): after saving, if the platform fields
+ changed, send the internal reconcile command instead of scheduling a restart.
+ The platforms page stops calling `control('restart')` for enable/disable.
+
+## Per-adapter hot-stop verdict
+
+| Platform | Clean single-stop? | Notes |
+|---|---|---|
+| Slack | ✅ | async stop-event + socket close |
+| 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 |
+
+## Decisions (locked — full scope, "一次到位")
+
+- **D1 — Feishu: patch for clean hot-stop.** Expose a stop on the nested lark
+ WS thread so Feishu can be hot-removed like the others (no fallback restart).
+- **D2 — Credential changes: rebuild, not per-adapter reconnect.** A credential
+ edit on an enabled platform = `remove_client` + `add_client` (tear down the
+ old adapter, build a fresh one with the new config, start it). Reuses the
+ add/remove machinery — no per-adapter "reconnect" code. Works for all 5 once
+ every adapter stops cleanly (D1).
+- **D3 — Trigger.** `POST /api/config` decides reconcile-vs-restart by diffing
+ the platform fields; manual Dashboard/Service restart buttons unchanged. With
+ full scope, platform enable/disable/credential changes ALL hot-reconcile (no
+ restart); a service-only restart remains only for non-platform config that
+ the running service doesn't hot-apply.
+
+## Risks & mitigations
+
+- Routing to a half-removed client → KeyError: mutate `clients` under a lock;
+ routing reads a snapshot.
+- A stuck `client.run()` won't join: bounded `join` timeout + the thread is a
+ daemon (dies at process exit); log a leak warning.
+- Callback re-registration: a newly added client must have callbacks wired
+ before its thread starts so early inbound isn't dropped.
+- Settings-manager file lifecycle for a newly added platform: lazy-load on
+ first 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
diff --git a/modules/im/multi.py b/modules/im/multi.py
index 291225dd5..45b416582 100644
--- a/modules/im/multi.py
+++ b/modules/im/multi.py
@@ -24,6 +24,10 @@ class MultiIMClient(BaseIMClient):
self.clients = clients
self.primary_platform = primary_platform
self._threads: Dict[str, threading.Thread] = {}
+ # 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.
+ self._clients_lock = threading.RLock()
self._stop_requested = threading.Event()
self._ready_lock = threading.Lock()
self._ready_platforms: set[str] = set()
@@ -281,22 +285,28 @@ class MultiIMClient(BaseIMClient):
def run(self):
self._stop_requested.clear()
- self._threads = {}
-
- for platform, client in self.clients.items():
- thread = threading.Thread(target=self._run_client, args=(platform, client), daemon=True)
- thread.start()
- self._threads[platform] = thread
+ with self._clients_lock:
+ self._threads = {}
+ for platform, client in self.clients.items():
+ thread = threading.Thread(target=self._run_client, args=(platform, client), daemon=True)
+ thread.start()
+ self._threads[platform] = thread
try:
+ # Idle-loop until an explicit stop. The runtime stays alive even when
+ # no platform threads remain — that is a valid state now: hot
+ # reconcile can disable every IM platform (workbench-only) or be
+ # mid-rebuild, and the runtime must keep running so a platform can be
+ # added back without restarting the service. (Previously this broke
+ # out when ``_threads`` emptied, which — via Controller._run_im_runtime
+ # calling loop.stop() — would tear the whole service down.)
while not self._stop_requested.is_set():
- for platform, thread in list(self._threads.items()):
- if thread.is_alive():
- continue
- logger.warning("IM runtime for %s exited", platform)
- self._threads.pop(platform, None)
- if not self._threads:
- break
+ with self._clients_lock:
+ for platform, thread in list(self._threads.items()):
+ if thread.is_alive():
+ continue
+ logger.warning("IM runtime for %s exited", platform)
+ self._threads.pop(platform, None)
time.sleep(0.5)
finally:
self.stop()
@@ -310,6 +320,52 @@ class MultiIMClient(BaseIMClient):
except Exception:
logger.exception("IM runtime for %s crashed", platform)
+ def add_client(self, platform: str, client: BaseIMClient) -> None:
+ """Start one platform's client (+ its runtime thread) at runtime.
+
+ Used by the hot-reconcile path to enable a platform without restarting
+ the service. A no-op if the platform is already present (callers rebuild
+ via remove_client + add_client for credential changes).
+ """
+ with self._clients_lock:
+ if platform in self.clients:
+ logger.warning("add_client: platform %s already present; skipping", platform)
+ return
+ self.clients[platform] = client
+ # 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():
+ thread = threading.Thread(target=self._run_client, args=(platform, client), daemon=True)
+ thread.start()
+ self._threads[platform] = thread
+ logger.info("Hot-added IM platform %s", platform)
+
+ def remove_client(self, platform: str) -> Optional[BaseIMClient]:
+ """Stop and drop one platform's client (+ join its thread) at runtime.
+
+ Blocking (signals the client's stop and joins its thread), so the
+ reconcile path calls this via ``asyncio.to_thread`` to avoid blocking the
+ loop. Returns the removed client, or ``None`` if it wasn't present.
+ """
+ with self._clients_lock:
+ client = self.clients.pop(platform, None)
+ thread = self._threads.pop(platform, None)
+ if client is None:
+ return None
+
+ stop_attr = getattr(client, "stop", None)
+ if callable(stop_attr) and not inspect.iscoroutinefunction(stop_attr):
+ try:
+ stop_attr()
+ except Exception:
+ logger.exception("Failed to stop IM client for %s", platform)
+ if thread is not None:
+ thread.join(timeout=5.0)
+ if thread.is_alive():
+ logger.warning("IM thread for %s did not stop within timeout (leaked)", platform)
+ logger.info("Hot-removed IM platform %s", platform)
+ return client
+
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)