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(platforms): centralize IM callbacks on controller loop

cyhhaoe21fd5effddf
diff --git a/core/controller.py b/core/controller.py
index eab0d1987..ad38c6025 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -4,6 +4,7 @@ import asyncio
import json
import os
import logging
+import threading
from typing import Optional, Dict, Any
from config import paths
from modules.im import BaseIMClient, MessageContext, IMFactory
@@ -34,6 +35,9 @@ class Controller:
"""Initialize controller with configuration"""
self.config = config
self._config_mtime: Optional[float] = None
+ self._loop: Optional[asyncio.AbstractEventLoop] = None
+ self._im_thread: Optional[threading.Thread] = None
+ self._im_run_exception: Optional[BaseException] = None
self.enabled_platforms = list(getattr(config, "enabled_platforms", lambda: [config.platform])())
self.primary_platform = getattr(getattr(config, "platforms", None), "primary", config.platform)
@@ -286,28 +290,60 @@ class Controller:
# Admin protection for "set_cwd" and "settings" is now handled by
# the centralized auth pipeline (core.auth.check_auth) in IM entry points.
command_handlers = {
- "start": self.command_handler.handle_start,
- "new": self.command_handler.handle_new,
- "cwd": self.command_handler.handle_cwd,
- "set_cwd": self.command_handler.handle_set_cwd,
- "settings": self.settings_handler.handle_settings,
- "stop": self.command_handler.handle_stop,
- "bind": self.command_handler.handle_bind,
+ "start": self._dispatch_to_controller_loop(self.command_handler.handle_start),
+ "new": self._dispatch_to_controller_loop(self.command_handler.handle_new),
+ "cwd": self._dispatch_to_controller_loop(self.command_handler.handle_cwd),
+ "set_cwd": self._dispatch_to_controller_loop(self.command_handler.handle_set_cwd),
+ "settings": self._dispatch_to_controller_loop(self.settings_handler.handle_settings),
+ "stop": self._dispatch_to_controller_loop(self.command_handler.handle_stop),
+ "bind": self._dispatch_to_controller_loop(self.command_handler.handle_bind),
}
# Register callbacks with the IM client
self.im_client.register_callbacks(
- on_message=self.message_handler.handle_user_message,
+ on_message=self._dispatch_to_controller_loop(self.message_handler.handle_user_message),
on_command=command_handlers,
- on_callback_query=self.message_handler.handle_callback_query,
- on_settings_update=self.settings_handler.handle_settings_update,
- on_change_cwd=self.command_handler.handle_change_cwd_submission,
- on_routing_update=self.settings_handler.handle_routing_update,
- on_routing_modal_update=self.settings_handler.handle_routing_modal_update,
- on_resume_session=self.session_handler.handle_resume_session_submission,
- on_ready=self._on_im_ready,
+ on_callback_query=self._dispatch_to_controller_loop(self.message_handler.handle_callback_query),
+ on_settings_update=self._dispatch_to_controller_loop(self.settings_handler.handle_settings_update),
+ on_change_cwd=self._dispatch_to_controller_loop(self.command_handler.handle_change_cwd_submission),
+ on_routing_update=self._dispatch_to_controller_loop(self.settings_handler.handle_routing_update),
+ on_routing_modal_update=self._dispatch_to_controller_loop(
+ self.settings_handler.handle_routing_modal_update
+ ),
+ on_resume_session=self._dispatch_to_controller_loop(self.session_handler.handle_resume_session_submission),
+ on_ready=self._dispatch_to_controller_loop(self._on_im_ready),
)
+ def _dispatch_to_controller_loop(self, callback):
+ async def _wrapped(*args, **kwargs):
+ loop = self._loop
+ if loop is None:
+ return await callback(*args, **kwargs)
+
+ try:
+ current_loop = asyncio.get_running_loop()
+ except RuntimeError:
+ current_loop = None
+
+ if current_loop is loop:
+ return await callback(*args, **kwargs)
+
+ future = asyncio.run_coroutine_threadsafe(callback(*args, **kwargs), loop)
+ return await asyncio.wrap_future(future)
+
+ return _wrapped
+
+ def _run_im_runtime(self) -> None:
+ try:
+ self.im_client.run()
+ except BaseException as exc: # noqa: BLE001
+ self._im_run_exception = exc
+ logger.error("IM runtime thread exited with error: %s", exc, exc_info=True)
+ finally:
+ loop = self._loop
+ if loop and loop.is_running():
+ loop.call_soon_threadsafe(loop.stop)
+
async def _on_im_ready(self):
"""Called when IM client is connected and ready.
@@ -464,20 +500,27 @@ class Controller:
"""Run the controller"""
logger.info("Starting Claude Proxy Controller with platforms: %s", ", ".join(self.enabled_platforms))
- # 不再创建额外事件循环,避免与 IM 客户端的内部事件循环冲突
- # 清理职责改为:
- # - 进程退出时做一次同步的 best-effort 取消(不跨循环 await)
-
try:
- # Run the IM client (blocking)
- self.im_client.run()
+ self._loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(self._loop)
+ self._im_thread = threading.Thread(target=self._run_im_runtime, name="im-runtime", daemon=True)
+ self._im_thread.start()
+ self._loop.run_forever()
+ if self._im_run_exception and not isinstance(self._im_run_exception, (KeyboardInterrupt, SystemExit)):
+ raise self._im_run_exception
except KeyboardInterrupt:
logger.info("Received keyboard interrupt, shutting down...")
except Exception as e:
logger.error(f"Error in main run loop: {e}", exc_info=True)
finally:
- # Best-effort 同步清理,避免跨事件循环 await
self.cleanup_sync()
+ if self._loop is not None:
+ try:
+ self._loop.stop()
+ except Exception:
+ pass
+ self._loop.close()
+ self._loop = None
async def periodic_cleanup(self):
"""[Deprecated] Periodic cleanup is disabled in favor of safe on-demand cleanup"""
@@ -525,15 +568,22 @@ class Controller:
import inspect
if inspect.iscoroutinefunction(shutdown_attr):
- try:
- asyncio.run(shutdown_attr())
- except RuntimeError:
- pass
+ loop = self._loop
+ if loop and loop.is_running():
+ try:
+ future = asyncio.run_coroutine_threadsafe(shutdown_attr(), loop)
+ future.result(timeout=5)
+ except Exception:
+ pass
else:
shutdown_attr()
except Exception as e:
logger.warning("Failed to shutdown IM client: %s", e)
+ if self._im_thread and self._im_thread.is_alive():
+ self._im_thread.join(timeout=5)
+ self._im_thread = None
+
# Stop OpenCode server if running
try:
from modules.agents.opencode import OpenCodeServerManager
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index 45a6dfeb3..0f448bcce 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -100,7 +100,9 @@ class CommandHandlers(BaseHandler):
# "New Session" button/command is unnecessary.
is_dm = bool((context.platform_specific or {}).get("is_dm", False))
supports_threads = (
- im_client.should_use_thread_for_dm_session() if is_dm else im_client.should_use_thread_for_reply()
+ getattr(im_client, "should_use_thread_for_dm_session", lambda: False)()
+ if is_dm
+ else getattr(im_client, "should_use_thread_for_reply", lambda: False)()
)
# For non-interactive platforms, use traditional text message
diff --git a/modules/im/multi.py b/modules/im/multi.py
index be2d24e3f..d6ce32041 100644
--- a/modules/im/multi.py
+++ b/modules/im/multi.py
@@ -9,7 +9,7 @@ import threading
import time
from typing import Any, Callable, Dict, Optional, cast
-from config.v2_settings import _infer_channel_platform, _infer_user_platform
+from config.v2_settings import _infer_channel_platform, _infer_user_platform, _split_scoped_key
from .base import BaseIMClient, InlineKeyboard, MessageContext
logger = logging.getLogger(__name__)
@@ -263,14 +263,16 @@ class MultiIMClient(BaseIMClient):
logger.exception("IM runtime for %s crashed", platform)
async def get_user_info(self, user_id: str) -> Dict[str, Any]:
- platform = _infer_user_platform(user_id)
+ 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])
- return await client.get_user_info(user_id)
+ return await client.get_user_info(raw_user_id)
async def get_channel_info(self, channel_id: str) -> Dict[str, Any]:
- platform = _infer_channel_platform(channel_id)
+ 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])
- return await client.get_channel_info(channel_id)
+ return await client.get_channel_info(raw_channel_id)
async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
return await self.get_client_for_context(context).add_reaction(context, message_id, emoji)
@@ -285,9 +287,10 @@ class MultiIMClient(BaseIMClient):
return await self.get_client_for_context(context).clear_typing_indicator(context)
async def send_dm(self, user_id: str, text: str, **kwargs):
- platform = _infer_user_platform(user_id)
+ 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])
- return await client.send_dm(user_id, text, **kwargs)
+ return await client.send_dm(raw_user_id, text, **kwargs)
def stop(self):
self._stop_requested.set()
diff --git a/tests/test_controller_dispatch_loop.py b/tests/test_controller_dispatch_loop.py
new file mode 100644
index 000000000..fbc65e76a
--- /dev/null
+++ b/tests/test_controller_dispatch_loop.py
@@ -0,0 +1,46 @@
+from __future__ import annotations
+
+import asyncio
+import threading
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core.controller import Controller
+
+
+def test_dispatch_to_controller_loop_runs_callback_on_controller_loop():
+ controller = Controller.__new__(Controller)
+ loop = asyncio.new_event_loop()
+ controller._loop = loop
+ result: dict[str, object] = {}
+
+ async def callback(value: str) -> str:
+ result["thread"] = threading.current_thread().name
+ result["loop"] = asyncio.get_running_loop()
+ result["value"] = value
+ return value.upper()
+
+ wrapped = Controller._dispatch_to_controller_loop(controller, callback)
+
+ def _loop_runner() -> None:
+ asyncio.set_event_loop(loop)
+ loop.run_forever()
+
+ loop_thread = threading.Thread(target=_loop_runner, name="controller-loop", daemon=True)
+ loop_thread.start()
+
+ async def _invoke() -> str:
+ return await wrapped("hello")
+
+ try:
+ output = asyncio.run(_invoke())
+ finally:
+ loop.call_soon_threadsafe(loop.stop)
+ loop_thread.join(timeout=2)
+ loop.close()
+
+ assert output == "HELLO"
+ assert result["thread"] == "controller-loop"
+ assert result["value"] == "hello"
diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.py
index eb856a800..8f50e8725 100644
--- a/tests/test_multi_platform_runtime.py
+++ b/tests/test_multi_platform_runtime.py
@@ -49,6 +49,10 @@ class _StubClient(BaseIMClient):
async def get_channel_info(self, channel_id: str):
return {"id": channel_id, "name": self.name}
+ async def send_dm(self, user_id: str, text: str, **kwargs):
+ self.sent.append(("dm", user_id, text))
+ return self.name
+
def format_markdown(self, text: str) -> str:
return text
@@ -94,3 +98,17 @@ def test_multi_im_client_annotates_inbound_context_platform():
asyncio.run(callback(MessageContext(user_id="u", channel_id="c"), "hello"))
assert captured == ["wechat"]
+
+
+def test_multi_im_client_routes_scoped_identity_lookups():
+ slack = _StubClient("slack")
+ wechat = _StubClient("wechat")
+ client = MultiIMClient({"slack": slack, "wechat": wechat}, primary_platform="slack")
+
+ user_info = asyncio.run(client.get_user_info("wechat::wx-user"))
+ channel_info = asyncio.run(client.get_channel_info("wechat::wx-chat"))
+ asyncio.run(client.send_dm("wechat::wx-user", "hello"))
+
+ assert user_info == {"id": "wx-user", "name": "wechat"}
+ assert channel_info == {"id": "wx-chat", "name": "wechat"}
+ assert wechat.sent[-1] == ("dm", "wx-user", "hello")