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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(wechat): drop fake login probe and reject empty recipients (#1587)
rkrkrkkbcc354a02c1f
diff --git a/modules/im/wechat.py b/modules/im/wechat.pyindex eeb26eb16..117dda806 100644--- a/modules/im/wechat.py+++ b/modules/im/wechat.py@@ -75,6 +75,15 @@ def _get_updates_error_code(resp: Optional[Dict[str, Any]]) -> Any:return code if code not in (None, 0) else None+def _require_outbound_recipient(context: MessageContext) -> str:+ """Return the iLink recipient, or raise before an empty id can leave this process."""+ raw = getattr(context, "user_id", None)+ user_id = str(raw).strip() if raw is not None else ""+ if not user_id:+ raise ValueError("WeChat outbound send rejected: empty recipient user_id")+ return user_id++# ---------------------------------------------------------------------------# Constants# ---------------------------------------------------------------------------@@ -384,55 +393,6 @@ class _WeChatCDN:wechat_cdn = _WeChatCDN()-# ----------------------------------------------------------------------------# Auth manager (QR code login lifecycle)-# ------------------------------------------------------------------------------class WeChatAuthManager:- """Manages QR code login flow and token refresh for iLink bots."""-- def __init__(self) -> None:- self.login_url: Optional[str] = None- self.is_logged_in: bool = False-- async def check_login_status(self, base_url: str, token: str) -> bool:- """Verify the bot token is valid and the session is active."""- try:- url = f"{base_url}/getLoginStatus"- payload = {"token": token}- async with aiohttp.ClientSession(- timeout=aiohttp.ClientTimeout(total=10),- ) as session:- async with session.post(url, json=payload) as resp:- if resp.status != 200:- return False- data = await resp.json()- self.is_logged_in = data.get("ret", -1) == 0- return self.is_logged_in- except Exception as exc:- logger.warning("Login status check failed: %s", exc)- return False-- async def request_qr_login(self, base_url: str, token: str) -> Optional[str]:- """Request a new QR code login URL."""- try:- url = f"{base_url}/getQRCode"- payload = {"token": token}- async with aiohttp.ClientSession(- timeout=aiohttp.ClientTimeout(total=10),- ) as session:- async with session.post(url, json=payload) as resp:- if resp.status != 200:- return None- data = await resp.json()- self.login_url = data.get("qr_url")- return self.login_url- except Exception as exc:- logger.warning("QR login request failed: %s", exc)- return None--# ---------------------------------------------------------------------------# Main adapter# ---------------------------------------------------------------------------@@ -464,9 +424,6 @@ class WeChatBot(BaseIMClient):self._session_expired_logged: bool = Falseself._connection_notified: bool = False- # Auth manager- self._auth_manager = WeChatAuthManager()-# Injected collaborators (set by controller)self.settings_manager: Any = Noneself.sessions: Any = None@@ -599,7 +556,7 @@ class WeChatBot(BaseIMClient):if not text:raise ValueError("WeChat send_message requires non-empty text")- user_id = context.user_id+ user_id = _require_outbound_recipient(context)context_token = self._get_context_token(context)# Build TEXT item@@ -729,7 +686,7 @@ class WeChatBot(BaseIMClient):context: MessageContext,) -> bool:"""Send a typing indicator (best-effort, don't block on errors)."""- user_id = context.user_id+ user_id = _require_outbound_recipient(context)context_token = self._get_context_token(context)if not context_token:return False@@ -755,7 +712,7 @@ class WeChatBot(BaseIMClient):async def clear_typing_indicator(self, context: MessageContext) -> bool:"""Cancel the active typing indicator for the current WeChat DM."""- user_id = context.user_id+ user_id = _require_outbound_recipient(context)context_token = self._get_context_token(context)if not context_token:return False@@ -795,6 +752,7 @@ class WeChatBot(BaseIMClient):title: Optional[str] = None,) -> str:"""Upload a file via CDN and send it as a file message."""+ user_id = _require_outbound_recipient(context)if self._is_video_file(file_path, title):return await self.upload_video_from_path(context, file_path, title=title)@@ -802,7 +760,7 @@ class WeChatBot(BaseIMClient):self.config.base_url,self.config.bot_token,getattr(self.config, "cdn_base_url", self.config.base_url),- context.user_id,+ user_id,file_path,proxy=self._proxy_url,)@@ -810,7 +768,6 @@ class WeChatBot(BaseIMClient):logger.error("Failed to upload file to CDN: %s", file_path)return ""- user_id = context.user_idcontext_token = self._get_context_token(context)display_name = title or Path(file_path).name@@ -854,6 +811,7 @@ class WeChatBot(BaseIMClient):title: Optional[str] = None,) -> str:"""Upload an image via CDN and send it as an image message."""+ user_id = _require_outbound_recipient(context)if self._is_video_file(file_path, title):return await self.upload_video_from_path(context, file_path, title=title)@@ -861,7 +819,7 @@ class WeChatBot(BaseIMClient):self.config.base_url,self.config.bot_token,getattr(self.config, "cdn_base_url", self.config.base_url),- context.user_id,+ user_id,file_path,proxy=self._proxy_url,)@@ -869,7 +827,6 @@ class WeChatBot(BaseIMClient):logger.error("Failed to upload image to CDN: %s", file_path)return ""- user_id = context.user_idcontext_token = self._get_context_token(context)item_list = [@@ -912,11 +869,12 @@ class WeChatBot(BaseIMClient):) -> str:"""Upload a video via CDN and send it as a native video message."""+ user_id = _require_outbound_recipient(context)cdn_meta = await wechat_cdn.upload_file_to_cdn(self.config.base_url,self.config.bot_token,getattr(self.config, "cdn_base_url", self.config.base_url),- context.user_id,+ user_id,file_path,media_type=_wechat_api_mod.UPLOAD_MEDIA_VIDEO,)@@ -924,7 +882,6 @@ class WeChatBot(BaseIMClient):logger.error("Failed to upload video to CDN: %s", file_path)return ""- user_id = context.user_idcontext_token = self._get_context_token(context)display_name = title or Path(file_path).name@@ -1082,64 +1039,57 @@ class WeChatBot(BaseIMClient):logger.info("Starting WeChat bot via iLink protocol...")- async def _start() -> None:- self._loop = asyncio.get_running_loop()- self._stop_event = asyncio.Event()+ try:+ asyncio.run(self._run_until_stopped())+ except KeyboardInterrupt:+ logger.info("WeChat bot shutting down (keyboard interrupt)...")- # Notify on_ready callback (starts UI server even without token)- if self._on_ready:- try:- await self._on_ready()- except Exception as exc:- logger.error("on_ready callback failed: %s", exc, exc_info=True)+ async def _run_until_stopped(self) -> None:+ """Async startup + poll loop until ``stop()`` is signalled."""+ self._loop = asyncio.get_running_loop()+ self._stop_event = asyncio.Event()- if not self.config.bot_token:- logger.info("WeChat bot idling (no bot_token). Complete QR login via the Web UI to activate.")- await self._stop_event.wait()- return+ # Notify on_ready callback (starts UI server even without token)+ if self._on_ready:+ try:+ await self._on_ready()+ except Exception as exc:+ logger.error("on_ready callback failed: %s", exc, exc_info=True)- # Load persisted sync buffer- self._load_sync_buf()- self._load_context_tokens()+ if not self.config.bot_token:+ logger.info("WeChat bot idling (no bot_token). Complete QR login via the Web UI to activate.")+ await self._stop_event.wait()+ return- # Check login status- logged_in = await self._auth_manager.check_login_status(- self.config.base_url,- self.config.bot_token,- )- if logged_in:- logger.info("WeChat bot session is active")- else:- logger.warning(- "WeChat bot session is not active; messages may fail until the session is re-authenticated",- )+ # Load persisted sync buffer+ self._load_sync_buf()+ self._load_context_tokens()- await self._notify_connection_state("start")+ logger.info(+ "WeChat bot starting poll loop; session health is reported by the first poll"+ )- # Start poll loop as a background task- self._poll_task = asyncio.create_task(self._poll_loop())+ await self._notify_connection_state("start")- logger.info("WeChat bot started, entering poll loop")+ # Start poll loop as a background task+ self._poll_task = asyncio.create_task(self._poll_loop())- # Block until stop is signalled- await self._stop_event.wait()+ logger.info("WeChat bot started, entering poll loop")- # Cancel poll task on shutdown- if self._poll_task and not self._poll_task.done():- self._poll_task.cancel()- try:- await self._poll_task- except asyncio.CancelledError:- pass+ # Block until stop is signalled+ await self._stop_event.wait()- await self._notify_connection_state("stop")+ # Cancel poll task on shutdown+ if self._poll_task and not self._poll_task.done():+ self._poll_task.cancel()+ try:+ await self._poll_task+ except asyncio.CancelledError:+ pass- logger.info("WeChat bot stopped")+ await self._notify_connection_state("stop")- try:- asyncio.run(_start())- except KeyboardInterrupt:- logger.info("WeChat bot shutting down (keyboard interrupt)...")+ logger.info("WeChat bot stopped")def stop(self) -> None:"""Signal the bot to stop."""@@ -1167,7 +1117,6 @@ class WeChatBot(BaseIMClient):return max(_MIN_POLL_TIMEOUT_MS, min(_MAX_POLL_TIMEOUT_MS, value))def _mark_session_expired(self, errcode: Any) -> None:- self._auth_manager.is_logged_in = Falseself._typing_tickets.clear()self._clear_context_tokens()if not self._session_expired_logged:@@ -1178,7 +1127,6 @@ class WeChatBot(BaseIMClient):self._session_expired_logged = Truedef _mark_session_active(self) -> None:- self._auth_manager.is_logged_in = Trueself._session_expired_logged = False# ------------------------------------------------------------------diff --git a/tests/test_wechat_bot.py b/tests/test_wechat_bot.pyindex 1c8f0b7aa..0f4cbf12e 100644--- a/tests/test_wechat_bot.py+++ b/tests/test_wechat_bot.py@@ -12,7 +12,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from config.v2_settings import SettingsStore, UserSettingsfrom core.auth import AuthResult-from modules.im import MessageContext+from modules.im import InlineButton, InlineKeyboard, MessageContextfrom modules.im.wechat import WeChatBot, WeChatConfig, _get_updates_error_codefrom modules.im import wechat_api as wechat_api_modulefrom modules.settings_manager import SettingsManager@@ -880,7 +880,6 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):channel_id="user-1",platform_specific={"context_token": "ctx-1"},)- bot._auth_manager.is_logged_in = Truebot._remember_context_token("user-1", "ctx-1")with patch(@@ -893,7 +892,7 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):cache_path = Path(tmpdir) / "state" / "wechat_context_tokens.json"data = json.loads(cache_path.read_text(encoding="utf-8"))- self.assertFalse(bot._auth_manager.is_logged_in)+ self.assertTrue(bot._session_expired_logged)self.assertEqual(data["tokens"], {})async def test_upload_file_from_path_uses_cdn_workflow(self):@@ -958,6 +957,159 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(result, "")+ async def test_startup_does_not_emit_false_session_warning_or_call_non_ilink_urls(self):+ captured_urls: list[str] = []++ class _Response:+ ok = True+ status = 200++ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return False++ async def text(self):+ return '{"ret": 0}'++ async def json(self):+ return {"ret": 0}++ class _Session:+ def __init__(self, *args, **kwargs):+ pass++ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return False++ def post(self, url, *args, **kwargs):+ captured_urls.append(str(url))+ return _Response()++ def get(self, url, *args, **kwargs):+ captured_urls.append(str(url))+ return _Response()++ async def _stop_immediately() -> None:+ assert bot._stop_event is not None+ bot._stop_event.set()++ with tempfile.TemporaryDirectory() as tmpdir:+ with patch.dict("os.environ", {"AVIBE_HOME": tmpdir}):+ bot = self._make_bot()+ with patch("modules.im.wechat_api.aiohttp.ClientSession", side_effect=_Session):+ with patch("modules.im.wechat.aiohttp.ClientSession", side_effect=_Session):+ with patch.object(bot, "_poll_loop", new=_stop_immediately):+ with self.assertLogs("modules.im.wechat", level="INFO") as captured:+ await bot._run_until_stopped()++ messages = [record.getMessage() for record in captured.records]+ self.assertFalse(+ any("session is not active" in message for message in messages),+ messages,+ )+ self.assertTrue(+ any("session health is reported by the first poll" in message for message in messages),+ messages,+ )+ self.assertTrue(captured_urls, "startup should still use real iLink endpoints")+ for url in captured_urls:+ self.assertIn("/ilink/bot/", url, url)+ self.assertNotIn("getLoginStatus", url)+ self.assertNotIn("getQRCode", url)+ self.assertNotIn("getconfig", url)++ async def test_send_message_rejects_empty_recipient_without_http(self):+ bot = self._make_bot()+ for recipient in (None, ""):+ context = MessageContext(+ user_id=recipient, # type: ignore[arg-type]+ channel_id="channel-1",+ platform_specific={"context_token": "ctx-1"},+ )+ with patch(+ "modules.im.wechat.wechat_api.send_message",+ new=AsyncMock(return_value={}),+ ) as mock_send:+ with patch("modules.im.wechat_api.aiohttp.ClientSession") as mock_session:+ with self.assertRaises(ValueError) as raised:+ await bot.send_message(context, "hello")+ self.assertIn("empty", str(raised.exception).lower())+ self.assertIn("recipient", str(raised.exception).lower())+ mock_send.assert_not_awaited()+ mock_session.assert_not_called()++ async def test_send_message_with_buttons_rejects_empty_recipient_without_http(self):+ bot = self._make_bot()+ context = MessageContext(+ user_id="",+ channel_id="channel-1",+ platform_specific={"context_token": "ctx-1"},+ )+ keyboard = InlineKeyboard(buttons=[[InlineButton(text="A", callback_data="a")]])+ with patch(+ "modules.im.wechat.wechat_api.send_message",+ new=AsyncMock(return_value={}),+ ) as mock_send:+ with self.assertRaises(ValueError) as raised:+ await bot.send_message_with_buttons(context, "hello", keyboard)+ self.assertIn("empty recipient", str(raised.exception).lower())+ mock_send.assert_not_awaited()++ async def test_send_message_passes_valid_recipient_through_as_to_user_id(self):+ bot = self._make_bot()+ recipient = "[email protected]"+ context = MessageContext(+ user_id=recipient,+ channel_id=recipient,+ platform_specific={"context_token": "ctx-1"},+ )+ with patch(+ "modules.im.wechat.wechat_api.send_message",+ new=AsyncMock(return_value={}),+ ) as mock_send:+ result = await bot.send_message(context, "hello")++ self.assertTrue(result.startswith("wc-"))+ mock_send.assert_awaited_once()+ self.assertEqual(mock_send.await_args.args[2], recipient) # type: ignore[union-attr]++ async def test_file_and_typing_paths_reject_empty_recipient_without_http(self):+ bot = self._make_bot()+ context = MessageContext(+ user_id="",+ channel_id="channel-1",+ platform_specific={"context_token": "ctx-1"},+ )+ with tempfile.TemporaryDirectory() as tmpdir:+ file_path = str(Path(tmpdir) / "note.txt")+ Path(file_path).write_text("x", encoding="utf-8")+ with patch("modules.im.wechat.wechat_api.send_message", new=AsyncMock()) as mock_send:+ with patch("modules.im.wechat.wechat_cdn.upload_file_to_cdn", new=AsyncMock()) as mock_file:+ with patch("modules.im.wechat.wechat_cdn.upload_image_to_cdn", new=AsyncMock()) as mock_image:+ with patch("modules.im.wechat.wechat_api.get_config", new=AsyncMock()) as mock_config:+ with patch("modules.im.wechat.wechat_api.send_typing", new=AsyncMock()) as mock_typing:+ for action in (+ lambda: bot.send_typing_indicator(context),+ lambda: bot.clear_typing_indicator(context),+ lambda: bot.upload_file_from_path(context, file_path),+ lambda: bot.upload_image_from_path(context, file_path),+ lambda: bot.upload_video_from_path(context, file_path),+ ):+ with self.assertRaises(ValueError) as raised:+ await action()+ self.assertIn("empty recipient", str(raised.exception).lower())++ mock_send.assert_not_awaited()+ mock_file.assert_not_awaited()+ mock_image.assert_not_awaited()+ mock_config.assert_not_awaited()+ mock_typing.assert_not_awaited()+if __name__ == "__main__":unittest.main()