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(wechat): unblock commands behind running sessions

cyh801a5eb4d0e1
diff --git a/modules/im/wechat.py b/modules/im/wechat.py
index 44bd048dd..312cf2007 100644
--- a/modules/im/wechat.py
+++ b/modules/im/wechat.py
@@ -374,6 +374,8 @@ class WeChatAuthManager:
class WeChatBot(BaseIMClient):
"""WeChat personal messaging adapter via iLink bot protocol."""
+ _MAX_IN_FLIGHT_MESSAGE_CALLBACK_TASKS = 100
+
def __init__(self, config: WeChatConfig):
super().__init__(config)
self.config: WeChatConfig = config
@@ -382,6 +384,7 @@ class WeChatBot(BaseIMClient):
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._stop_event: Optional[asyncio.Event] = None
self._poll_task: Optional[asyncio.Task] = None
+ self._message_callback_tasks: Set[asyncio.Task[Any]] = set()
# Context tokens per user (needed for replies)
self._context_tokens: Dict[str, str] = {}
@@ -1174,6 +1177,30 @@ class WeChatBot(BaseIMClient):
# Inbound message processing
# ------------------------------------------------------------------
+ async def _wait_for_message_callback_capacity(self) -> None:
+ while len(self._message_callback_tasks) >= self._MAX_IN_FLIGHT_MESSAGE_CALLBACK_TASKS:
+ pending = tuple(self._message_callback_tasks)
+ if not pending:
+ return
+ await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
+
+ async def _spawn_message_callback_task(self, context: MessageContext, text: str) -> None:
+ if not self.on_message_callback:
+ return
+ await self._wait_for_message_callback_capacity()
+ task = asyncio.create_task(self.on_message_callback(context, text))
+ self._message_callback_tasks.add(task)
+ task.add_done_callback(self._handle_message_callback_task_done)
+
+ def _handle_message_callback_task_done(self, task: asyncio.Task[Any]) -> None:
+ self._message_callback_tasks.discard(task)
+ try:
+ task.result()
+ except asyncio.CancelledError:
+ return
+ except Exception:
+ logger.exception("WeChat message callback task failed")
+
async def _process_inbound_message(self, msg: dict) -> None:
"""Convert an iLink message to MessageContext and dispatch."""
message_id = str(msg.get("message_id", ""))
@@ -1261,7 +1288,7 @@ class WeChatBot(BaseIMClient):
# Dispatch to message handler
if self.on_message_callback:
try:
- await self.on_message_callback(context, text)
+ await self._spawn_message_callback_task(context, text)
except Exception as exc:
logger.error(
"Message callback error for user %s: %s",
diff --git a/tests/test_wechat_bot.py b/tests/test_wechat_bot.py
index 5e32736c2..fc918e398 100644
--- a/tests/test_wechat_bot.py
+++ b/tests/test_wechat_bot.py
@@ -1,3 +1,4 @@
+import asyncio
import unittest
from unittest.mock import AsyncMock
from pathlib import Path
@@ -213,12 +214,59 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):
}
await bot._process_inbound_message(msg)
+ await asyncio.gather(*tuple(bot._message_callback_tasks))
bot.on_message_callback.assert_awaited_once()
args = bot.on_message_callback.await_args.args # type: ignore[union-attr]
self.assertEqual(args[0].user_id, "user-1")
self.assertEqual(args[1], "hi")
+ async def test_process_inbound_message_does_not_block_commands_behind_running_callback(self):
+ bot = self._make_bot()
+ bot.check_authorization = lambda **kwargs: AuthResult(allowed=True, is_dm=True)
+ bot._process_media_items = AsyncMock(return_value=None)
+
+ callback_started = asyncio.Event()
+ release_callback = asyncio.Event()
+
+ async def running_callback(_context, _text: str):
+ callback_started.set()
+ await release_callback.wait()
+
+ async def dispatch_command(_context, text: str, allow_plain_bind: bool = False) -> bool:
+ return text == "/new"
+
+ bot.on_message_callback = running_callback
+ bot.dispatch_text_command = AsyncMock(side_effect=dispatch_command)
+
+ normal_msg = {
+ "message_id": "mid-1",
+ "from_user_id": "user-1",
+ "context_token": "ctx-1",
+ "item_list": [{"type": 1, "text_item": {"text": "hi"}}],
+ }
+ command_msg = {
+ "message_id": "mid-2",
+ "from_user_id": "user-1",
+ "context_token": "ctx-1",
+ "item_list": [{"type": 1, "text_item": {"text": "/new"}}],
+ }
+
+ first_task = asyncio.create_task(bot._process_inbound_message(normal_msg))
+ await asyncio.sleep(0)
+ self.assertTrue(first_task.done())
+ await callback_started.wait()
+
+ second_task = asyncio.create_task(bot._process_inbound_message(command_msg))
+ await asyncio.sleep(0)
+ self.assertTrue(second_task.done())
+
+ dispatched_texts = [call.args[1] for call in bot.dispatch_text_command.await_args_list]
+ self.assertEqual(dispatched_texts, ["hi", "/new"])
+
+ release_callback.set()
+ await asyncio.gather(*tuple(bot._message_callback_tasks))
+
async def test_process_media_items_falls_back_to_referenced_media(self):
bot = self._make_bot()
context = MessageContext(user_id="user-1", channel_id="user-1", files=[])