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): route message handlers by context

cyhhao3e15e7a8350e
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index f2d4cd678..4db0b036f 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -332,7 +332,7 @@ class MessageHandler(BaseHandler):
async def _prepend_user_info(self, context: MessageContext, message: str) -> str:
"""Prepend user identity as [username<user_id>] to the message."""
try:
- user_info = await self.im_client.get_user_info(context.user_id)
+ user_info = await self._get_im_client(context).get_user_info(context.user_id)
raw_name = self._resolve_user_display_name(user_info, context.user_id)
except Exception as e:
logger.debug(f"Failed to fetch user info for {context.user_id}: {e}")
@@ -345,6 +345,7 @@ class MessageHandler(BaseHandler):
"""Route callback queries to appropriate handlers"""
try:
logger.info(f"handle_callback_query called with data: {callback_data} for user {context.user_id}")
+ im_client = self._get_im_client(context)
settings_handler = self.controller.settings_handler
command_handlers = self.controller.command_handler
@@ -397,7 +398,7 @@ class MessageHandler(BaseHandler):
if hasattr(self.controller, "update_checker"):
await self.controller.update_checker.handle_update_button_click(context, target_version)
else:
- await self.im_client.send_message(
+ await im_client.send_message(
context,
self.formatter.format_warning(self._t("error.updateUnavailable")),
)
@@ -410,7 +411,7 @@ class MessageHandler(BaseHandler):
emoji="ℹ️",
footer=self._t("info.genericFooter"),
)
- await self.im_client.send_message(context, info_text)
+ await im_client.send_message(context, info_text)
elif callback_data.startswith("resume_session:"):
# Feishu resume button: resume_session:{agent}:{session_id}
@@ -484,7 +485,7 @@ class MessageHandler(BaseHandler):
)
try:
if remove_target_message_id or can_remove_via_interaction:
- await self.im_client.remove_inline_keyboard(context, remove_target_message_id or "")
+ await im_client.remove_inline_keyboard(context, remove_target_message_id or "")
else:
logger.debug("Skip quick-reply keyboard removal: message id unavailable")
except Exception as err:
@@ -494,7 +495,7 @@ class MessageHandler(BaseHandler):
quick_reply_echo_id = None
try:
quick_reply_echo = self._t("message.quickReplyNote", text=reply_text)
- quick_reply_echo_id = await self.im_client.send_message(
+ quick_reply_echo_id = await im_client.send_message(
self._get_target_context(context),
quick_reply_echo,
)
@@ -504,7 +505,7 @@ class MessageHandler(BaseHandler):
# Add ack reaction on the echo message before dispatching.
if quick_reply_echo_id and getattr(self.config, "ack_mode", "reaction") == "reaction":
try:
- await self.im_client.add_reaction(
+ await im_client.add_reaction(
self._get_target_context(context),
quick_reply_echo_id,
":eyes:",
@@ -526,14 +527,14 @@ class MessageHandler(BaseHandler):
else:
logger.warning(f"Unknown callback data: {callback_data}")
- await self.im_client.send_message(
+ await im_client.send_message(
context,
self.formatter.format_warning(self._t("error.unknownAction", action=callback_data)),
)
except Exception as e:
logger.error(f"Error handling callback query: {e}", exc_info=True)
- await self.im_client.send_message(
+ await self._get_im_client(context).send_message(
context,
self.formatter.format_error(self._t("error.processActionFailed", error=str(e))),
)
@@ -561,7 +562,7 @@ class MessageHandler(BaseHandler):
await self._handle_missing_agent(context, agent_name)
return False
if not handled:
- await self.im_client.send_message(context, f"ℹ️ {self._t('command.stop.noActiveSession')}")
+ await self._get_im_client(context).send_message(context, f"ℹ️ {self._t('command.stop.noActiveSession')}")
return handled
except Exception as e:
logger.error(f"Error handling inline stop: {e}", exc_info=True)
@@ -571,13 +572,14 @@ class MessageHandler(BaseHandler):
"""Notify user when a requested agent backend is unavailable."""
target = agent_name or self.controller.agent_service.default_agent
msg = f"❌ {self._t('error.agentNotConfigured', agent=target)}"
- await self.im_client.send_message(context, msg)
+ await self._get_im_client(context).send_message(context, msg)
async def _delete_ack(self, channel_id: str, request: AgentRequest):
"""Delete acknowledgement message if it still exists."""
- if request.ack_message_id and hasattr(self.im_client, "delete_message"):
+ im_client = self._get_im_client(request.context)
+ if request.ack_message_id and hasattr(im_client, "delete_message"):
try:
- await self.im_client.delete_message(channel_id, request.ack_message_id)
+ await im_client.delete_message(channel_id, request.ack_message_id)
except Exception as err:
logger.debug(f"Failed to delete ack message: {err}")
finally:
@@ -585,6 +587,7 @@ class MessageHandler(BaseHandler):
async def _remove_ack_reaction(self, context: MessageContext, request: AgentRequest):
"""Remove acknowledgement reaction / typing indicator if it still exists."""
+ im_client = self._get_im_client(context)
typing_task = request.typing_indicator_task
if typing_task is not None:
typing_task.cancel()
@@ -599,7 +602,7 @@ class MessageHandler(BaseHandler):
if request.typing_indicator_active:
try:
- await self.im_client.clear_typing_indicator(context)
+ await im_client.clear_typing_indicator(context)
except Exception as err:
logger.debug(f"Failed to clear typing ack: {err}")
finally:
@@ -607,7 +610,7 @@ class MessageHandler(BaseHandler):
if request.ack_reaction_message_id and request.ack_reaction_emoji:
try:
- await self.im_client.remove_reaction(
+ await im_client.remove_reaction(
context,
request.ack_reaction_message_id,
request.ack_reaction_emoji,
@@ -660,8 +663,9 @@ class MessageHandler(BaseHandler):
continue
try:
+ im_client = self._get_im_client(context)
# Download the file content
- if hasattr(self.im_client, "download_file") and attachment.url:
+ if hasattr(im_client, "download_file") and attachment.url:
# Platform-agnostic download info dict
file_info = {
"url": attachment.url,
@@ -683,9 +687,9 @@ class MessageHandler(BaseHandler):
detected_sample = None
content_size = None
- if hasattr(self.im_client, "download_file_to_path"):
+ if hasattr(im_client, "download_file_to_path"):
self._cleanup_partial_attachment(temp_path)
- result = await self.im_client.download_file_to_path(file_info, str(temp_path))
+ result = await im_client.download_file_to_path(file_info, str(temp_path))
if not isinstance(result, FileDownloadResult):
result = FileDownloadResult(bool(result), None if result else "Download failed")
@@ -700,7 +704,7 @@ class MessageHandler(BaseHandler):
logger.warning("Failed to download file %s: %s", attachment.name, error_text)
errors.append(f"Attachment '{attachment.name}' could not be downloaded: {error_text}")
else:
- content = await self.im_client.download_file(file_info)
+ content = await im_client.download_file(file_info)
if content:
with open(local_path, "wb") as f:
f.write(content)
diff --git a/modules/im/discord.py b/modules/im/discord.py
index 4ed9122e8..23b99f81f 100644
--- a/modules/im/discord.py
+++ b/modules/im/discord.py
@@ -170,6 +170,7 @@ class DiscordBot(BaseIMClient):
raise ValueError("Discord bot token is required")
async def _run():
+ self._loop = asyncio.get_running_loop()
# Inject SOCKS proxy connector inside the event loop (required
# by aiohttp). Must happen before login() creates the session.
from vibe.proxy import get_system_socks_proxy
@@ -192,6 +193,15 @@ class DiscordBot(BaseIMClient):
except KeyboardInterrupt:
return
+ def stop(self) -> None:
+ loop = getattr(self, "_loop", None)
+ if loop is None or loop.is_closed():
+ return
+ try:
+ loop.call_soon_threadsafe(lambda: loop.create_task(self.client.close()))
+ except Exception:
+ logger.exception("Failed to stop Discord client")
+
@staticmethod
def _redact_proxy_url(proxy_url: str) -> str:
"""Return a proxy URL safe for logs (credentials stripped)."""
@@ -209,7 +219,10 @@ class DiscordBot(BaseIMClient):
return "<configured>"
async def shutdown(self) -> None:
- await self.client.close()
+ loop = getattr(self, "_loop", None)
+ current_loop = asyncio.get_running_loop()
+ if loop is None or loop is current_loop:
+ await self.client.close()
# ---------------------------------------------------------------------
# Message helpers
diff --git a/modules/im/multi.py b/modules/im/multi.py
index 58f4cc062..be2d24e3f 100644
--- a/modules/im/multi.py
+++ b/modules/im/multi.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
import inspect
import logging
import threading
@@ -300,7 +301,13 @@ class MultiIMClient(BaseIMClient):
async def shutdown(self) -> None:
self._stop_requested.set()
+ self.stop()
+ for thread in list(self._threads.values()):
+ await asyncio.to_thread(thread.join, 2.0)
+
for client in self.clients.values():
+ if any(thread.is_alive() for thread in self._threads.values()):
+ break
shutdown_attr = getattr(client, "shutdown", None)
if callable(shutdown_attr):
try:
diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.py
index 8c9494e30..f7a5dd4ec 100644
--- a/tests/test_message_handler_typing.py
+++ b/tests/test_message_handler_typing.py
@@ -96,6 +96,15 @@ class _StubIMClient:
def should_use_thread_for_reply(self):
return False
+ async def get_user_info(self, user_id):
+ return {"display_name": f"user:{user_id}"}
+
+ async def download_file_to_path(self, file_info, target_path):
+ self.sent_messages.append(("download", file_info["name"], target_path))
+ from modules.im.base import FileDownloadResult
+
+ return FileDownloadResult(False, "not implemented")
+
async def send_typing_indicator(self, context):
self.typing_calls.append((context.channel_id, context.user_id))
return self.typing_result
@@ -143,6 +152,9 @@ class _StubController:
def update_thread_message_id(self, context):
return None
+ def get_im_client_for_context(self, context):
+ return self.im_client
+
def resolve_agent_for_context(self, context):
return "codex"
@@ -211,6 +223,22 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(controller.im_client.reactions, [])
self.assertGreaterEqual(len(controller.im_client.typing_calls), 1)
+ async def test_platform_specific_client_is_used_for_user_info(self):
+ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)
+ handler = MessageHandler(controller)
+ context = MessageContext(user_id="wx-user", channel_id="wx-chat", platform="wechat")
+
+ class _WechatClient(_StubIMClient):
+ async def get_user_info(self, user_id):
+ return {"display_name": "WeChat User"}
+
+ wechat_client = _WechatClient(typing_result=True)
+ controller.get_im_client_for_context = lambda _context: wechat_client # type: ignore[method-assign]
+
+ result = await handler._prepend_user_info(context, "hello")
+
+ self.assertEqual(result, "[WeChat User<wx-user>] hello")
+
if __name__ == "__main__":
unittest.main()