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): align iLink interface metadata (#605)

Call White2ba07811c405
diff --git a/modules/im/wechat.py b/modules/im/wechat.py
index 34fe40061..05e61af3f 100644
--- a/modules/im/wechat.py
+++ b/modules/im/wechat.py
@@ -398,6 +398,7 @@ class WeChatBot(BaseIMClient):
self._sync_buf: str = ""
self._poll_timeout_ms: int = _POLL_TIMEOUT_MS
self._session_expired_logged: bool = False
+ self._connection_notified: bool = False
# Auth manager
self._auth_manager = WeChatAuthManager()
@@ -983,6 +984,26 @@ class WeChatBot(BaseIMClient):
# Run / shutdown
# ------------------------------------------------------------------
+ async def _notify_connection_state(self, action: str) -> None:
+ """Best-effort online-state notification for the iLink gateway."""
+ if not self.config.bot_token:
+ return
+ try:
+ if action == "start":
+ if self._connection_notified:
+ return
+ resp = await _wechat_api_mod.notify_start(self.config.base_url, self.config.bot_token)
+ elif action == "stop":
+ if not self._connection_notified:
+ return
+ resp = await _wechat_api_mod.notify_stop(self.config.base_url, self.config.bot_token)
+ else:
+ raise ValueError(f"unknown WeChat notify action: {action}")
+ _raise_if_wechat_api_error(resp, f"notify_{action}")
+ self._connection_notified = action == "start"
+ except Exception as exc:
+ logger.warning("WeChat notify_%s failed: %s", action, exc)
+
def run(self) -> None:
"""Start the WeChat bot: validate config, run the async poll loop."""
if not self.config.bot_token:
@@ -1026,6 +1047,8 @@ class WeChatBot(BaseIMClient):
"WeChat bot session is not active; messages may fail until the session is re-authenticated",
)
+ await self._notify_connection_state("start")
+
# Start poll loop as a background task
self._poll_task = asyncio.create_task(self._poll_loop())
@@ -1042,6 +1065,8 @@ class WeChatBot(BaseIMClient):
except asyncio.CancelledError:
pass
+ await self._notify_connection_state("stop")
+
logger.info("WeChat bot stopped")
try:
@@ -1062,6 +1087,7 @@ class WeChatBot(BaseIMClient):
"""Best-effort async shutdown for platform resources."""
if self._stop_event is not None:
self._stop_event.set()
+ await self._notify_connection_state("stop")
# Persist sync buffer so we don't re-process old messages on restart
self._save_sync_buf()
diff --git a/modules/im/wechat_api.py b/modules/im/wechat_api.py
index a4247da57..3b183b564 100644
--- a/modules/im/wechat_api.py
+++ b/modules/im/wechat_api.py
@@ -2,7 +2,7 @@
Handles all HTTP communication with the WeChat iLink bot backend.
All messaging endpoints are POST to ``{base_url}/ilink/bot/{endpoint}``;
-auth/QR endpoints are GET.
+auth/QR status endpoints are GET; QR issuance is POST.
Ported from the TypeScript reference implementation.
"""
@@ -10,6 +10,7 @@ Ported from the TypeScript reference implementation.
import asyncio
import base64
import logging
+import re
import struct
import uuid
from typing import Any, Dict, List, Optional
@@ -56,9 +57,14 @@ DEFAULT_LONG_POLL_TIMEOUT_MS = 35_000
DEFAULT_LONG_POLL_TIMEOUT_GRACE_MS = 5_000
DEFAULT_API_TIMEOUT_MS = 15_000
DEFAULT_CONFIG_TIMEOUT_MS = 10_000
+DEFAULT_QR_FETCH_TIMEOUT_MS = 30_000
-# Channel version reported in base_info
-CHANNEL_VERSION = "vibe-remote"
+# WeChat's iLink gateway validates the client metadata against the OpenClaw
+# Weixin channel build. Keep this aligned with Tencent/openclaw-weixin.
+CHANNEL_VERSION = "2.4.3"
+ILINK_APP_ID = "bot"
+ILINK_APP_CLIENT_VERSION = (2 << 16) | (4 << 8) | 3
+BOT_AGENT_FALLBACK_VERSION = "unknown"
# ---------------------------------------------------------------------------
@@ -79,9 +85,36 @@ def _ensure_trailing_slash(url: str) -> str:
return url if url.endswith("/") else f"{url}/"
+def _safe_product_version(raw: Any) -> str:
+ if not isinstance(raw, str) or not raw.strip():
+ return BOT_AGENT_FALLBACK_VERSION
+ return re.sub(r"[^A-Za-z0-9_.+\-]", "_", raw.strip())[:32] or BOT_AGENT_FALLBACK_VERSION
+
+
+def _build_bot_agent() -> str:
+ try:
+ from vibe import __version__
+ except Exception:
+ version = BOT_AGENT_FALLBACK_VERSION
+ else:
+ version = _safe_product_version(__version__)
+ return f"Avibe/{version} OpenClaw/2.4.3"
+
+
def _build_base_info() -> Dict[str, str]:
"""Build the ``base_info`` payload included in every API request."""
- return {"channel_version": CHANNEL_VERSION}
+ return {
+ "channel_version": CHANNEL_VERSION,
+ "bot_agent": _build_bot_agent(),
+ }
+
+
+def _build_common_headers() -> Dict[str, str]:
+ """Build iLink metadata headers shared by GET and POST requests."""
+ return {
+ "iLink-App-Id": ILINK_APP_ID,
+ "iLink-App-ClientVersion": str(ILINK_APP_CLIENT_VERSION),
+ }
def _build_headers(token: Optional[str] = None, body_bytes: Optional[bytes] = None) -> Dict[str, str]:
@@ -90,9 +123,8 @@ def _build_headers(token: Optional[str] = None, body_bytes: Optional[bytes] = No
"Content-Type": "application/json",
"AuthorizationType": "ilink_bot_token",
"X-WECHAT-UIN": _random_wechat_uin(),
+ **_build_common_headers(),
}
- if body_bytes is not None:
- headers["Content-Length"] = str(len(body_bytes))
if token and token.strip():
headers["Authorization"] = f"Bearer {token.strip()}"
return headers
@@ -331,6 +363,34 @@ async def send_typing(
)
+async def notify_start(
+ base_url: str,
+ token: str,
+) -> dict:
+ """Notify the iLink server that this WeChat client is starting."""
+ return await _api_fetch(
+ base_url,
+ "ilink/bot/msg/notifystart",
+ {},
+ token=token,
+ timeout_ms=DEFAULT_CONFIG_TIMEOUT_MS,
+ )
+
+
+async def notify_stop(
+ base_url: str,
+ token: str,
+) -> dict:
+ """Notify the iLink server that this WeChat client is stopping."""
+ return await _api_fetch(
+ base_url,
+ "ilink/bot/msg/notifystop",
+ {},
+ token=token,
+ timeout_ms=DEFAULT_CONFIG_TIMEOUT_MS,
+ )
+
+
# ---------------------------------------------------------------------------
# Auth / QR code endpoints (GET requests, no token)
# ---------------------------------------------------------------------------
@@ -339,23 +399,28 @@ async def send_typing(
async def get_bot_qrcode(
base_url: str,
bot_type: str = "3",
+ local_token_list: Optional[List[str]] = None,
+ timeout_ms: int = DEFAULT_QR_FETCH_TIMEOUT_MS,
) -> dict:
"""Fetch a new QR code for bot login.
- GET ``ilink/bot/get_bot_qrcode?bot_type={bot_type}``
+ POST ``ilink/bot/get_bot_qrcode?bot_type={bot_type}``
Returns:
Dict with ``qrcode`` (string token) and ``qrcode_img_content`` (URL/data).
"""
+ import json
+
url = urljoin(
_ensure_trailing_slash(base_url),
- f"ilink/bot/get_bot_qrcode?bot_type={quote(bot_type)}",
+ f"ilink/bot/get_bot_qrcode?bot_type={quote(bot_type, safe='')}",
)
logger.info("Fetching QR code from: %s", url)
- timeout = aiohttp.ClientTimeout(total=DEFAULT_API_TIMEOUT_MS / 1000.0)
+ body = json.dumps({"local_token_list": local_token_list or []}).encode("utf-8")
+ timeout = aiohttp.ClientTimeout(total=timeout_ms / 1000.0)
async with aiohttp.ClientSession(timeout=timeout) as session:
- async with session.get(url) as resp:
+ async with session.post(url, data=body, headers=_build_headers(body_bytes=body)) as resp:
if not resp.ok:
body = await resp.text()
logger.error(
@@ -372,11 +437,12 @@ async def get_bot_qrcode(
async def get_qrcode_status(
base_url: str,
qrcode: str,
+ verify_code: Optional[str] = None,
+ timeout_ms: int = DEFAULT_LONG_POLL_TIMEOUT_MS,
) -> dict:
"""Long-poll QR code scan status.
GET ``ilink/bot/get_qrcode_status?qrcode={qrcode}``
- Includes ``iLink-App-ClientVersion: 1`` header.
On client-side timeout (35 s), returns ``{"status": "wait"}``.
@@ -388,11 +454,13 @@ async def get_qrcode_status(
url = urljoin(
_ensure_trailing_slash(base_url),
- f"ilink/bot/get_qrcode_status?qrcode={quote(qrcode)}",
+ f"ilink/bot/get_qrcode_status?qrcode={quote(qrcode, safe='')}",
)
- headers = {"iLink-App-ClientVersion": "1"}
+ if verify_code:
+ url += f"&verify_code={quote(verify_code, safe='')}"
+ headers = _build_common_headers()
- timeout = aiohttp.ClientTimeout(total=DEFAULT_LONG_POLL_TIMEOUT_MS / 1000.0)
+ timeout = aiohttp.ClientTimeout(total=timeout_ms / 1000.0)
logger.debug("Long-poll QR status from: %s", url)
try:
@@ -410,6 +478,6 @@ async def get_qrcode_status(
except (aiohttp.ServerTimeoutError, TimeoutError):
logger.debug(
"pollQRStatus: client-side timeout after %dms, returning wait",
- DEFAULT_LONG_POLL_TIMEOUT_MS,
+ timeout_ms,
)
return {"status": "wait"}
diff --git a/modules/im/wechat_auth.py b/modules/im/wechat_auth.py
index 0ad06cdd5..157511546 100644
--- a/modules/im/wechat_auth.py
+++ b/modules/im/wechat_auth.py
@@ -13,8 +13,9 @@ import time
import uuid
from dataclasses import dataclass, field
from typing import Dict, Optional
+from urllib.parse import urlparse
-import aiohttp
+from modules.im import wechat_api
logger = logging.getLogger(__name__)
@@ -38,11 +39,14 @@ class WeChatLoginSession:
qrcode_url: str = "" # URL to render as QR image
started_at: float = field(default_factory=time.time)
status: str = "wait" # "wait" | "scaned" | "confirmed" | "expired"
+ pending_verify_code: Optional[str] = None
bot_token: Optional[str] = None
bot_id: Optional[str] = None
base_url: Optional[str] = None
user_id: Optional[str] = None
qr_refresh_count: int = 1 # tracks how many QR codes have been issued
+ current_base_url: Optional[str] = None
+ local_token_list: list[str] = field(default_factory=list)
# ---------------------------------------------------------------------------
@@ -53,32 +57,21 @@ async def get_bot_qrcode(
bot_type: str,
*,
timeout: float = 30,
+ local_token_list: Optional[list[str]] = None,
) -> dict:
"""Fetch a new QR code from the iLink server.
- GET {base_url}/ilink/bot/get_bot_qrcode?bot_type={bot_type}
+ POST {base_url}/ilink/bot/get_bot_qrcode?bot_type={bot_type}
Returns:
dict with keys ``qrcode`` and ``qrcode_img_content``.
"""
- base = base_url.rstrip("/")
- url = f"{base}/ilink/bot/get_bot_qrcode?bot_type={bot_type}"
- logger.info("Fetching QR code from: %s", url)
-
- client_timeout = aiohttp.ClientTimeout(total=timeout)
- async with aiohttp.ClientSession(timeout=client_timeout) as session:
- async with session.get(url) as resp:
- if resp.status != 200:
- body = await resp.text()
- logger.error(
- "QR code fetch failed: %s %s body=%s",
- resp.status,
- resp.reason,
- body[:500],
- )
- raise RuntimeError(f"Failed to fetch QR code: {resp.status} {resp.reason}")
- # iLink API returns application/octet-stream, not application/json
- return await resp.json(content_type=None)
+ return await wechat_api.get_bot_qrcode(
+ base_url,
+ bot_type,
+ local_token_list=local_token_list,
+ timeout_ms=int(timeout * 1000),
+ )
async def get_qrcode_status(
@@ -86,6 +79,7 @@ async def get_qrcode_status(
qrcode: str,
*,
timeout: float = QR_POLL_TIMEOUT_S,
+ verify_code: Optional[str] = None,
) -> dict:
"""Long-poll the QR code scan status.
@@ -96,29 +90,13 @@ async def get_qrcode_status(
On ``confirmed``, also includes ``bot_token``, ``ilink_bot_id``,
``baseurl``, and ``ilink_user_id``.
"""
- base = base_url.rstrip("/")
- url = f"{base}/ilink/bot/get_qrcode_status?qrcode={qrcode}"
- logger.debug("Long-poll QR status from: %s", url)
-
- headers = {"iLink-App-ClientVersion": "1"}
- client_timeout = aiohttp.ClientTimeout(total=timeout + 5)
-
try:
- async with aiohttp.ClientSession(timeout=client_timeout) as session:
- async with session.get(url, headers=headers) as resp:
- raw = await resp.text()
- logger.debug("get_qrcode_status: HTTP %s body=%s", resp.status, raw[:200])
- if resp.status != 200:
- logger.error(
- "QR status poll failed: %s %s body=%s",
- resp.status,
- resp.reason,
- raw[:500],
- )
- raise RuntimeError(f"Failed to poll QR status: {resp.status} {resp.reason}")
- import json
-
- return json.loads(raw)
+ return await wechat_api.get_qrcode_status(
+ base_url,
+ qrcode,
+ verify_code=verify_code,
+ timeout_ms=int(timeout * 1000),
+ )
except asyncio.TimeoutError:
logger.debug(
"get_qrcode_status: client-side timeout after %ss, returning wait",
@@ -158,12 +136,48 @@ class WeChatAuthManager:
self.cleanup_expired()
return self._sessions.get(session_key)
+ def _refresh_base_url(self, session: WeChatLoginSession, redirect_host: str) -> Optional[str]:
+ host = redirect_host.strip()
+ if not host:
+ return None
+ parsed = urlparse(host if "://" in host else f"https://{host}")
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
+ logger.warning("Ignoring invalid WeChat QR redirect host: %s", redirect_host)
+ return None
+ refreshed = f"{parsed.scheme}://{parsed.netloc}"
+ session.current_base_url = refreshed
+ return refreshed
+
+ async def _refresh_qr_session(self, session: WeChatLoginSession) -> dict:
+ qr_response = await get_bot_qrcode(
+ session.base_url or self.DEFAULT_BASE_URL,
+ self.BOT_TYPE,
+ local_token_list=session.local_token_list,
+ )
+ session.qrcode = qr_response.get("qrcode", "")
+ session.qrcode_url = qr_response.get("qrcode_img_content", "")
+ session.started_at = time.time()
+ session.status = "wait"
+ session.current_base_url = session.base_url
+ session.pending_verify_code = None
+ logger.info("New QR code obtained for session=%s", session.session_key)
+ return {
+ "status": "refreshed",
+ "qrcode_url": session.qrcode_url,
+ "message": (
+ f"QR code expired, refreshed "
+ f"({session.qr_refresh_count}/{self.MAX_QR_REFRESH}). "
+ f"Please scan again."
+ ),
+ }
+
# -- public API -------------------------------------------------------
async def start_login(
self,
session_key: Optional[str] = None,
base_url: Optional[str] = None,
+ local_token_list: Optional[list[str]] = None,
) -> dict:
"""Start a new QR code login.
@@ -175,10 +189,14 @@ class WeChatAuthManager:
base_url = base_url or self.DEFAULT_BASE_URL
self.cleanup_expired()
+ normalized_local_tokens = [
+ token.strip() for token in (local_token_list or []) if isinstance(token, str) and token.strip()
+ ]
# Reuse an existing fresh session if available
existing = self._sessions.get(session_key)
if existing and self._is_session_fresh(existing) and existing.qrcode_url:
+ existing.local_token_list = normalized_local_tokens
return {
"session_key": session_key,
"qrcode_url": existing.qrcode_url,
@@ -195,7 +213,7 @@ class WeChatAuthManager:
try:
logger.info("Starting WeChat login with bot_type=%s", self.BOT_TYPE)
- qr_response = await get_bot_qrcode(base_url, self.BOT_TYPE)
+ qr_response = await get_bot_qrcode(base_url, self.BOT_TYPE, local_token_list=normalized_local_tokens)
qrcode = qr_response.get("qrcode", "")
qrcode_url = qr_response.get("qrcode_img_content", "")
@@ -213,6 +231,8 @@ class WeChatAuthManager:
started_at=time.time(),
status="wait",
base_url=base_url,
+ current_base_url=base_url,
+ local_token_list=normalized_local_tokens,
)
self._sessions[session_key] = session
@@ -230,7 +250,7 @@ class WeChatAuthManager:
"error": f"Failed to start login: {exc}",
}
- async def poll_status(self, session_key: str) -> dict:
+ async def poll_status(self, session_key: str, verify_code: Optional[str] = None) -> dict:
"""Poll login status for a single cycle.
Returns:
@@ -251,10 +271,17 @@ class WeChatAuthManager:
"message": "QR code has expired. Please start a new login.",
}
- base_url = session.base_url or self.DEFAULT_BASE_URL
+ base_url = session.current_base_url or session.base_url or self.DEFAULT_BASE_URL
+
+ if verify_code is not None:
+ session.pending_verify_code = verify_code.strip() or None
try:
- status_resp = await get_qrcode_status(base_url, session.qrcode)
+ status_resp = await get_qrcode_status(
+ base_url,
+ session.qrcode,
+ verify_code=session.pending_verify_code,
+ )
except Exception as exc:
# Don't delete session on transient errors (timeouts, network blips).
# The UI will retry on the next poll cycle.
@@ -278,8 +305,52 @@ class WeChatAuthManager:
return {"status": "wait", "message": "Waiting for QR code scan..."}
if status == "scaned":
+ session.pending_verify_code = None
return {"status": "scaned", "message": "QR code scanned. Please confirm in WeChat."}
+ if status == "scaned_but_redirect":
+ redirect_host = status_resp.get("redirect_host", "")
+ refreshed_base_url = self._refresh_base_url(session, redirect_host)
+ return {
+ "status": "scaned",
+ "message": "QR code scanned. Please confirm in WeChat.",
+ **({"base_url": refreshed_base_url} if refreshed_base_url else {}),
+ }
+
+ if status == "binded_redirect":
+ resp_base_url = session.current_base_url or session.base_url or self.DEFAULT_BASE_URL
+ del self._sessions[session_key]
+ return {
+ "status": "already_connected",
+ "message": "This WeChat bot is already connected. Existing credentials remain valid.",
+ "base_url": resp_base_url,
+ }
+
+ if status == "need_verifycode":
+ return {
+ "status": "need_verifycode",
+ "message": "Enter the verification code shown in WeChat to continue.",
+ }
+
+ if status == "verify_code_blocked":
+ session.pending_verify_code = None
+ session.qr_refresh_count += 1
+ if session.qr_refresh_count > self.MAX_QR_REFRESH:
+ del self._sessions[session_key]
+ return {
+ "status": "expired",
+ "message": "WeChat verification failed too many times. Please restart the login flow.",
+ }
+ try:
+ return await self._refresh_qr_session(session)
+ except Exception as exc:
+ logger.error("Failed to refresh QR code after blocked verification: %s", exc)
+ del self._sessions[session_key]
+ return {
+ "status": "error",
+ "message": f"Failed to refresh QR code: {exc}",
+ }
+
if status == "expired":
session.qr_refresh_count += 1
if session.qr_refresh_count > self.MAX_QR_REFRESH:
@@ -301,21 +372,7 @@ class WeChatAuthManager:
session_key,
)
try:
- qr_response = await get_bot_qrcode(base_url, self.BOT_TYPE)
- session.qrcode = qr_response.get("qrcode", "")
- session.qrcode_url = qr_response.get("qrcode_img_content", "")
- session.started_at = time.time()
- session.status = "wait"
- logger.info("New QR code obtained for session=%s", session_key)
- return {
- "status": "refreshed",
- "qrcode_url": session.qrcode_url,
- "message": (
- f"QR code expired, refreshed "
- f"({session.qr_refresh_count}/{self.MAX_QR_REFRESH}). "
- f"Please scan again."
- ),
- }
+ return await self._refresh_qr_session(session)
except Exception as exc:
logger.error("Failed to refresh QR code: %s", exc)
del self._sessions[session_key]
@@ -335,7 +392,8 @@ class WeChatAuthManager:
}
bot_token = status_resp.get("bot_token")
- resp_base_url = status_resp.get("baseurl")
+ session.pending_verify_code = None
+ resp_base_url = status_resp.get("baseurl") or session.current_base_url or session.base_url
user_id = status_resp.get("ilink_user_id")
# Store on session before removing
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index ca0ba597b..4d770ccde 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -614,7 +614,7 @@ def test_wechat_qr_poll_marks_bind_hint_and_schedules_managed_restart(monkeypatc
from vibe import runtime
class _Auth:
- async def poll_status(self, session_key):
+ async def poll_status(self, session_key, verify_code=None):
assert session_key == "qr-session"
return {
"status": "confirmed",
@@ -625,9 +625,11 @@ def test_wechat_qr_poll_marks_bind_hint_and_schedules_managed_restart(monkeypatc
bound_users = []
restart_calls = []
+ persisted = []
runtime.ensure_config()
monkeypatch.setattr(ui_server, "_get_wechat_auth", lambda: _Auth())
+ monkeypatch.setattr(ui_server, "_persist_wechat_qr_credentials", lambda result: persisted.append(result.copy()))
monkeypatch.setattr(
ui_server,
"_schedule_wechat_qr_login_restart",
@@ -648,10 +650,207 @@ def test_wechat_qr_poll_marks_bind_hint_and_schedules_managed_restart(monkeypatc
assert response.status_code == 200
assert response.get_json()["status"] == "confirmed"
+ assert persisted == [
+ {
+ "status": "confirmed",
+ "bot_token": "wechat-token",
+ "base_url": "https://wechat.example.com",
+ "user_id": "wx-user",
+ }
+ ]
assert bound_users == ["wx-user"]
assert restart_calls == [True]
+def test_wechat_qr_poll_passes_verify_code(monkeypatch):
+ class _Auth:
+ async def poll_status(self, session_key, verify_code=None):
+ assert session_key == "qr-session"
+ return {"status": "need_verifycode", "verify_code": verify_code}
+
+ monkeypatch.setattr(ui_server, "_get_wechat_auth", lambda: _Auth())
+
+ client = app.test_client()
+ response = client.post(
+ "/api/wechat/qr_login/poll",
+ json={"session_key": "qr-session", "verify_code": "1234"},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ assert response.get_json() == {"status": "need_verifycode", "verify_code": "1234"}
+
+
+def test_persist_wechat_qr_credentials_saves_before_restart(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ from vibe import api
+
+ payload = _full_config_payload()
+ payload["platforms"] = {"enabled": [], "primary": "avibe"}
+ payload["wechat"] = {
+ "bot_token": "",
+ "base_url": "https://old-wechat.example.com",
+ "cdn_base_url": "https://cdn.example.com/c2c",
+ "proxy_url": "socks5://127.0.0.1:1080",
+ }
+ api.save_config(payload)
+
+ ui_server._persist_wechat_qr_credentials(
+ {
+ "status": "confirmed",
+ "bot_token": "new-token",
+ "base_url": "https://new-wechat.example.com",
+ "user_id": "wx-user",
+ }
+ )
+
+ updated = api.load_config()
+ assert updated.wechat is not None
+ assert updated.wechat.bot_token == "new-token"
+ assert updated.wechat.base_url == "https://new-wechat.example.com"
+ assert updated.wechat.cdn_base_url == "https://cdn.example.com/c2c"
+ assert updated.wechat.proxy_url == "socks5://127.0.0.1:1080"
+ assert updated.platforms.enabled == ["wechat"]
+ assert updated.platforms.primary == "wechat"
+
+
+def test_persist_wechat_qr_credentials_seeds_fresh_config(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ from config import paths
+ from vibe import api
+
+ assert not paths.get_config_path().exists()
+
+ ui_server._persist_wechat_qr_credentials(
+ {
+ "status": "confirmed",
+ "bot_token": "new-token",
+ "base_url": "https://new-wechat.example.com",
+ "user_id": "wx-user",
+ }
+ )
+
+ updated = api.load_config()
+ assert updated.wechat is not None
+ assert updated.wechat.bot_token == "new-token"
+ assert updated.wechat.base_url == "https://new-wechat.example.com"
+ assert updated.platforms.enabled == ["wechat"]
+ assert updated.platforms.primary == "wechat"
+
+
+def test_wechat_qr_start_sends_saved_token_list_to_fixed_qr_host(monkeypatch):
+ class _Auth:
+ async def start_login(self, base_url=None, local_token_list=None):
+ return {
+ "session_key": "qr-session",
+ "qrcode_url": "https://wechat.example.com/qr",
+ "base_url": base_url,
+ "local_token_list": local_token_list,
+ }
+
+ monkeypatch.setattr(ui_server, "_get_wechat_auth", lambda: _Auth())
+ monkeypatch.setattr(ui_server, "_load_wechat_local_tokens", lambda: ["saved-token"])
+
+ client = app.test_client()
+ response = client.post(
+ "/api/wechat/qr_login/start",
+ json={"base_url": "https://wechat.example.com"},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ payload = response.get_json()
+ assert payload["base_url"] == "https://ilinkai.weixin.qq.com"
+ assert payload["local_token_list"] == ["saved-token"]
+
+
+def test_wechat_qr_poll_does_not_autobind_without_user_id(monkeypatch):
+ from vibe import runtime
+
+ class _Auth:
+ async def poll_status(self, session_key, verify_code=None):
+ assert session_key == "qr-session"
+ return {
+ "status": "confirmed",
+ "bot_token": "wechat-token",
+ "base_url": "https://wechat.example.com",
+ }
+
+ bound_users = []
+ restart_calls = []
+ persisted = []
+
+ runtime.ensure_config()
+ monkeypatch.setattr(ui_server, "_get_wechat_auth", lambda: _Auth())
+ monkeypatch.setattr(ui_server, "_persist_wechat_qr_credentials", lambda result: persisted.append(result.copy()))
+ monkeypatch.setattr(
+ ui_server,
+ "_schedule_wechat_qr_login_restart",
+ lambda: restart_calls.append(True) or {"job_id": "restart-1"},
+ )
+ monkeypatch.setattr(
+ "vibe.api.auto_bind_wechat_user",
+ lambda user_id: bound_users.append(user_id)
+ or {"ok": True, "already_bound": False, "is_admin": True, "pending_bind_menu_hint": True},
+ )
+
+ client = app.test_client()
+ response = client.post(
+ "/api/wechat/qr_login/poll",
+ json={"session_key": "qr-session"},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ assert response.get_json()["status"] == "confirmed"
+ assert persisted == []
+ assert bound_users == []
+ assert restart_calls == []
+
+
+def test_wechat_qr_poll_blocks_restart_when_credential_persist_fails(monkeypatch):
+ from vibe import runtime
+
+ class _Auth:
+ async def poll_status(self, session_key, verify_code=None):
+ assert session_key == "qr-session"
+ return {
+ "status": "confirmed",
+ "bot_token": "wechat-token",
+ "base_url": "https://wechat.example.com",
+ "user_id": "wx-user",
+ }
+
+ restart_calls = []
+ bound_users = []
+
+ runtime.ensure_config()
+ monkeypatch.setattr(ui_server, "_get_wechat_auth", lambda: _Auth())
+ monkeypatch.setattr(
+ ui_server,
+ "_persist_wechat_qr_credentials",
+ lambda result: (_ for _ in ()).throw(RuntimeError("disk full")),
+ )
+ monkeypatch.setattr(
+ ui_server,
+ "_schedule_wechat_qr_login_restart",
+ lambda: restart_calls.append(True) or {"job_id": "restart-1"},
+ )
+ monkeypatch.setattr("vibe.api.auto_bind_wechat_user", lambda user_id: bound_users.append(user_id))
+
+ client = app.test_client()
+ response = client.post(
+ "/api/wechat/qr_login/poll",
+ json={"session_key": "qr-session"},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 500
+ assert response.get_json()["error"] == "failed_to_persist_wechat_credentials"
+ assert restart_calls == []
+ assert bound_users == []
+
+
def test_web_push_subscription_routes_roundtrip(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
ensure_sqlite_state()
diff --git a/tests/test_wechat_auth.py b/tests/test_wechat_auth.py
index b6e8bdd87..9cc8477f1 100644
--- a/tests/test_wechat_auth.py
+++ b/tests/test_wechat_auth.py
@@ -18,11 +18,15 @@ class WeChatAuthManagerTests(unittest.IsolatedAsyncioTestCase):
"modules.im.wechat_auth.get_bot_qrcode",
new=AsyncMock(return_value={"qrcode": "qr-token", "qrcode_img_content": "https://example.com/qr.png"}),
):
- result = await manager.start_login(base_url="https://wechat.example.com")
+ result = await manager.start_login(
+ base_url="https://wechat.example.com",
+ local_token_list=[" saved-token ", "", "second-token"],
+ )
session = manager.get_session(result["session_key"])
self.assertIsNotNone(session)
self.assertEqual(session.base_url, "https://wechat.example.com")
+ self.assertEqual(session.local_token_list, ["saved-token", "second-token"])
async def test_poll_status_returns_expired_when_session_missing(self):
manager = WeChatAuthManager()
@@ -53,6 +57,197 @@ class WeChatAuthManagerTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(result["status"], "expired")
self.assertIn("start a new login", result["message"].lower())
+ async def test_poll_status_follows_scan_redirect_and_preserves_session(self):
+ manager = WeChatAuthManager()
+
+ with patch(
+ "modules.im.wechat_auth.get_bot_qrcode",
+ new=AsyncMock(return_value={"qrcode": "qr-token", "qrcode_img_content": "https://example.com/qr.png"}),
+ ):
+ started = await manager.start_login(session_key="qr-session", base_url="https://ilinkai.weixin.qq.com")
+
+ with patch(
+ "modules.im.wechat_auth.get_qrcode_status",
+ new=AsyncMock(return_value={"status": "scaned_but_redirect", "redirect_host": "redirect.weixin.qq.com"}),
+ ) as poll:
+ result = await manager.poll_status(started["session_key"])
+
+ self.assertEqual(result["status"], "scaned")
+ self.assertEqual(result["base_url"], "https://redirect.weixin.qq.com")
+ session = manager.get_session("qr-session")
+ self.assertIsNotNone(session)
+ self.assertEqual(session.base_url, "https://ilinkai.weixin.qq.com")
+ self.assertEqual(session.current_base_url, "https://redirect.weixin.qq.com")
+ poll.assert_awaited_once_with("https://ilinkai.weixin.qq.com", "qr-token", verify_code=None)
+
+ with patch(
+ "modules.im.wechat_auth.get_qrcode_status",
+ new=AsyncMock(
+ return_value={
+ "status": "confirmed",
+ "bot_token": "token-1",
+ "ilink_bot_id": "bot-1",
+ "ilink_user_id": "wx-user",
+ }
+ ),
+ ) as redirected_poll:
+ confirmed = await manager.poll_status("qr-session")
+
+ self.assertEqual(confirmed["status"], "confirmed")
+ self.assertEqual(confirmed["base_url"], "https://redirect.weixin.qq.com")
+ redirected_poll.assert_awaited_once_with("https://redirect.weixin.qq.com", "qr-token", verify_code=None)
+
+ async def test_poll_status_returns_already_connected_for_binded_redirect(self):
+ manager = WeChatAuthManager()
+
+ with patch(
+ "modules.im.wechat_auth.get_bot_qrcode",
+ new=AsyncMock(return_value={"qrcode": "qr-token", "qrcode_img_content": "https://example.com/qr.png"}),
+ ):
+ started = await manager.start_login(session_key="qr-session", base_url="https://ilinkai.weixin.qq.com")
+
+ with patch(
+ "modules.im.wechat_auth.get_qrcode_status",
+ new=AsyncMock(return_value={"status": "binded_redirect"}),
+ ):
+ result = await manager.poll_status(started["session_key"])
+
+ self.assertEqual(result["status"], "already_connected")
+ self.assertEqual(result["base_url"], "https://ilinkai.weixin.qq.com")
+ self.assertIn("already connected", result["message"].lower())
+ self.assertIsNone(manager.get_session("qr-session"))
+
+ def test_wechat_config_handles_already_connected_status(self):
+ source = Path("ui/src/components/steps/WeChatConfig.tsx").read_text(encoding="utf-8")
+
+ self.assertIn("status === 'already_connected'", source)
+ self.assertIn("setLoginState('connected')", source)
+ self.assertIn("preserveExistingConnectionFields(result)", source)
+ self.assertIn("base_url: baseUrl || data.wechat?.base_url || ''", source)
+ self.assertIn("result.status === 'refreshed'", source)
+ self.assertIn("setQrCodeUrl(result.qrcode_url || '')", source)
+
+ async def test_poll_status_refresh_preserves_local_token_list(self):
+ manager = WeChatAuthManager()
+ qr_fetch = AsyncMock(
+ side_effect=[
+ {"qrcode": "qr-token-1", "qrcode_img_content": "https://example.com/qr-1.png"},
+ {"qrcode": "qr-token-2", "qrcode_img_content": "https://example.com/qr-2.png"},
+ ]
+ )
+
+ with patch("modules.im.wechat_auth.get_bot_qrcode", new=qr_fetch):
+ started = await manager.start_login(
+ session_key="qr-session",
+ base_url="https://ilinkai.weixin.qq.com",
+ local_token_list=["saved-token"],
+ )
+
+ with patch(
+ "modules.im.wechat_auth.get_qrcode_status",
+ new=AsyncMock(return_value={"status": "expired"}),
+ ):
+ refreshed = await manager.poll_status(started["session_key"])
+
+ self.assertEqual(refreshed["status"], "refreshed")
+ self.assertEqual(refreshed["qrcode_url"], "https://example.com/qr-2.png")
+ self.assertEqual(qr_fetch.await_count, 2)
+ self.assertEqual(qr_fetch.await_args_list[0].kwargs["local_token_list"], ["saved-token"])
+ self.assertEqual(qr_fetch.await_args_list[1].kwargs["local_token_list"], ["saved-token"])
+ session = manager.get_session("qr-session")
+ self.assertIsNotNone(session)
+ self.assertEqual(session.qrcode, "qr-token-2")
+
+ async def test_poll_status_refresh_uses_login_host_after_status_redirect(self):
+ manager = WeChatAuthManager()
+ qr_fetch = AsyncMock(
+ side_effect=[
+ {"qrcode": "qr-token-1", "qrcode_img_content": "https://example.com/qr-1.png"},
+ {"qrcode": "qr-token-2", "qrcode_img_content": "https://example.com/qr-2.png"},
+ ]
+ )
+
+ with patch("modules.im.wechat_auth.get_bot_qrcode", new=qr_fetch):
+ started = await manager.start_login(
+ session_key="qr-session",
+ base_url="https://ilinkai.weixin.qq.com",
+ local_token_list=["saved-token"],
+ )
+ with patch(
+ "modules.im.wechat_auth.get_qrcode_status",
+ new=AsyncMock(return_value={"status": "scaned_but_redirect", "redirect_host": "redirect.weixin.qq.com"}),
+ ):
+ await manager.poll_status(started["session_key"])
+
+ with patch(
+ "modules.im.wechat_auth.get_qrcode_status",
+ new=AsyncMock(return_value={"status": "expired"}),
+ ):
+ refreshed = await manager.poll_status(started["session_key"])
+
+ self.assertEqual(refreshed["status"], "refreshed")
+ self.assertEqual(qr_fetch.await_args_list[1].args[0], "https://ilinkai.weixin.qq.com")
+ session = manager.get_session("qr-session")
+ self.assertIsNotNone(session)
+ self.assertEqual(session.current_base_url, "https://ilinkai.weixin.qq.com")
+
+ async def test_poll_status_refreshes_after_blocked_verify_code(self):
+ manager = WeChatAuthManager()
+ qr_fetch = AsyncMock(
+ side_effect=[
+ {"qrcode": "qr-token-1", "qrcode_img_content": "https://example.com/qr-1.png"},
+ {"qrcode": "qr-token-2", "qrcode_img_content": "https://example.com/qr-2.png"},
+ ]
+ )
+
+ with patch("modules.im.wechat_auth.get_bot_qrcode", new=qr_fetch):
+ started = await manager.start_login(session_key="qr-session", base_url="https://ilinkai.weixin.qq.com")
+ with patch(
+ "modules.im.wechat_auth.get_qrcode_status",
+ new=AsyncMock(return_value={"status": "verify_code_blocked"}),
+ ):
+ refreshed = await manager.poll_status(started["session_key"], verify_code="bad-code")
+
+ self.assertEqual(refreshed["status"], "refreshed")
+ self.assertEqual(refreshed["qrcode_url"], "https://example.com/qr-2.png")
+ self.assertIsNotNone(manager.get_session("qr-session"))
+
+ async def test_poll_status_submits_verify_code_and_confirms(self):
+ manager = WeChatAuthManager()
+
+ with patch(
+ "modules.im.wechat_auth.get_bot_qrcode",
+ new=AsyncMock(return_value={"qrcode": "qr-token", "qrcode_img_content": "https://example.com/qr.png"}),
+ ):
+ started = await manager.start_login(session_key="qr-session", base_url="https://ilinkai.weixin.qq.com")
+
+ with patch(
+ "modules.im.wechat_auth.get_qrcode_status",
+ new=AsyncMock(return_value={"status": "need_verifycode"}),
+ ) as first_poll:
+ result = await manager.poll_status(started["session_key"])
+
+ self.assertEqual(result["status"], "need_verifycode")
+ first_poll.assert_awaited_once_with("https://ilinkai.weixin.qq.com", "qr-token", verify_code=None)
+
+ with patch(
+ "modules.im.wechat_auth.get_qrcode_status",
+ new=AsyncMock(
+ return_value={
+ "status": "confirmed",
+ "bot_token": "token-1",
+ "ilink_bot_id": "bot-1",
+ "baseurl": "https://wechat.example.com",
+ "ilink_user_id": "wx-user",
+ }
+ ),
+ ) as verify_poll:
+ confirmed = await manager.poll_status("qr-session", verify_code="1234")
+
+ self.assertEqual(confirmed["status"], "confirmed")
+ self.assertEqual(confirmed["bot_token"], "token-1")
+ verify_poll.assert_awaited_once_with("https://ilinkai.weixin.qq.com", "qr-token", verify_code="1234")
+
async def test_auto_bind_wechat_user_marks_one_time_menu_hint_pending(self):
SettingsStore.reset_instance()
diff --git a/tests/test_wechat_bot.py b/tests/test_wechat_bot.py
index b62f1664a..cf6772319 100644
--- a/tests/test_wechat_bot.py
+++ b/tests/test_wechat_bot.py
@@ -56,6 +56,23 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(_get_updates_error_code({"errcode": -14, "errmsg": "session timeout"}), -14)
self.assertIsNone(_get_updates_error_code({"ret": 0}))
+ def test_wechat_api_metadata_matches_current_openclaw_weixin_interface(self):
+ self.assertEqual(wechat_api_module.CHANNEL_VERSION, "2.4.3")
+ self.assertEqual(wechat_api_module.ILINK_APP_ID, "bot")
+ self.assertEqual(wechat_api_module.ILINK_APP_CLIENT_VERSION, 132099)
+ with patch("vibe.__version__", "3.0.3.dev102+g5a817be5f"):
+ self.assertEqual(
+ wechat_api_module._build_base_info(),
+ {"channel_version": "2.4.3", "bot_agent": "Avibe/3.0.3.dev102+g5a817be5f OpenClaw/2.4.3"},
+ )
+ self.assertEqual(
+ wechat_api_module._build_common_headers(),
+ {"iLink-App-Id": "bot", "iLink-App-ClientVersion": "132099"},
+ )
+
+ def test_wechat_api_bot_agent_sanitizes_version(self):
+ self.assertEqual(wechat_api_module._safe_product_version("3.0.3 dev/102"), "3.0.3_dev_102")
+
async def test_wechat_api_get_updates_adds_long_poll_timeout_grace(self):
captured = {}
@@ -84,6 +101,8 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):
def post(self, url, data=None, headers=None):
captured["url"] = url
+ captured["headers"] = headers
+ captured["data"] = data
return _Response()
with patch("modules.im.wechat_api.aiohttp.ClientSession", side_effect=lambda timeout: _Session(timeout)):
@@ -97,6 +116,10 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(result["get_updates_buf"], "buf-2")
self.assertEqual(captured["timeout"], 40.0)
self.assertTrue(captured["url"].endswith("/ilink/bot/getupdates"))
+ self.assertEqual(captured["headers"]["iLink-App-Id"], "bot")
+ self.assertEqual(captured["headers"]["iLink-App-ClientVersion"], "132099")
+ self.assertNotIn("Content-Length", captured["headers"])
+ self.assertEqual(json.loads(captured["data"])["base_info"]["channel_version"], "2.4.3")
async def test_wechat_api_get_updates_poll_logs_are_debug(self):
class _Response:
@@ -192,6 +215,7 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):
return False
def post(self, url, data=None, headers=None):
+ captured["headers"] = headers
return _Response()
with patch("modules.im.wechat_api.aiohttp.ClientSession", side_effect=lambda timeout: _Session(timeout)):
@@ -205,6 +229,139 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(result, {"ret": 0})
self.assertEqual(captured["timeout"], 15.0)
+ self.assertEqual(captured["headers"]["iLink-App-Id"], "bot")
+ self.assertEqual(captured["headers"]["iLink-App-ClientVersion"], "132099")
+
+ async def test_wechat_api_notify_start_uses_current_metadata(self):
+ captured = {}
+
+ 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}'
+
+ class _Session:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb):
+ return False
+
+ def post(self, url, data=None, headers=None):
+ captured["url"] = url
+ captured["data"] = data
+ captured["headers"] = headers
+ return _Response()
+
+ with patch("modules.im.wechat_api.aiohttp.ClientSession", side_effect=lambda timeout: _Session()):
+ result = await wechat_api_module.notify_start("https://wechat.example.com", "token")
+
+ self.assertEqual(result, {"ret": 0})
+ self.assertTrue(captured["url"].endswith("/ilink/bot/msg/notifystart"))
+ self.assertEqual(json.loads(captured["data"])["base_info"]["channel_version"], "2.4.3")
+ self.assertEqual(captured["headers"]["iLink-App-Id"], "bot")
+ self.assertEqual(captured["headers"]["iLink-App-ClientVersion"], "132099")
+
+ async def test_wechat_api_qr_fetch_posts_current_interface_metadata(self):
+ captured = {}
+
+ class _Response:
+ ok = True
+ status = 200
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb):
+ return False
+
+ async def json(self, content_type=None):
+ captured["content_type"] = content_type
+ return {"qrcode": "qr-token", "qrcode_img_content": "https://wechat.example.com/qr"}
+
+ class _Session:
+ def __init__(self, timeout):
+ captured["timeout_total"] = timeout.total
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb):
+ return False
+
+ def post(self, url, data=None, headers=None):
+ captured["url"] = url
+ captured["data"] = data
+ captured["headers"] = headers
+ return _Response()
+
+ with patch("modules.im.wechat_api.aiohttp.ClientSession", side_effect=lambda timeout: _Session(timeout)):
+ result = await wechat_api_module.get_bot_qrcode(
+ "https://wechat.example.com",
+ "3",
+ local_token_list=["token-1"],
+ )
+
+ self.assertEqual(result["qrcode"], "qr-token")
+ self.assertTrue(captured["url"].endswith("/ilink/bot/get_bot_qrcode?bot_type=3"))
+ self.assertEqual(json.loads(captured["data"]), {"local_token_list": ["token-1"]})
+ self.assertEqual(captured["headers"]["iLink-App-Id"], "bot")
+ self.assertEqual(captured["headers"]["iLink-App-ClientVersion"], "132099")
+ self.assertEqual(captured["content_type"], None)
+ self.assertEqual(captured["timeout_total"], 30.0)
+
+ async def test_wechat_api_qr_status_uses_current_interface_headers_and_timeout(self):
+ captured = {}
+
+ 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 '{"status": "wait"}'
+
+ class _Session:
+ def __init__(self, timeout):
+ captured["timeout"] = timeout.total
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb):
+ return False
+
+ def get(self, url, headers=None):
+ captured["url"] = url
+ captured["headers"] = headers
+ return _Response()
+
+ with patch("modules.im.wechat_api.aiohttp.ClientSession", side_effect=lambda timeout: _Session(timeout)):
+ result = await wechat_api_module.get_qrcode_status(
+ "https://wechat.example.com",
+ "qr token",
+ verify_code="1234",
+ timeout_ms=3000,
+ )
+
+ self.assertEqual(result, {"status": "wait"})
+ self.assertEqual(captured["timeout"], 3.0)
+ self.assertIn("qrcode=qr%20token", captured["url"])
+ self.assertIn("verify_code=1234", captured["url"])
+ self.assertEqual(captured["headers"], {"iLink-App-Id": "bot", "iLink-App-ClientVersion": "132099"})
async def test_get_user_info_uses_short_fixed_display_name(self):
bot = self._make_bot()
@@ -242,6 +399,29 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):
args = mock_typing.await_args.args # type: ignore[union-attr]
self.assertEqual(args[3], "ticket-1")
+ async def test_notify_connection_state_is_best_effort(self):
+ bot = self._make_bot()
+
+ with patch("modules.im.wechat_api.notify_start", new=AsyncMock(return_value={"ret": 0})) as start:
+ await bot._notify_connection_state("start")
+
+ start.assert_awaited_once_with("https://ilinkai.weixin.qq.com", "token")
+
+ with patch("modules.im.wechat_api.notify_stop", new=AsyncMock(side_effect=RuntimeError("offline"))):
+ await bot._notify_connection_state("stop")
+
+ async def test_notify_connection_state_sends_stop_once(self):
+ bot = self._make_bot()
+
+ with patch("modules.im.wechat_api.notify_start", new=AsyncMock(return_value={"ret": 0})):
+ await bot._notify_connection_state("start")
+
+ with patch("modules.im.wechat_api.notify_stop", new=AsyncMock(return_value={"ret": 0})) as stop:
+ await bot._notify_connection_state("stop")
+ await bot._notify_connection_state("stop")
+
+ stop.assert_awaited_once_with("https://ilinkai.weixin.qq.com", "token")
+
async def test_process_inbound_message_dispatches_allowed_message(self):
bot = self._make_bot()
bot.check_authorization = lambda **kwargs: AuthResult(allowed=True, is_dm=True)
diff --git a/ui/src/components/steps/WeChatConfig.tsx b/ui/src/components/steps/WeChatConfig.tsx
index 80315efe8..e845c00df 100644
--- a/ui/src/components/steps/WeChatConfig.tsx
+++ b/ui/src/components/steps/WeChatConfig.tsx
@@ -18,6 +18,7 @@ import { hasUsableSecret, secretInputValue, withSecretDraft } from '../../lib/se
import { EmbeddedConfigShell, EyebrowBadge, WizardCard } from '../visual';
import { ProxyUrlField } from '../shared/ProxyUrlField';
import { Button } from '../ui/button';
+import { Input } from '../ui/input';
interface WeChatConfigProps {
data: Record<string, any>;
@@ -45,12 +46,19 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBack
const [botToken, setBotToken] = useState<string>(secretInputValue(data.wechat, 'bot_token'));
const [baseUrl, setBaseUrl] = useState<string>(data.wechat?.base_url || '');
const [proxyUrl, setProxyUrl] = useState<string>(data.wechat?.proxy_url || '');
+ const [verifyCode, setVerifyCode] = useState('');
+ const [needsVerifyCode, setNeedsVerifyCode] = useState(false);
const [starting, setStarting] = useState(false);
const pollTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const autoStartedRef = useRef(false);
const activeSessionKeyRef = useRef<string | null>(null);
+ const preserveExistingConnectionFields = useCallback((result: Record<string, any> = {}) => {
+ setBotToken(result.bot_token || secretInputValue(data.wechat, 'bot_token'));
+ setBaseUrl(result.base_url || data.wechat?.base_url || '');
+ }, [data.wechat]);
+
const stopPolling = useCallback(() => {
if (pollTimerRef.current) {
clearTimeout(pollTimerRef.current);
@@ -71,6 +79,8 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBack
setQrCodeUrl('');
setBotToken('');
setBaseUrl('');
+ setVerifyCode('');
+ setNeedsVerifyCode(false);
activeSessionKeyRef.current = null;
stopPolling();
@@ -137,9 +147,17 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBack
const status = result.status;
if (status === 'scaned') {
+ setNeedsVerifyCode(false);
+ setVerifyCode('');
setLoginState('confirming');
setMessage(result.message || t('wechatConfig.confirmOnPhone'));
+ } else if (status === 'need_verifycode') {
+ setNeedsVerifyCode(true);
+ setLoginState('confirming');
+ setMessage(result.message || t('wechatConfig.verifyCodePrompt'));
} else if (status === 'confirmed') {
+ setNeedsVerifyCode(false);
+ setVerifyCode('');
setLoginState('connected');
setMessage(result.message || t('wechatConfig.connected'));
setBotToken(result.bot_token || '');
@@ -147,17 +165,30 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBack
activeSessionKeyRef.current = null;
stopPolling();
return;
+ } else if (status === 'already_connected') {
+ setNeedsVerifyCode(false);
+ setVerifyCode('');
+ setLoginState('connected');
+ setMessage(result.message || t('wechatConfig.connected'));
+ preserveExistingConnectionFields(result);
+ activeSessionKeyRef.current = null;
+ stopPolling();
+ return;
} else if (status === 'refreshed') {
+ setNeedsVerifyCode(false);
+ setVerifyCode('');
setLoginState('qr_ready');
setQrCodeUrl(result.qrcode_url || '');
setMessage(result.message || t('wechatConfig.qrExpired'));
} else if (status === 'expired') {
+ setNeedsVerifyCode(false);
setLoginState('error');
setMessage(result.message || t('wechatConfig.qrExpired'));
activeSessionKeyRef.current = null;
stopPolling();
return;
} else if (status === 'error') {
+ setNeedsVerifyCode(false);
setLoginState('error');
setMessage(result.message || t('wechatConfig.pollError'));
activeSessionKeyRef.current = null;
@@ -178,6 +209,70 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBack
void pollOnce();
};
+ const submitVerifyCode = async () => {
+ const key = activeSessionKeyRef.current;
+ const code = verifyCode.trim();
+ if (!key || !code) return;
+ stopPolling();
+ try {
+ const result = await api.wechatPollLogin(key, code);
+ if (!result || activeSessionKeyRef.current !== key) return;
+ if (result.status === 'confirmed') {
+ setNeedsVerifyCode(false);
+ setVerifyCode('');
+ setLoginState('connected');
+ setMessage(result.message || t('wechatConfig.connected'));
+ setBotToken(result.bot_token || '');
+ setBaseUrl(result.base_url || '');
+ activeSessionKeyRef.current = null;
+ return;
+ }
+ if (result.status === 'already_connected') {
+ setNeedsVerifyCode(false);
+ setVerifyCode('');
+ setLoginState('connected');
+ setMessage(result.message || t('wechatConfig.connected'));
+ preserveExistingConnectionFields(result);
+ activeSessionKeyRef.current = null;
+ return;
+ }
+ if (result.status === 'scaned') {
+ setNeedsVerifyCode(false);
+ setVerifyCode('');
+ setLoginState('confirming');
+ setMessage(result.message || t('wechatConfig.confirmOnPhone'));
+ startPolling(key);
+ return;
+ }
+ if (result.status === 'need_verifycode') {
+ setNeedsVerifyCode(true);
+ setLoginState('confirming');
+ setMessage(result.message || t('wechatConfig.verifyCodePrompt'));
+ return;
+ }
+ if (result.status === 'refreshed') {
+ setNeedsVerifyCode(false);
+ setVerifyCode('');
+ setLoginState('qr_ready');
+ setQrCodeUrl(result.qrcode_url || '');
+ setMessage(result.message || t('wechatConfig.qrExpired'));
+ startPolling(key);
+ return;
+ }
+ if (result.status === 'error' || result.status === 'expired') {
+ setNeedsVerifyCode(false);
+ setLoginState('error');
+ setMessage(result.message || t('wechatConfig.pollError'));
+ activeSessionKeyRef.current = null;
+ return;
+ }
+ startPolling(key);
+ } catch (err: any) {
+ setMessage(err?.message || t('wechatConfig.pollError'));
+ startPolling(key);
+ }
+ };
+
const canProceed = hasUsableSecret(data.wechat, 'bot_token', botToken);
const isAlreadyBound = loginState === 'idle' && !botToken && hasUsableSecret(data.wechat, 'bot_token');
@@ -200,7 +295,7 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBack
platform: 'wechat',
wechat: {
...withSecretDraft(data.wechat, 'bot_token', botToken),
- base_url: baseUrl,
+ base_url: baseUrl || data.wechat?.base_url || '',
proxy_url: proxyUrl || undefined,
},
});
@@ -334,6 +429,20 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBack
)}
</div>
<p className="text-center text-[11px] text-muted">{t('wechatConfig.scanHint')}</p>
+ {needsVerifyCode && (
+ <div className="w-full max-w-xs space-y-2">
+ <Input
+ value={verifyCode}
+ onChange={(event) => setVerifyCode(event.target.value)}
+ inputMode="numeric"
+ autoComplete="one-time-code"
+ placeholder={t('wechatConfig.verifyCodePlaceholder')}
+ />
+ <Button type="button" variant="brand" size="sm" className="w-full" onClick={submitVerifyCode}>
+ {t('wechatConfig.submitVerifyCode')}
+ </Button>
+ </div>
+ )}
</div>
</div>
)}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 52e42bbbf..08820eb87 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -121,7 +121,7 @@ export type ApiContextType = {
larkTempWsStart: (appId: string, appSecret?: string, domain?: string) => Promise<any>;
larkTempWsStop: () => Promise<any>;
wechatStartLogin: () => Promise<any>;
- wechatPollLogin: (sessionKey: string) => Promise<any>;
+ wechatPollLogin: (sessionKey: string, verifyCode?: string) => Promise<any>;
doctor: () => Promise<any>;
opencodeOptions: (cwd: string) => Promise<any>;
opencodeSetupPermission: () => Promise<{ ok: boolean; message: string; config_path: string }>;
@@ -1647,7 +1647,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
larkTempWsStart: (appId, appSecret, domain) => postJson('/api/lark/temp_ws/start', { app_id: appId, app_secret: appSecret, domain: domain || 'feishu' }),
larkTempWsStop: () => postJson('/api/lark/temp_ws/stop', {}),
wechatStartLogin: () => postJson('/api/wechat/qr_login/start', {}),
- wechatPollLogin: (sessionKey) => postJson('/api/wechat/qr_login/poll', { session_key: sessionKey }),
+ wechatPollLogin: (sessionKey, verifyCode) => postJson('/api/wechat/qr_login/poll', { session_key: sessionKey, verify_code: verifyCode || undefined }),
doctor: () => postJson('/api/doctor', {}),
opencodeOptions: (cwd) => postJson('/api/opencode/options', { cwd }),
opencodeSetupPermission: () => postJson('/api/opencode/setup-permission', {}),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 75db7b7d8..c3896c11c 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -999,6 +999,9 @@
"startFailed": "Failed to start login flow",
"waitingForScan": "Waiting for you to scan the QR code...",
"confirmOnPhone": "Scanned! Please confirm on your phone.",
+ "verifyCodePrompt": "Enter the verification code shown in WeChat.",
+ "verifyCodePlaceholder": "Verification code",
+ "submitVerifyCode": "Continue",
"scanHint": "Open WeChat on your phone and scan this QR code to log in.",
"connected": "WeChat connected successfully!",
"connectedTitle": "Connected",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 5b8dc32bc..ad2614667 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -999,6 +999,9 @@
"startFailed": "启动登录流程失败",
"waitingForScan": "等待扫描二维码...",
"confirmOnPhone": "已扫描!请在手机上确认。",
+ "verifyCodePrompt": "请输入微信中显示的验证码。",
+ "verifyCodePlaceholder": "验证码",
+ "submitVerifyCode": "继续",
"scanHint": "打开手机微信,扫描此二维码登录。",
"connected": "微信连接成功!",
"connectedTitle": "已连接",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index e4f71676a..dd2ee1990 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3144,6 +3144,20 @@ def _get_wechat_auth():
return _wechat_auth_manager
+def _load_wechat_local_tokens() -> list[str]:
+ try:
+ from core.services import settings as settings_service
+
+ config = settings_service.load_config()
+ except Exception:
+ logger.warning("Failed to load WeChat local token list for QR login", exc_info=True)
+ return []
+ token = getattr(getattr(config, "wechat", None), "bot_token", "")
+ if isinstance(token, str) and token.strip():
+ return [token.strip()]
+ return []
+
+
def _schedule_wechat_qr_login_restart() -> dict:
"""Schedule a managed restart after QR-login credentials are persisted."""
from vibe.restart_supervisor import schedule_restart
@@ -3151,14 +3165,48 @@ def _schedule_wechat_qr_login_restart() -> dict:
return schedule_restart(delay_seconds=2.0, trigger="wechat-qr-login")
+def _persist_wechat_qr_credentials(result: dict) -> None:
+ token = result.get("bot_token")
+ if not isinstance(token, str) or not token.strip():
+ return
+
+ from vibe import api as vibe_api
+ from core.services import settings as settings_service
+
+ config = settings_service.load_config(default_factory=settings_service.default_config)
+ current = vibe_api.config_to_payload(config, include_secrets=True)
+ wechat = dict(current.get("wechat") or {})
+ wechat["bot_token"] = token.strip()
+ if isinstance(result.get("base_url"), str) and result["base_url"].strip():
+ wechat["base_url"] = result["base_url"].strip()
+ elif not wechat.get("base_url"):
+ wechat["base_url"] = "https://ilinkai.weixin.qq.com"
+ current["wechat"] = wechat
+
+ platforms = dict(current.get("platforms") or {})
+ enabled = list(platforms.get("enabled") or [])
+ if "wechat" not in enabled:
+ enabled.append("wechat")
+ platforms["enabled"] = enabled
+ if not platforms.get("primary") or platforms.get("primary") == "avibe":
+ platforms["primary"] = "wechat"
+ current["platforms"] = platforms
+
+ vibe_api.save_config(current)
+
+
+WECHAT_QR_LOGIN_BASE_URL = "https://ilinkai.weixin.qq.com"
+
+
@app.route("/api/wechat/qr_login/start", methods=["POST"])
async def wechat_qr_login_start():
"""Start WeChat QR code login flow."""
auth = _get_wechat_auth()
- payload = request.json or {}
- base_url = payload.get("base_url", "https://ilinkai.weixin.qq.com")
- result = await auth.start_login(base_url=base_url)
+ result = await auth.start_login(
+ base_url=WECHAT_QR_LOGIN_BASE_URL,
+ local_token_list=_load_wechat_local_tokens(),
+ )
if result.get("ok") is False:
return jsonify(result), 500
return jsonify(result)
@@ -3171,15 +3219,24 @@ async def wechat_qr_login_poll():
session_key = payload.get("session_key", "")
if not session_key:
return jsonify({"error": "session_key required"}), 400
+ verify_code = payload.get("verify_code")
+ if verify_code is not None and not isinstance(verify_code, str):
+ return jsonify({"error": "invalid_verify_code"}), 400
auth = _get_wechat_auth()
- result = await auth.poll_status(session_key)
+ result = await auth.poll_status(session_key, verify_code=verify_code)
if result.get("ok") is False:
return jsonify(result), 500
# If confirmed, auto-bind the WeChat user
- if result.get("status") == "confirmed" and result.get("bot_token"):
- user_id = result.get("user_id", "wechat_user")
+ if result.get("status") == "confirmed" and result.get("bot_token") and result.get("user_id"):
+ user_id = result["user_id"]
+
+ try:
+ _persist_wechat_qr_credentials(result)
+ except Exception as exc:
+ logger.error("Failed to persist WeChat QR credentials: %s", exc)
+ return jsonify({"ok": False, "error": "failed_to_persist_wechat_credentials"}), 500
# Auto-bind user
try: