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.

fix(im): harden hot platform removal

cyha0f7064db055
diff --git a/core/controller.py b/core/controller.py
index 77c3cb89d..9b5348715 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -35,6 +35,105 @@ from vibe.i18n import get_supported_languages, t as i18n_t
logger = logging.getLogger(__name__)
+class RemovedPlatformIMClient(BaseIMClient):
+ """No-op sink for stale replies after an IM platform is hot-disabled."""
+
+ def __init__(self, platform: str):
+ from config.v2_config import AvibeConfig
+ from modules.im.formatters.avibe_formatter import AvibeFormatter
+
+ super().__init__(AvibeConfig())
+ self.platform = platform
+ self.formatter = AvibeFormatter()
+
+ def get_default_parse_mode(self) -> Optional[str]:
+ return None
+
+ def should_use_thread_for_reply(self) -> bool:
+ return False
+
+ def supports_message_editing(self, context: Optional[MessageContext] = None) -> bool:
+ return False
+
+ async def send_message(
+ self,
+ context: MessageContext,
+ text: str,
+ parse_mode: Optional[str] = None,
+ reply_to: Optional[str] = None,
+ ) -> str:
+ logger.info("Dropping stale outbound message for removed IM platform %s", self.platform)
+ return ""
+
+ async def send_message_with_buttons(
+ self,
+ context: MessageContext,
+ text: str,
+ keyboard,
+ parse_mode: Optional[str] = None,
+ ) -> str:
+ logger.info("Dropping stale outbound button message for removed IM platform %s", self.platform)
+ return ""
+
+ async def edit_message(
+ self,
+ context: MessageContext,
+ message_id: str,
+ text: Optional[str] = None,
+ keyboard: Optional[Any] = None,
+ parse_mode: Optional[str] = None,
+ ) -> bool:
+ return False
+
+ async def remove_inline_keyboard(
+ self,
+ context: MessageContext,
+ message_id: str,
+ text: Optional[str] = None,
+ parse_mode: Optional[str] = None,
+ ) -> bool:
+ return False
+
+ async def answer_callback(self, callback_id: str, text: Optional[str] = None, show_alert: bool = False) -> bool:
+ return False
+
+ def register_handlers(self):
+ return None
+
+ def run(self):
+ return None
+
+ def stop(self):
+ return None
+
+ async def get_user_info(self, user_id: str) -> Dict[str, Any]:
+ return {"id": user_id, "platform": self.platform, "removed": True}
+
+ async def get_channel_info(self, channel_id: str) -> Dict[str, Any]:
+ return {"id": channel_id, "platform": self.platform, "removed": True}
+
+ async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
+ return False
+
+ async def remove_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
+ return False
+
+ async def send_typing_indicator(self, context: MessageContext) -> bool:
+ return False
+
+ async def clear_typing_indicator(self, context: MessageContext) -> bool:
+ return False
+
+ async def delete_message(self, context: MessageContext, message_id: str) -> bool:
+ return False
+
+ async def send_dm(self, user_id: str, text: str, **kwargs):
+ return None
+
+ def format_markdown(self, text: str) -> str:
+ return text
+
+
def _optional_target_str(value: Any) -> Optional[str]:
if value is None:
return None
@@ -69,6 +168,7 @@ class Controller:
self.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
+ self._removed_im_clients: Dict[str, BaseIMClient] = {}
# Session tracking (must be initialized before handlers)
self.claude_sessions: Dict[str, Any] = {}
@@ -154,6 +254,7 @@ class Controller:
from modules.im.avibe import AvibeBot, AvibeConfig
self.im_clients["avibe"] = AvibeBot(AvibeConfig())
+ self._removed_im_clients = {}
formatter = self.im_clients.get(self.primary_platform, self.im_clients["avibe"]).formatter
self.claude_client = ClaudeClient(self.config.claude, formatter)
@@ -302,6 +403,8 @@ class Controller:
for platform in removed + rebuilt:
await asyncio.to_thread(self.im_client.remove_client, platform)
self.im_clients.pop(platform, None)
+ if platform in removed:
+ self._removed_im_clients[platform] = RemovedPlatformIMClient(platform)
self.enabled_platforms = next_enabled
self.primary_platform = next_primary
@@ -316,6 +419,7 @@ class Controller:
self._ensure_agent_route_for_platform("avibe")
for platform in rebuilt + added:
+ self._removed_im_clients.pop(platform, None)
client = self._build_platform_client(platform, new_config)
self.im_clients[platform] = client
self.im_client.add_client(platform, client)
@@ -707,10 +811,22 @@ class Controller:
if context is None:
return self.im_clients[self.primary_platform]
platform = context.platform or (context.platform_specific or {}).get("platform") or self.primary_platform
- return self.im_clients.get(platform, self.im_clients[self.primary_platform])
+ client = self.im_clients.get(platform)
+ if client is not None:
+ return client
+ removed_client = self._removed_im_clients.get(platform)
+ if removed_client is not None:
+ return removed_client
+ return self.im_clients[self.primary_platform]
def _get_im_client_for_platform(self, platform: str) -> BaseIMClient:
- return self.im_clients.get(platform, self.im_clients[self.primary_platform])
+ client = self.im_clients.get(platform)
+ if client is not None:
+ return client
+ removed_client = self._removed_im_clients.get(platform)
+ if removed_client is not None:
+ return removed_client
+ return self.im_clients[self.primary_platform]
# --- Streaming turn sinks -------------------------------------------
# A live SSE caller registers a sink before dispatching a turn so the
diff --git a/modules/im/multi.py b/modules/im/multi.py
index 3c6bbeb7b..6c2b0cf08 100644
--- a/modules/im/multi.py
+++ b/modules/im/multi.py
@@ -15,6 +15,10 @@ from .base import BaseIMClient, InlineKeyboard, MessageContext
logger = logging.getLogger(__name__)
+class IMClientRemovalError(RuntimeError):
+ """Raised when a hot-remove cannot stop a platform runtime cleanly."""
+
+
class MultiIMClient(BaseIMClient):
"""Delegate inbound/outbound messaging across multiple IM clients."""
@@ -204,24 +208,43 @@ class MultiIMClient(BaseIMClient):
return None
async def _wrapped(*args: Any, **kwargs: Any):
- should_fire = False
with self._ready_lock:
self._ready_platforms.add(platform)
- logger.info(
- "Platform '%s' ready (%d/%d)",
- platform,
- len(self._ready_platforms),
- len(self._client_snapshot()),
- )
- 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 = True
- should_fire = True
- if should_fire:
+ if self._mark_ready_if_complete():
await callback(*args, **kwargs)
return _wrapped
+ def _mark_ready_if_complete(self) -> bool:
+ """Return True once when all currently registered clients are ready."""
+ with self._ready_lock:
+ client_count = len(self._client_snapshot())
+ logger.info(
+ "IM runtime ready progress (%d/%d)",
+ len(self._ready_platforms),
+ client_count,
+ )
+ if client_count > 0 and not self._ready_emitted and len(self._ready_platforms) >= client_count:
+ self._ready_emitted = True
+ return True
+ return False
+
+ def _aggregate_ready_callback(self) -> Optional[Callable]:
+ if self._registered_callbacks is None:
+ return None
+ return self._registered_callbacks[3].get("on_ready")
+
+ def _fire_aggregate_ready_from_thread(self, callback: Callable) -> None:
+ async def _call_ready() -> None:
+ result = callback()
+ if inspect.isawaitable(result):
+ await result
+
+ try:
+ asyncio.run(_call_ready())
+ except Exception:
+ logger.exception("MultiIMClient aggregate on_ready callback failed")
+
def _emit_empty_ready_once(self) -> None:
callback = getattr(self, "on_ready_callback", None)
if callback is None:
@@ -378,6 +401,9 @@ class MultiIMClient(BaseIMClient):
continue
logger.warning("IM runtime for %s exited", platform)
self._threads.pop(platform, None)
+ if self.clients and not self._threads:
+ logger.error("All enabled IM runtime threads exited")
+ break
time.sleep(0.5)
finally:
self.stop()
@@ -425,17 +451,10 @@ class MultiIMClient(BaseIMClient):
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 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.formatter
+ client = self.clients.get(platform)
+ thread = self._threads.get(platform)
if 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):
@@ -446,7 +465,25 @@ class MultiIMClient(BaseIMClient):
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)
+ message = f"IM thread for {platform} did not stop within timeout"
+ logger.error("%s; hot-remove failed", message)
+ raise IMClientRemovalError(message)
+
+ ready_callback = None
+ with self._clients_lock:
+ self.clients.pop(platform, None)
+ 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.formatter
+ with self._ready_lock:
+ self._ready_platforms.discard(platform)
+ if self._mark_ready_if_complete():
+ ready_callback = self._aggregate_ready_callback()
+ if ready_callback is not None:
+ self._fire_aggregate_ready_from_thread(ready_callback)
logger.info("Hot-removed IM platform %s", platform)
return client
diff --git a/tests/test_controller_platform_reconcile.py b/tests/test_controller_platform_reconcile.py
index 6091e7524..1e21a81a6 100644
--- a/tests/test_controller_platform_reconcile.py
+++ b/tests/test_controller_platform_reconcile.py
@@ -150,6 +150,7 @@ def _controller(config):
controller.im_client = MultiIMClient(dict(clients), controller.primary_platform)
controller.im_clients = dict(clients)
controller.im_clients["avibe"] = _Client("avibe")
+ controller._removed_im_clients = {}
controller.settings_manager = MultiSettingsManager(
Controller._settings_platforms_for(controller.enabled_platforms, controller.primary_platform),
primary_platform=controller.primary_platform,
@@ -198,6 +199,26 @@ def test_reconcile_removes_platform_and_keeps_workbench_delivery(monkeypatch):
assert "avibe" in controller.im_clients
+def test_reconcile_routes_removed_platform_context_to_noop_sink(monkeypatch):
+ monkeypatch.setattr("core.controller.get_platform_descriptor", lambda platform: _Descriptor(platform))
+ controller = _controller(_config(["slack", "discord"]))
+ slack = controller.im_clients["slack"]
+
+ asyncio.run(controller.reconcile_platforms(_config(["slack"])))
+
+ stale_context = MessageContext(user_id="u", channel_id="discord-channel", platform="discord")
+ removed_client = controller.get_im_client_for_context(stale_context)
+ platform_client = controller._get_im_client_for_platform("discord")
+
+ assert removed_client is platform_client
+ assert removed_client is not slack
+ assert asyncio.run(removed_client.send_message(stale_context, "late result")) == ""
+ assert asyncio.run(removed_client.send_message_with_buttons(stale_context, "late result", None)) == ""
+ assert asyncio.run(removed_client.send_typing_indicator(stale_context)) is False
+ assert asyncio.run(removed_client.clear_typing_indicator(stale_context)) is False
+ assert asyncio.run(removed_client.delete_message(stale_context, "ack-1")) is False
+
+
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"]))
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 7768928be..02d6a4ef5 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -205,6 +205,28 @@ def test_reconcile_platforms_endpoint_calls_controller(monkeypatch):
assert calls == ["compat:v2-config"]
+def test_reconcile_platforms_endpoint_reports_controller_failure(monkeypatch):
+ controller = _build_controller_double()
+
+ async def reconcile_platforms(config):
+ raise RuntimeError("IM thread for discord did not stop within timeout")
+
+ controller.reconcile_platforms = reconcile_platforms
+ monkeypatch.setattr("config.v2_config.V2Config.load", lambda: "v2-config")
+ monkeypatch.setattr("config.v2_compat.to_app_config", lambda config: f"compat:{config}")
+ app = internal_server.create_app(controller)
+
+ async def _go():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ return await client.post("/internal/reconcile-platforms")
+
+ resp = asyncio.run(_go())
+
+ assert resp.status_code == 500
+ assert resp.json() == {"ok": False, "error": "IM thread for discord did not stop within timeout"}
+
+
async def _dispatch_round_trip(body: dict) -> httpx.Response:
app = internal_server.create_app(_build_controller_double())
transport = httpx.ASGITransport(app=app)
diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.py
index 089e6d848..921ff3fce 100644
--- a/tests/test_multi_platform_runtime.py
+++ b/tests/test_multi_platform_runtime.py
@@ -10,7 +10,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from modules.im.base import BaseIMClient, BaseIMConfig, MessageContext
-from modules.im.multi import MultiIMClient
+from modules.im.multi import IMClientRemovalError, MultiIMClient
from modules.settings_manager import MultiSettingsManager
from config.v2_sessions import ActivePollInfo
from core.processing_indicator import ProcessingIndicatorService
@@ -26,10 +26,13 @@ class _StubConfig(BaseIMConfig):
class _StubClient(BaseIMClient):
- def __init__(self, name: str, *, supports_editing: bool = True):
+ def __init__(self, name: str, *, supports_editing: bool = True, run_until_stopped: bool = False):
super().__init__(_StubConfig())
self.name = name
self._supports_editing = supports_editing
+ self._run_until_stopped = run_until_stopped
+ self._stop_event = threading.Event()
+ self.started = threading.Event()
self.sent = []
self.removed = []
self.dismissed = []
@@ -62,10 +65,14 @@ class _StubClient(BaseIMClient):
return None
def run(self):
+ self.started.set()
+ if self._run_until_stopped:
+ self._stop_event.wait()
return None
def stop(self):
self.stopped = True
+ self._stop_event.set()
async def get_user_info(self, user_id: str):
return {"id": user_id, "name": self.name}
@@ -154,6 +161,67 @@ def test_multi_im_client_remove_client_stops_and_drops_platform():
assert client.primary_platform == "wechat"
+def test_multi_im_client_remove_pending_platform_completes_ready():
+ slack = _StubClient("slack")
+ discord = _StubClient("discord")
+ client = MultiIMClient({"slack": slack, "discord": discord}, primary_platform="slack")
+ ready_calls: list[bool] = []
+
+ async def on_ready():
+ ready_calls.append(True)
+
+ client.register_callbacks(on_ready=on_ready)
+
+ assert slack.on_ready_callback is not None
+ asyncio.run(slack.on_ready_callback())
+ assert ready_calls == []
+
+ removed = client.remove_client("discord")
+
+ assert removed is discord
+ assert ready_calls == [True]
+
+
+def test_multi_im_client_run_returns_when_all_enabled_threads_exit():
+ client = MultiIMClient({"slack": _StubClient("slack")}, primary_platform="slack")
+ returned: list[bool] = []
+
+ def _run() -> None:
+ client.run()
+ returned.append(True)
+
+ thread = threading.Thread(target=_run, daemon=True)
+ thread.start()
+
+ thread.join(timeout=2)
+
+ assert thread.is_alive() is False
+ assert returned == [True]
+
+
+def test_multi_im_client_remove_client_keeps_maps_when_thread_will_not_stop():
+ stuck = _StubClient("slack", run_until_stopped=True)
+ client = MultiIMClient({"slack": stuck}, primary_platform="slack")
+ never_stop = threading.Event()
+ thread = threading.Thread(target=never_stop.wait, daemon=True)
+ thread.start()
+ client._threads["slack"] = thread
+
+ try:
+ try:
+ client.remove_client("slack")
+ except IMClientRemovalError:
+ pass
+ else:
+ raise AssertionError("remove_client should fail when the old runtime thread stays alive")
+
+ assert client.clients["slack"] is stuck
+ assert client._threads["slack"] is thread
+ finally:
+ never_stop.set()
+ thread.join(timeout=2)
+
+
def test_multi_im_client_empty_runtime_stays_alive_until_stop():
client = MultiIMClient({}, primary_platform="avibe")
returned: list[bool] = []
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 566bbef4f..cb49e5ce0 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -431,6 +431,44 @@ def test_config_post_schedules_service_restart_when_hot_reconcile_unavailable(mo
assert restart_calls == [True]
+def test_config_post_schedules_service_restart_when_hot_reconcile_fails(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ from vibe import api
+ from vibe import internal_client
+
+ payload = _full_config_payload()
+ payload["platforms"] = {"enabled": ["discord"], "primary": "discord"}
+ api.save_config(payload)
+
+ async def _reconcile_platforms():
+ return {
+ "status_code": 500,
+ "body": {"ok": False, "error": "IM thread for discord did not stop within timeout"},
+ }
+
+ restart_calls = []
+ monkeypatch.setattr(internal_client, "reconcile_platforms", _reconcile_platforms)
+ monkeypatch.setattr(
+ ui_server,
+ "_schedule_service_restart_for_config_fallback",
+ lambda: restart_calls.append(True) or {"ok": True, "restart": {"job_id": "job-hot-failure"}},
+ )
+
+ client = app.test_client()
+ response = client.post(
+ "/api/config",
+ json={"discord": {"bot_token": "discord-new-token-12345"}},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ runtime = response.get_json()["platform_runtime"]
+ assert runtime["hot_reconciled"] is False
+ assert runtime["restart_scheduled"] is True
+ assert runtime["body"]["error"] == "IM thread for discord did not stop within timeout"
+ assert restart_calls == [True]
+
+
def test_static_ui_assets_use_cache_headers(monkeypatch, tmp_path):
ui_dist = tmp_path / "dist"
assets_dir = ui_dist / "assets"