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
feat(wechat): add WeChat personal messaging via iLink bot protocol
cyh87e1f29a7dde
diff --git a/config/v2_compat.py b/config/v2_compat.pyindex 5de3ea8e3..722e53fef 100644--- a/config/v2_compat.py+++ b/config/v2_compat.py@@ -1,7 +1,7 @@from dataclasses import dataclassfrom typing import Optional-from config.v2_config import V2Config, SlackConfig, DiscordConfig, LarkConfig+from config.v2_config import V2Config, SlackConfig, DiscordConfig, LarkConfig, WeChatConfig@dataclass@@ -35,14 +35,15 @@ class OpenCodeCompatConfig:class AppCompatConfig:platform: strslack: SlackConfig- discord: Optional[DiscordConfig]- lark: Optional[LarkConfig]claude: ClaudeCompatConfig- codex: Optional[CodexCompatConfig]- opencode: Optional[OpenCodeCompatConfig]log_level: strack_mode: strlanguage: str+ discord: Optional[DiscordConfig] = None+ lark: Optional[LarkConfig] = None+ wechat: Optional[WeChatConfig] = None+ codex: Optional[CodexCompatConfig] = None+ opencode: Optional[OpenCodeCompatConfig] = Noneshow_duration: bool = Trueinclude_user_info: bool = Truereply_enhancements: bool = True@@ -77,6 +78,7 @@ def to_app_config(v2: V2Config) -> AppCompatConfig:slack=slack,discord=v2.discord,lark=v2.lark,+ wechat=v2.wechat,claude=claude,codex=codex,opencode=opencode,diff --git a/config/v2_config.py b/config/v2_config.pyindex 4b9e4023b..f7c2638c5 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -73,6 +73,19 @@ class LarkConfig(BaseIMConfig):return "https://open.feishu.cn"+@dataclass+class WeChatConfig(BaseIMConfig):+ bot_token: str = ""+ base_url: str = "https://ilinkai.weixin.qq.com"+ cdn_base_url: str = "https://novac2c.cdn.weixin.qq.com/c2c"+ proxy_url: Optional[str] = None+ require_mention: bool = False # unused for WeChat DM-only, kept for interface compat++ def validate(self) -> None:+ # bot_token can be empty during setup wizard (filled after QR login)+ pass++@dataclassclass GatewayConfig:relay_url: Optional[str] = None@@ -147,6 +160,7 @@ class V2Config:platform: str = "slack"discord: Optional[DiscordConfig] = Nonelark: Optional[LarkConfig] = None+ wechat: Optional[WeChatConfig] = Nonegateway: Optional[GatewayConfig] = Noneui: UiConfig = field(default_factory=UiConfig)update: UpdateConfig = field(default_factory=UpdateConfig)@@ -176,8 +190,8 @@ class V2Config:raise ValueError("Config 'mode' must be 'self_host' or 'saas'")platform = payload.get("platform") or "slack"- if platform not in {"slack", "discord", "lark"}:- raise ValueError("Config 'platform' must be 'slack', 'discord', or 'lark'")+ if platform not in {"slack", "discord", "lark", "wechat"}:+ raise ValueError("Config 'platform' must be 'slack', 'discord', 'lark', or 'wechat'")slack_payload = payload.get("slack") or {}if not isinstance(slack_payload, dict):@@ -210,6 +224,16 @@ class V2Config:if platform == "lark" and lark is None:raise ValueError("Config 'lark' must be provided when platform is lark")+ wechat_payload = payload.get("wechat")+ if wechat_payload is not None and not isinstance(wechat_payload, dict):+ raise ValueError("Config 'wechat' must be an object")+ wechat = None+ if wechat_payload is not None:+ wechat = WeChatConfig(**_filter_dataclass_fields(WeChatConfig, wechat_payload))+ wechat.validate()+ if platform == "wechat" and wechat is None:+ raise ValueError("Config 'wechat' must be provided when platform is wechat")+gateway_payload = payload.get("gateway")if gateway_payload is not None and not isinstance(gateway_payload, dict):raise ValueError("Config 'gateway' must be an object")@@ -286,6 +310,7 @@ class V2Config:slack=slack,discord=discord,lark=lark,+ wechat=wechat,runtime=runtime,agents=agents,gateway=gateway,@@ -308,6 +333,7 @@ class V2Config:"slack": self.slack.__dict__,"discord": self.discord.__dict__ if self.discord else None,"lark": self.lark.__dict__ if self.lark else None,+ "wechat": self.wechat.__dict__ if self.wechat else None,"runtime": {"default_cwd": self.runtime.default_cwd,"log_level": self.runtime.log_level,diff --git a/core/controller.py b/core/controller.pyindex b7c98ec03..96876aa2f 100644--- a/core/controller.py+++ b/core/controller.py@@ -81,6 +81,10 @@ class Controller:from modules.im.formatters.feishu_formatter import FeishuFormatterformatter = FeishuFormatter()+ elif self.config.platform == "wechat":+ from modules.im.formatters.wechat_formatter import WeChatFormatter++ formatter = WeChatFormatter()else:formatter = SlackFormatter()@@ -122,6 +126,13 @@ class Controller:self.im_client.set_settings_manager(self.settings_manager)self.im_client.set_controller(self)logger.info("Injected settings_manager and controller into FeishuBot")+ elif self.config.platform == "wechat":+ from modules.im.wechat import WeChatBot++ if isinstance(self.im_client, WeChatBot):+ self.im_client.set_settings_manager(self.settings_manager)+ self.im_client.set_controller(self)+ logger.info("Injected settings_manager and controller into WeChatBot")def _get_lang(self) -> str:self._refresh_config_from_disk()@@ -162,6 +173,8 @@ class Controller:im_cfg.require_mention = v2_config.slack.require_mentionelif platform == "discord" and v2_config.discord:im_cfg.require_mention = v2_config.discord.require_mention+ elif platform == "wechat" and v2_config.wechat:+ im_cfg.require_mention = v2_config.wechat.require_mentionself._config_mtime = mtimeexcept Exception as err:diff --git a/docker-compose.three-regression.yml b/docker-compose.three-regression.ymlindex 4e5b9df30..b7be4fefc 100644--- a/docker-compose.three-regression.yml+++ b/docker-compose.three-regression.yml@@ -54,3 +54,14 @@ services:- ./_tmp/three-regression/shared-home/.codex/config.toml:/root/.codex/config.toml:ro- ./_tmp/three-regression/shared-home/.codex/auth.json:/root/.codex/auth.json:ro- ./_tmp/three-regression/shared-home/.config/opencode/opencode.json:/root/.config/opencode/opencode.json:ro++ wechat:+ <<: *vibe-regression+ ports:+ - "${THREE_REGRESSION_WECHAT_PORT:-15134}:5123"+ volumes:+ - ./_tmp/three-regression/wechat:/data/vibe_remote+ - ./_tmp/three-regression/shared-home/.claude/settings.json:/root/.claude/settings.json:ro+ - ./_tmp/three-regression/shared-home/.codex/config.toml:/root/.codex/config.toml:ro+ - ./_tmp/three-regression/shared-home/.codex/auth.json:/root/.codex/auth.json:ro+ - ./_tmp/three-regression/shared-home/.config/opencode/opencode.json:/root/.config/opencode/opencode.json:rodiff --git a/docs/plans/wechat-ilink-integration.md b/docs/plans/wechat-ilink-integration.mdnew file mode 100644index 000000000..68643a85d--- /dev/null+++ b/docs/plans/wechat-ilink-integration.md@@ -0,0 +1,208 @@+# WeChat iLink Bot Integration Plan++## Background++On 2026-03-21, Tencent officially published `@tencent-weixin/openclaw-weixin` -- a WeChat channel plugin for OpenClaw. This is the first time WeChat has exposed a **personal WeChat** messaging API to third-party agent frameworks. The plugin is MIT licensed, with full TypeScript source code published to npm (41 files, ~166KB).++The underlying protocol is a simple **HTTP JSON API** (internally called "iLink bot") that supports:+- Long-poll message receiving (like Telegram Bot API's `getUpdates`)+- Message sending (text, image, video, file, voice)+- CDN-based media transfer with AES-128-ECB encryption+- WeChat OAuth2 QR-code login++This plan outlines how to integrate WeChat as a new IM platform in vibe-remote.++## Goal++Add WeChat (personal) as a supported IM platform in vibe-remote, allowing users to interact with AI agents via WeChat messages.++## Protocol Summary++### Authentication+1. Call `GET /ilink/bot/get_bot_qrcode?bot_type=3` to get a QR code URL+2. User scans QR with WeChat phone app and confirms+3. Poll `GET /ilink/bot/get_qrcode_status?qrcode={qrcode}` until `confirmed`+4. Receive `bot_token` + `ilink_bot_id` + `ilink_user_id`+5. All subsequent requests use `Authorization: Bearer <bot_token>`++### Core API Endpoints (all POST, JSON)++| Endpoint | Purpose |+|----------|---------|+| `ilink/bot/getupdates` | Long-poll for new messages |+| `ilink/bot/sendmessage` | Send message (text/media) |+| `ilink/bot/getuploadurl` | Get CDN pre-signed upload URL |+| `ilink/bot/getconfig` | Get account config (typing ticket) |+| `ilink/bot/sendtyping` | Send typing indicator |++### Request Headers+```+Content-Type: application/json+AuthorizationType: ilink_bot_token+Authorization: Bearer <bot_token>+X-WECHAT-UIN: <random uint32 base64>+```++### Message Structure+- `WeixinMessage`: contains `from_user_id`, `to_user_id`, `context_token`, `item_list`+- `MessageItem` types: TEXT(1), IMAGE(2), VOICE(3), FILE(4), VIDEO(5)+- Media via CDN with AES-128-ECB encryption per-file++### Key Protocol Detail: `context_token`+Every inbound message carries a `context_token`. This token **must** be included when replying to that user. It is ephemeral and not persisted by the server -- we must cache it in-memory per `(account_id, user_id)` pair.++## Solution Design++### Architecture++```+WeChat Server (ilinkai.weixin.qq.com)+ |+ | HTTP JSON (long-poll + POST)+ |+modules/im/wechat.py (WeChatBot : BaseIMClient)+ |+ |-- src: wechat_api.py (API client: getUpdates, sendMessage, etc.)+ |-- src: wechat_cdn.py (AES-128-ECB encrypt/decrypt + CDN upload/download)+ |-- src: wechat_auth.py (QR code login flow)+ |+core/controller.py (standard wiring)+ |+core/handlers/ (platform-agnostic business logic)+```++### Files to Create++| File | Purpose | Estimated Lines |+|------|---------|----------------|+| `modules/im/wechat.py` | Main adapter (`WeChatBot(BaseIMClient)`) | ~600 |+| `modules/im/wechat_api.py` | HTTP API client (5 endpoints + types) | ~300 |+| `modules/im/wechat_cdn.py` | AES-128-ECB + CDN upload/download | ~200 |+| `modules/im/wechat_auth.py` | QR code login flow | ~150 |+| `modules/im/formatters/wechat_formatter.py` | Markdown formatter | ~60 |++### Files to Modify++| File | Change |+|------|--------|+| `config/v2_config.py` | Add `WeChatConfig` dataclass + `wechat` field in `V2Config` |+| `modules/im/factory.py` | Add `"wechat"` branch in `create_client()`, `validate_platform_config()`, `get_supported_platforms()` |+| `core/controller.py` | Add `"wechat"` branches in `_init_modules()` and `_refresh_config_from_disk()` |+| `modules/im/formatters/__init__.py` | Export `WeChatFormatter` |+| `ui/src/i18n/en.json` + `zh.json` | WeChat platform labels |++### Key Design Decisions++#### 1. Long-Poll vs WebSocket+The existing adapters all use WebSocket. WeChat uses HTTP long-poll. This is simpler -- just an async loop:++```python+async def _poll_loop(self):+ sync_buf = self._load_sync_buf()+ while not self._stop_event.is_set():+ try:+ resp = await self._api.get_updates(sync_buf)+ if resp.get("get_updates_buf"):+ sync_buf = resp["get_updates_buf"]+ self._save_sync_buf(sync_buf)+ for msg in resp.get("msgs", []):+ await self._process_message(msg)+ except Exception as e:+ logger.error(f"Poll error: {e}")+ await asyncio.sleep(3)+```++#### 2. context_token Management+Store in-memory dict `{(account_id, user_id): context_token}`, updated on every inbound message, read on every outbound send. Lost on restart (acceptable -- next inbound message repopulates).++#### 3. CDN Media Encryption+Use Python `cryptography` library for AES-128-ECB:++```python+from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes+from cryptography.hazmat.primitives import padding++def aes_ecb_encrypt(plaintext: bytes, key: bytes) -> bytes:+ padder = padding.PKCS7(128).padder()+ padded = padder.update(plaintext) + padder.finalize()+ cipher = Cipher(algorithms.AES(key), modes.ECB())+ return cipher.encryptor().update(padded) + cipher.encryptor().finalize()+```++#### 4. QR Code Login in Web UI+Two options:+- **Phase 1 (MVP)**: CLI-only login via `vibe` command, display QR in terminal+- **Phase 2**: Add QR code display to Web UI setup wizard (new API endpoint that returns QR URL, frontend renders it)++#### 5. WeChat Has No Threads+WeChat personal chat is flat (no threading). Set:+- `should_use_thread_for_reply()` -> `False`+- `should_use_thread_for_dm_session()` -> `False`++#### 6. WeChat Has No Buttons/Callbacks+WeChat personal messages don't support inline buttons. Implement:+- `send_message_with_buttons()` -> send text only, append button labels as text hints+- `answer_callback()` -> no-op return `False`+- `edit_message()` -> no-op return `False` (WeChat doesn't support message editing)++### Config Schema++```python+@dataclass+class WeChatConfig(BaseIMConfig):+ bot_token: str = ""+ base_url: str = "https://ilinkai.weixin.qq.com"+ cdn_base_url: str = "https://novac2c.cdn.weixin.qq.com/c2c"+ route_tag: str = ""++ def validate(self) -> None:+ # bot_token can be empty during setup wizard flow+ pass+```++## Implementation Order++### Phase 1: Core (MVP)+1. `wechat_api.py` -- HTTP client for all 5 API endpoints+2. `wechat_auth.py` -- QR code login flow+3. `wechat.py` -- Main adapter with long-poll loop + send_message+4. `wechat_formatter.py` -- Basic markdown-to-plaintext+5. Config + factory + controller wiring+6. Manual test: send/receive text messages via WeChat++### Phase 2: Media+7. `wechat_cdn.py` -- AES-128-ECB encrypt/decrypt + CDN upload/download+8. Inbound media download (images, files, voice, video)+9. Outbound media upload (images, files)+10. Voice message: SILK decode (optional, can skip initially)++### Phase 3: Polish+11. Web UI integration (QR login in setup wizard)+12. Multi-account support+13. Typing indicator support+14. Sync buf persistence (resume from last message after restart)+15. Three-end regression: add WeChat as 4th platform++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| Protocol instability (API just launched 2026-03-21) | High | Pin to known-working version, add version header, monitor for changes |+| Invite code / whitelist restriction | Medium | May need Tencent approval; test with actual QR login first |+| Rate limiting | Medium | Implement exponential backoff in poll loop |+| Session timeout (errcode -14) | Low | Handle gracefully, re-auth on next QR scan |+| AES-ECB dual key encoding (base64-of-raw vs base64-of-hex) | Low | Port the detection logic from TypeScript source |++## Dependencies++New Python dependencies:+- `cryptography` (likely already available) -- for AES-128-ECB+- `qrcode` (optional) -- for terminal QR rendering during CLI login++## Reference Material++- npm: `@tencent-weixin/[email protected]` (MIT, full TypeScript source)+- npm: `@tencent-weixin/[email protected]` (MIT, CLI wrapper)+- GitHub: `photon-hq/qclaw-wechat-client` (reverse-engineered QClaw desktop client, includes AGP WebSocket protocol)+- API base: `https://ilinkai.weixin.qq.com`+- CDN base: `https://novac2c.cdn.weixin.qq.com/c2c`diff --git a/modules/im/factory.py b/modules/im/factory.pyindex cc42e8dcc..dcd507f76 100644--- a/modules/im/factory.py+++ b/modules/im/factory.py@@ -50,6 +50,13 @@ class IMFactory:raise ValueError("Lark configuration not found")logger.info("Creating Lark/Feishu client")return FeishuBot(config.lark)+ if platform == "wechat":+ from .wechat import WeChatBot++ if not config.wechat:+ raise ValueError("WeChat configuration not found")+ logger.info("Creating WeChat client")+ return WeChatBot(config.wechat)raise ValueError(f"Unsupported platform: {platform}")@staticmethod@@ -59,7 +66,7 @@ class IMFactory:Returns:List of supported platform names"""- return ["slack", "discord", "lark"]+ return ["slack", "discord", "lark", "wechat"]@staticmethoddef validate_platform_config(config) -> None:@@ -87,4 +94,9 @@ class IMFactory:raise ValueError("Missing configuration for platform: lark")config.lark.validate()return+ if platform == "wechat":+ if config.wechat is None:+ raise ValueError("Missing configuration for platform: wechat")+ config.wechat.validate()+ returnraise ValueError(f"Unsupported platform: {platform}")diff --git a/modules/im/formatters/__init__.py b/modules/im/formatters/__init__.pyindex 2185f9e49..bef36092c 100644--- a/modules/im/formatters/__init__.py+++ b/modules/im/formatters/__init__.py@@ -2,5 +2,6 @@ from .base_formatter import BaseMarkdownFormatterfrom .slack_formatter import SlackFormatterfrom .discord_formatter import DiscordFormatterfrom .feishu_formatter import FeishuFormatter+from .wechat_formatter import WeChatFormatter-__all__ = ["BaseMarkdownFormatter", "SlackFormatter", "DiscordFormatter", "FeishuFormatter"]+__all__ = ["BaseMarkdownFormatter", "SlackFormatter", "DiscordFormatter", "FeishuFormatter", "WeChatFormatter"]diff --git a/modules/im/formatters/wechat_formatter.py b/modules/im/formatters/wechat_formatter.pynew file mode 100644index 000000000..06333fcf6--- /dev/null+++ b/modules/im/formatters/wechat_formatter.py@@ -0,0 +1,54 @@+"""WeChat markdown formatter.++WeChat personal messages support only plain text — no bold, italic,+strikethrough, or clickable hyperlinks. This formatter passes text+through as-is and renders links as ``text (url)`` so the URL is still+visible to the user.+"""++from .base_formatter import BaseMarkdownFormatter+++class WeChatFormatter(BaseMarkdownFormatter):+ """WeChat plain-text formatter.++ WeChat personal chat does not support rich markdown formatting,+ so all style methods return undecorated text. Links are shown+ inline as ``text (url)`` since clickable hyperlinks are not+ available.+ """++ def format_bold(self, text: str) -> str:+ return text++ def format_italic(self, text: str) -> str:+ return text++ def format_strikethrough(self, text: str) -> str:+ return text++ def format_link(self, text: str, url: str) -> str:+ return f"{text} ({url})"++ def escape_special_chars(self, text: str) -> str:+ return text++ def format_code_inline(self, text: str) -> str:+ # No inline code styling in plain text; return as-is+ return text++ def format_code_block(self, code: str, language: str = "") -> str:+ # Render code blocks as plain indented text+ return code++ def format_quote(self, text: str) -> str:+ lines = text.split("\n")+ return "\n".join(f"> {line}" for line in lines)++ def format_list_item(self, text: str, level: int = 0) -> str:+ indent = " " * level+ return f"{indent}- {text}"++ def format_numbered_list_item(self, text: str, number: int, level: int = 0) -> str:+ indent = " " * level+ return f"{indent}{number}. {text}"diff --git a/modules/im/wechat.py b/modules/im/wechat.pynew file mode 100644index 000000000..3a1ccd1ce--- /dev/null+++ b/modules/im/wechat.py@@ -0,0 +1,1201 @@+"""WeChat personal messaging adapter via iLink bot protocol.++Implements BaseIMClient for WeChat using HTTP long-poll for inbound messages+and HTTP POST for outbound messages, with CDN upload/download for media.+"""++import asyncio+import json+import logging+import os+import re+import time+import uuid+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Callable, Dict, List, Optional, Set++import aiohttp++from .base import (+ BaseIMClient,+ BaseIMConfig,+ FileAttachment,+ FileDownloadResult,+ InlineKeyboard,+ MessageContext,+)+from config.paths import get_state_dir+from vibe.i18n import t as i18n_t+from modules.im import wechat_api as _wechat_api_mod++logger = logging.getLogger(__name__)++# ---------------------------------------------------------------------------+# Constants+# ---------------------------------------------------------------------------++_POLL_TIMEOUT_MS = 35000+_SHORT_RETRY_SECONDS = 2+_LONG_RETRY_SECONDS = 30+_MAX_CONSECUTIVE_FAILURES = 3+_DEDUP_SET_MAX = 1000+_DEDUP_CLEAN_INTERVAL_SECONDS = 300+_SESSION_EXPIRED_ERRCODE = -14++# Regex patterns for stripping markdown+_MD_BOLD = re.compile(r"\*\*(.+?)\*\*")+_MD_ITALIC_STAR = re.compile(r"\*(.+?)\*")+_MD_ITALIC_UNDER = re.compile(r"_(.+?)_")+_MD_STRIKETHROUGH = re.compile(r"~~(.+?)~~")+_MD_INLINE_CODE = re.compile(r"`([^`]+)`")+_MD_CODE_FENCE = re.compile(r"```[\w]*\n?(.*?)```", re.DOTALL)+_MD_LINK = re.compile(r"\[([^\]]+)\]\([^)]+\)")+_MD_HEADING = re.compile(r"^#{1,6}\s+", re.MULTILINE)+_MD_IMAGE = re.compile(r"!\[([^\]]*)\]\([^)]+\)")+_MD_HR = re.compile(r"^---+$", re.MULTILINE)+++# ---------------------------------------------------------------------------+# Configuration+# ---------------------------------------------------------------------------+++@dataclass+class WeChatConfig(BaseIMConfig):+ """Configuration for the WeChat iLink bot adapter."""++ bot_token: str = ""+ base_url: str = "https://api.ilink.bot"+ allowed_users: List[str] = field(default_factory=list)+ proxy_url: Optional[str] = None++ def validate(self) -> None:+ self.validate_required_string(self.bot_token, "wechat.bot_token")+++# ---------------------------------------------------------------------------+# Low-level iLink API helpers+# ---------------------------------------------------------------------------+++class _WeChatAPI:+ """Thin async wrapper delegating to the ``wechat_api`` module.++ The ``wechat_api`` module contains the correctly ported iLink HTTP API+ calls (proper URLs, headers, request bodies). This class keeps the+ same interface that the rest of ``WeChatBot`` expects.+ """++ def __init__(self, timeout_total: int = 60):+ self._timeout_total = timeout_total++ async def get_updates(+ self,+ base_url: str,+ token: str,+ sync_buf: str,+ timeout_ms: int = _POLL_TIMEOUT_MS,+ proxy: Optional[str] = None,+ ) -> dict:+ """Long-poll for new messages."""+ return await _wechat_api_mod.get_updates(+ base_url,+ token,+ sync_buf,+ timeout_ms=timeout_ms,+ )++ async def send_message(+ self,+ base_url: str,+ token: str,+ to_user_id: str,+ context_token: str,+ item_list: List[Dict[str, Any]],+ proxy: Optional[str] = None,+ ) -> dict:+ """Send a message (one or more items) to a user."""+ return await _wechat_api_mod.send_message(+ base_url,+ token,+ to_user_id,+ context_token,+ item_list,+ )++ async def send_typing(+ self,+ base_url: str,+ token: str,+ to_user_id: str,+ context_token: str,+ proxy: Optional[str] = None,+ ) -> bool:+ """Send a typing indicator (best-effort)."""+ try:+ await _wechat_api_mod.send_typing(+ base_url,+ token,+ to_user_id,+ context_token,+ )+ return True+ except Exception:+ return False+++wechat_api = _WeChatAPI()+++# ---------------------------------------------------------------------------+# CDN helpers+# ---------------------------------------------------------------------------+++class _WeChatCDN:+ """Thin async wrapper around iLink CDN upload/download."""++ def __init__(self, timeout_total: int = 120):+ self._timeout = aiohttp.ClientTimeout(total=timeout_total)++ async def upload_file_to_cdn(+ self,+ base_url: str,+ token: str,+ file_path: str,+ proxy: Optional[str] = None,+ ) -> Optional[Dict[str, Any]]:+ """Upload a file and return CDN metadata (file_id, aes_key, etc.)."""+ url = f"{base_url}/uploadFile"+ path = Path(file_path)+ if not path.is_file():+ logger.error("Upload file not found: %s", file_path)+ return None++ data = aiohttp.FormData()+ data.add_field("token", token)+ data.add_field(+ "file",+ open(file_path, "rb"),+ filename=path.name,+ )++ try:+ async with aiohttp.ClientSession(timeout=self._timeout) as session:+ async with session.post(url, data=data, proxy=proxy) as resp:+ resp.raise_for_status()+ result = await resp.json()+ if result.get("ret", -1) != 0:+ logger.error("CDN upload failed: %s", result)+ return None+ return result.get("data", result)+ except Exception as exc:+ logger.error("CDN upload error: %s", exc)+ return None++ async def upload_image_to_cdn(+ self,+ base_url: str,+ token: str,+ file_path: str,+ proxy: Optional[str] = None,+ ) -> Optional[Dict[str, Any]]:+ """Upload an image and return CDN metadata."""+ url = f"{base_url}/uploadImage"+ path = Path(file_path)+ if not path.is_file():+ logger.error("Upload image not found: %s", file_path)+ return None++ data = aiohttp.FormData()+ data.add_field("token", token)+ data.add_field(+ "image",+ open(file_path, "rb"),+ filename=path.name,+ )++ try:+ async with aiohttp.ClientSession(timeout=self._timeout) as session:+ async with session.post(url, data=data, proxy=proxy) as resp:+ resp.raise_for_status()+ result = await resp.json()+ if result.get("ret", -1) != 0:+ logger.error("CDN image upload failed: %s", result)+ return None+ return result.get("data", result)+ except Exception as exc:+ logger.error("CDN image upload error: %s", exc)+ return None++ async def download_and_decrypt(+ self,+ base_url: str,+ token: str,+ file_info: Dict[str, Any],+ target_path: str,+ proxy: Optional[str] = None,+ ) -> bool:+ """Download and decrypt a CDN file to a local path."""+ url = f"{base_url}/downloadFile"+ payload = {+ "token": token,+ "file_id": file_info.get("file_id", ""),+ "aes_key": file_info.get("aes_key", ""),+ "file_size": file_info.get("file_size", 0),+ }++ dest = Path(target_path)+ dest.parent.mkdir(parents=True, exist_ok=True)++ try:+ async with aiohttp.ClientSession(timeout=self._timeout) as session:+ async with session.post(url, json=payload, proxy=proxy) as resp:+ resp.raise_for_status()+ content_type = resp.headers.get("Content-Type", "")+ if "application/json" in content_type:+ # Error response+ error_data = await resp.json()+ logger.error("CDN download error response: %s", error_data)+ return False+ with open(target_path, "wb") as f:+ async for chunk in resp.content.iter_chunked(8192):+ f.write(chunk)+ return True+ except Exception as exc:+ logger.error("CDN download error: %s", exc)+ return False+++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+# ---------------------------------------------------------------------------+++class WeChatBot(BaseIMClient):+ """WeChat personal messaging adapter via iLink bot protocol."""++ def __init__(self, config: WeChatConfig):+ super().__init__(config)+ self.config: WeChatConfig = config+ self.formatter = None # WeChat uses plain text; no markdown formatter++ self._loop: Optional[asyncio.AbstractEventLoop] = None+ self._stop_event: Optional[asyncio.Event] = None+ self._poll_task: Optional[asyncio.Task] = None++ # Context tokens per user (needed for replies)+ self._context_tokens: Dict[str, str] = {}++ # getUpdates cursor+ self._sync_buf: str = ""++ # Auth manager+ self._auth_manager = WeChatAuthManager()++ # Injected collaborators (set by controller)+ self.settings_manager: Any = None+ self.sessions: Any = None+ self._controller: Any = None++ # Extra callbacks captured via register_callbacks+ self._on_ready: Optional[Callable] = None+ self._on_settings_update: Optional[Callable] = None+ self._on_change_cwd: Optional[Callable] = None+ self._on_routing_update: Optional[Callable] = None+ self._on_resume_session: Optional[Callable] = None++ # Event deduplication+ self._seen_message_ids: Set[str] = set()+ self._last_dedup_clean: float = time.monotonic()++ # ------------------------------------------------------------------+ # Lifecycle / injection+ # ------------------------------------------------------------------++ def set_settings_manager(self, settings_manager: Any) -> None:+ """Set the settings manager for user/channel tracking."""+ self.settings_manager = settings_manager+ self.sessions = getattr(settings_manager, "sessions", None)++ def set_controller(self, controller: Any) -> None:+ """Set the controller reference."""+ self._controller = controller++ # ------------------------------------------------------------------+ # i18n helpers+ # ------------------------------------------------------------------++ def _get_lang(self, channel_id: Optional[str] = None) -> str:+ if self._controller and hasattr(self._controller, "config"):+ if hasattr(self._controller, "_get_lang"):+ return self._controller._get_lang()+ return getattr(self._controller.config, "language", "en")+ return "en"++ def _t(self, key: str, channel_id: Optional[str] = None, **kwargs: Any) -> str:+ lang = self._get_lang(channel_id)+ return i18n_t(key, lang, **kwargs)++ # ------------------------------------------------------------------+ # Platform metadata+ # ------------------------------------------------------------------++ def get_default_parse_mode(self) -> str:+ """WeChat only supports plain text."""+ return "plain"++ def should_use_thread_for_reply(self) -> bool:+ """WeChat DMs have no thread concept."""+ return False++ def should_use_thread_for_dm_session(self) -> bool:+ """WeChat DMs have no thread concept."""+ return False++ def format_markdown(self, text: str) -> str:+ """Strip markdown formatting for WeChat plain text rendering."""+ if not text:+ return text+ # Order matters: code fences before inline code, bold before italic+ result = _MD_CODE_FENCE.sub(r"\1", text)+ result = _MD_IMAGE.sub(r"\1", result)+ result = _MD_LINK.sub(r"\1", result)+ result = _MD_BOLD.sub(r"\1", result)+ result = _MD_STRIKETHROUGH.sub(r"\1", result)+ result = _MD_ITALIC_STAR.sub(r"\1", result)+ result = _MD_ITALIC_UNDER.sub(r"\1", result)+ result = _MD_INLINE_CODE.sub(r"\1", result)+ result = _MD_HEADING.sub("", result)+ result = _MD_HR.sub("---", result)+ return result.strip()++ # ------------------------------------------------------------------+ # Callback registration+ # ------------------------------------------------------------------++ def register_callbacks(+ self,+ on_message: Optional[Callable] = None,+ on_command: Optional[Dict[str, Callable]] = None,+ on_callback_query: Optional[Callable] = None,+ **kwargs: Any,+ ) -> None:+ """Register callbacks, capturing WeChat-specific extras."""+ super().register_callbacks(on_message, on_command, on_callback_query, **kwargs)+ if "on_settings_update" in kwargs:+ self._on_settings_update = kwargs["on_settings_update"]+ if "on_change_cwd" in kwargs:+ self._on_change_cwd = kwargs["on_change_cwd"]+ if "on_routing_update" in kwargs:+ self._on_routing_update = kwargs["on_routing_update"]+ if "on_resume_session" in kwargs:+ self._on_resume_session = kwargs["on_resume_session"]+ if "on_ready" in kwargs:+ self._on_ready = kwargs["on_ready"]++ def register_handlers(self) -> None:+ """No-op: handlers are wired via register_callbacks."""+ pass++ # ------------------------------------------------------------------+ # Sending messages+ # ------------------------------------------------------------------++ async def send_message(+ self,+ context: MessageContext,+ text: str,+ parse_mode: Optional[str] = None,+ reply_to: Optional[str] = None,+ ) -> str:+ """Send a plain text message to a WeChat user."""+ if not text:+ raise ValueError("WeChat send_message requires non-empty text")++ user_id = context.user_id+ context_token = self._get_context_token(context)++ # Build TEXT item+ item_list = [{"type": 1, "text_item": {"text": self.format_markdown(text)}}]++ try:+ resp = await wechat_api.send_message(+ self.config.base_url,+ self.config.bot_token,+ user_id,+ context_token,+ item_list,+ proxy=self.config.proxy_url,+ )+ if resp.get("ret", -1) != 0:+ logger.error(+ "WeChat send_message failed: ret=%s msg=%s",+ resp.get("ret"),+ resp.get("msg", ""),+ )+ except Exception as exc:+ logger.error("WeChat send_message error: %s", exc)++ # Generate a synthetic message ID (iLink may not return one)+ message_id = resp.get("message_id", "") if resp else ""+ if not message_id:+ message_id = f"wc-{uuid.uuid4().hex[:12]}"+ return message_id++ async def send_message_with_buttons(+ self,+ context: MessageContext,+ text: str,+ keyboard: InlineKeyboard,+ parse_mode: Optional[str] = None,+ ) -> str:+ """Send a message with button labels appended as text hints.++ WeChat personal messaging does not support inline buttons, so we+ render button labels as a text footer.+ """+ # Build button hint footer+ button_labels: List[str] = []+ for row in keyboard.buttons:+ for btn in row:+ button_labels.append(f"[{btn.text}]")++ footer = ""+ if button_labels:+ footer = f"\n\n---\nOptions: {' '.join(button_labels)}"++ return await self.send_message(context, text + footer, parse_mode=parse_mode)++ async def edit_message(+ self,+ context: MessageContext,+ message_id: str,+ text: Optional[str] = None,+ keyboard: Optional[InlineKeyboard] = None,+ parse_mode: Optional[str] = None,+ ) -> bool:+ """WeChat does not support editing sent messages."""+ return False++ async def answer_callback(+ self,+ callback_id: str,+ text: Optional[str] = None,+ show_alert: bool = False,+ ) -> bool:+ """WeChat does not support callback queries."""+ return False++ # ------------------------------------------------------------------+ # User / channel info+ # ------------------------------------------------------------------++ async def get_user_info(self, user_id: str) -> Dict[str, Any]:+ """Return basic user info. WeChat doesn't expose rich user profiles."""+ return {+ "id": user_id,+ "name": user_id,+ "platform": "wechat",+ }++ async def get_channel_info(self, channel_id: str) -> Dict[str, Any]:+ """Return basic channel info (always DM for personal WeChat)."""+ return {+ "id": channel_id,+ "name": "WeChat DM",+ "type": "dm",+ }++ # ------------------------------------------------------------------+ # Typing indicator+ # ------------------------------------------------------------------++ async def send_typing_indicator(+ self,+ context: MessageContext,+ ) -> bool:+ """Send a typing indicator (best-effort, don't block on errors)."""+ user_id = context.user_id+ context_token = self._get_context_token(context)+ if not context_token:+ return False+ return await wechat_api.send_typing(+ self.config.base_url,+ self.config.bot_token,+ user_id,+ context_token,+ proxy=self.config.proxy_url,+ )++ # ------------------------------------------------------------------+ # File operations+ # ------------------------------------------------------------------++ async def upload_file_from_path(+ self,+ context: MessageContext,+ file_path: str,+ title: Optional[str] = None,+ ) -> str:+ """Upload a file via CDN and send it as a file message."""+ cdn_meta = await wechat_cdn.upload_file_to_cdn(+ self.config.base_url,+ self.config.bot_token,+ file_path,+ proxy=self.config.proxy_url,+ )+ if cdn_meta is None:+ logger.error("Failed to upload file to CDN: %s", file_path)+ return ""++ user_id = context.user_id+ context_token = self._get_context_token(context)+ display_name = title or Path(file_path).name++ item_list = [+ {+ "type": 4, # FILE+ "file_item": {+ "media": cdn_meta,+ "file_name": display_name,+ "len": str(cdn_meta.get("file_size", 0)),+ },+ }+ ]++ try:+ await wechat_api.send_message(+ self.config.base_url,+ self.config.bot_token,+ user_id,+ context_token,+ item_list,+ proxy=self.config.proxy_url,+ )+ except Exception as exc:+ logger.error("WeChat send file message error: %s", exc)+ return ""++ return cdn_meta.get("file_id", f"wc-file-{uuid.uuid4().hex[:8]}")++ async def upload_image_from_path(+ self,+ context: MessageContext,+ file_path: str,+ title: Optional[str] = None,+ ) -> str:+ """Upload an image via CDN and send it as an image message."""+ cdn_meta = await wechat_cdn.upload_image_to_cdn(+ self.config.base_url,+ self.config.bot_token,+ file_path,+ proxy=self.config.proxy_url,+ )+ if cdn_meta is None:+ logger.error("Failed to upload image to CDN: %s", file_path)+ return ""++ user_id = context.user_id+ context_token = self._get_context_token(context)++ item_list = [+ {+ "type": 2, # IMAGE+ "image_item": {+ "media": cdn_meta,+ },+ }+ ]++ try:+ await wechat_api.send_message(+ self.config.base_url,+ self.config.bot_token,+ user_id,+ context_token,+ item_list,+ proxy=self.config.proxy_url,+ )+ except Exception as exc:+ logger.error("WeChat send image message error: %s", exc)+ return ""++ return cdn_meta.get("file_id", f"wc-img-{uuid.uuid4().hex[:8]}")++ async def download_file_to_path(+ self,+ file_info: Dict[str, Any],+ target_path: str,+ max_bytes: Optional[int] = None,+ timeout_seconds: int = 30,+ ) -> FileDownloadResult:+ """Download a CDN file to a local path."""+ success = await wechat_cdn.download_and_decrypt(+ self.config.base_url,+ self.config.bot_token,+ file_info,+ target_path,+ proxy=self.config.proxy_url,+ )+ if not success:+ return FileDownloadResult(False, "CDN download/decrypt failed")++ # Enforce max_bytes after download if specified+ if max_bytes is not None:+ dest = Path(target_path)+ if dest.exists() and dest.stat().st_size > max_bytes:+ dest.unlink(missing_ok=True)+ return FileDownloadResult(+ False,+ f"File exceeds max_bytes ({max_bytes})",+ )++ return FileDownloadResult(True)++ async def download_file(+ self,+ file_info: Dict[str, Any],+ max_bytes: Optional[int] = None,+ timeout_seconds: int = 30,+ ) -> Optional[bytes]:+ """Download a CDN file into memory."""+ import tempfile++ with tempfile.NamedTemporaryFile(delete=False) as tmp:+ tmp_path = tmp.name++ try:+ result = await self.download_file_to_path(+ file_info,+ tmp_path,+ max_bytes=max_bytes,+ timeout_seconds=timeout_seconds,+ )+ if not result.success:+ return None+ return Path(tmp_path).read_bytes()+ finally:+ try:+ os.unlink(tmp_path)+ except OSError:+ pass++ # ------------------------------------------------------------------+ # DM convenience+ # ------------------------------------------------------------------++ async def send_dm(self, user_id: str, text: str, **kwargs: Any) -> Optional[str]:+ """Send a direct message by user ID.++ For WeChat, every conversation is already a DM, so we just need a+ cached context_token for the user.+ """+ context_token = self._context_tokens.get(user_id, "")+ if not context_token:+ logger.warning(+ "No context_token cached for user %s; cannot send DM",+ user_id,+ )+ return None++ context = MessageContext(+ user_id=user_id,+ channel_id=user_id,+ thread_id=None,+ message_id=None,+ platform_specific={"is_dm": True, "context_token": context_token},+ )+ try:+ return await self.send_message(context, text)+ except Exception as exc:+ logger.error("send_dm failed for user %s: %s", user_id, exc)+ return None++ # ------------------------------------------------------------------+ # Run / shutdown+ # ------------------------------------------------------------------++ def run(self) -> None:+ """Start the WeChat bot: validate config, run the async poll loop."""+ if not self.config.bot_token:+ logger.warning(+ "WeChat bot_token is not configured. "+ "The bot will idle until a token is set via the Web UI QR login. "+ "Access the setup wizard to complete WeChat configuration."+ )++ logger.info("Starting WeChat bot via iLink protocol...")++ async def _start() -> None:+ self._loop = asyncio.get_running_loop()+ self._stop_event = asyncio.Event()++ # 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)++ 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++ # Load persisted sync buffer+ self._load_sync_buf()++ # 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",+ )++ # Start poll loop as a background task+ self._poll_task = asyncio.create_task(self._poll_loop())++ logger.info("WeChat bot started, entering poll loop")++ # Block until stop is signalled+ await self._stop_event.wait()++ # 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")++ try:+ asyncio.run(_start())+ except KeyboardInterrupt:+ logger.info("WeChat bot shutting down (keyboard interrupt)...")++ def stop(self) -> None:+ """Signal the bot to stop."""+ if self._stop_event is None:+ return+ if self._loop and self._loop.is_running():+ self._loop.call_soon_threadsafe(self._stop_event.set)+ else:+ self._stop_event.set()++ async def shutdown(self) -> None:+ """Best-effort async shutdown for platform resources."""+ if self._stop_event is not None:+ self._stop_event.set()+ # Persist sync buffer so we don't re-process old messages on restart+ self._save_sync_buf()++ # ------------------------------------------------------------------+ # Long-poll loop+ # ------------------------------------------------------------------++ async def _poll_loop(self) -> None:+ """Main message receiving loop via HTTP long-poll."""+ consecutive_failures = 0++ while not self._stop_event.is_set():+ try:+ resp = await wechat_api.get_updates(+ self.config.base_url,+ self.config.bot_token,+ self._sync_buf,+ timeout_ms=_POLL_TIMEOUT_MS,+ proxy=self.config.proxy_url,+ )++ ret = resp.get("ret", 0)+ if ret != 0:+ errcode = resp.get("errcode", ret)+ logger.warning(+ "getUpdates error: ret=%s errcode=%s msg=%s",+ ret,+ errcode,+ resp.get("msg", ""),+ )++ # Handle session expired+ if errcode == _SESSION_EXPIRED_ERRCODE:+ logger.error(+ "WeChat session expired (errcode %s); re-authentication required",+ errcode,+ )+ self._auth_manager.is_logged_in = False++ consecutive_failures += 1+ if consecutive_failures >= _MAX_CONSECUTIVE_FAILURES:+ logger.warning(+ "Multiple consecutive poll failures (%d); backing off to %ds",+ consecutive_failures,+ _LONG_RETRY_SECONDS,+ )+ await asyncio.sleep(_LONG_RETRY_SECONDS)+ consecutive_failures = 0+ else:+ await asyncio.sleep(_SHORT_RETRY_SECONDS)+ continue++ # Success path+ consecutive_failures = 0++ # Update sync cursor+ new_buf = resp.get("get_updates_buf", "")+ if new_buf:+ self._sync_buf = new_buf+ self._save_sync_buf()++ # Process messages+ msgs = resp.get("msgs", [])+ if msgs:+ logger.info("Received %d message(s)", len(msgs))+ for msg in msgs:+ try:+ await self._process_inbound_message(msg)+ except Exception as msg_exc:+ logger.error(+ "Failed to process message %s: %s",+ msg.get("message_id", "?"),+ msg_exc,+ exc_info=True,+ )++ except asyncio.CancelledError:+ break+ except Exception as exc:+ logger.error("Poll loop error: %s", exc, exc_info=True)+ consecutive_failures += 1+ delay = (+ _LONG_RETRY_SECONDS if consecutive_failures >= _MAX_CONSECUTIVE_FAILURES else _SHORT_RETRY_SECONDS+ )+ await asyncio.sleep(delay)+ if consecutive_failures >= _MAX_CONSECUTIVE_FAILURES:+ consecutive_failures = 0++ # ------------------------------------------------------------------+ # Inbound message processing+ # ------------------------------------------------------------------++ async def _process_inbound_message(self, msg: dict) -> None:+ """Convert an iLink message to MessageContext and dispatch."""+ message_id = str(msg.get("message_id", ""))++ # Dedup+ if message_id and not self._mark_message_seen(message_id):+ return++ from_user = msg.get("from_user_id", "")+ if not from_user:+ logger.debug("Skipping message with empty from_user_id")+ return++ context_token = msg.get("context_token", "")+ logger.info(+ "Processing inbound message: id=%s from=%s context_token=%s items=%d",+ message_id,+ from_user,+ context_token[:16] + "..." if len(context_token) > 16 else context_token,+ len(msg.get("item_list", [])),+ )++ # Cache context_token for replies+ if context_token:+ self._context_tokens[from_user] = context_token++ # Extract text from item_list+ text = self._extract_text(msg)++ # Build MessageContext+ context = MessageContext(+ user_id=from_user,+ channel_id=from_user, # WeChat DM: channel == user+ thread_id=None, # No threads in WeChat+ message_id=message_id,+ platform_specific={+ "message": msg,+ "is_dm": True, # Always DM for personal messaging+ "context_token": context_token,+ },+ files=[],+ )++ # Handle media attachments+ await self._process_media_items(msg, context)++ # Authorization check+ auth_result = self.check_authorization(+ user_id=from_user,+ channel_id=from_user,+ is_dm=True,+ text=text,+ settings_manager=self.settings_manager,+ )+ if auth_result is not None and auth_result is not True:+ # auth_result is a denial reason string+ denial_text = self.build_auth_denial_text(+ auth_result,+ channel_id=from_user,+ )+ if denial_text:+ try:+ await self.send_message(context, denial_text)+ except Exception as exc:+ logger.error("Failed to send auth denial: %s", exc)+ return++ # Try slash command dispatch first+ allow_plain_bind = self.should_allow_plain_bind(+ user_id=from_user,+ is_dm=True,+ settings_manager=self.settings_manager,+ )+ if await self.dispatch_text_command(+ context,+ text,+ allow_plain_bind=allow_plain_bind,+ ):+ return++ # Dispatch to message handler+ if self.on_message_callback:+ try:+ await self.on_message_callback(context, text)+ except Exception as exc:+ logger.error(+ "Message callback error for user %s: %s",+ from_user,+ exc,+ exc_info=True,+ )++ # ------------------------------------------------------------------+ # Text / media extraction+ # ------------------------------------------------------------------++ @staticmethod+ def _extract_text(msg: dict) -> str:+ """Extract text content from iLink message item_list.++ The ``type`` field is an integer: 1=TEXT, 2=IMAGE, 3=VOICE, 4=FILE, 5=VIDEO.+ """+ text_parts: List[str] = []+ for item in msg.get("item_list", []):+ item_type = item.get("type", 0)+ # type 1 = TEXT+ if item_type == 1 or item_type in ("TEXT", "text"):+ content = item.get("content", "")+ if content:+ text_parts.append(content)++ return " ".join(text_parts).strip()++ async def _process_media_items(+ self,+ msg: dict,+ context: MessageContext,+ ) -> None:+ """Populate context.files from media items in the message."""+ if context.files is None:+ context.files = []++ for item in msg.get("item_list", []):+ item_type = item.get("type", 0)+ # 2=IMAGE, 3=VOICE, 4=FILE, 5=VIDEO+ type_name_map = {2: "IMAGE", 3: "VOICE", 4: "FILE", 5: "VIDEO"}+ type_name = type_name_map.get(item_type)+ if type_name is None:+ continue++ cdn_info = item.get("cdn", {})+ file_name = item.get("content", "") or item.get("file_name", "")++ mime_map = {+ "IMAGE": "image/jpeg",+ "FILE": "application/octet-stream",+ "VIDEO": "video/mp4",+ "VOICE": "audio/amr",+ }+ mimetype = mime_map.get(type_name, "application/octet-stream")++ attachment = FileAttachment(+ name=file_name or f"{type_name.lower()}_attachment",+ mimetype=mimetype,+ url=cdn_info.get("url", ""),+ size=cdn_info.get("file_size"),+ )+ # Store CDN info for later download+ attachment.__dict__["cdn_info"] = cdn_info+ context.files.append(attachment)++ # ------------------------------------------------------------------+ # Deduplication+ # ------------------------------------------------------------------++ def _mark_message_seen(self, message_id: str) -> bool:+ """Return True if this is a new message; False if already seen."""+ self._maybe_clean_dedup_set()++ if message_id in self._seen_message_ids:+ logger.debug("Duplicate message ignored: %s", message_id)+ return False++ self._seen_message_ids.add(message_id)+ return True++ def _maybe_clean_dedup_set(self) -> None:+ """Periodically trim the dedup set to avoid unbounded growth."""+ now = time.monotonic()+ if now - self._last_dedup_clean < _DEDUP_CLEAN_INTERVAL_SECONDS:+ return++ self._last_dedup_clean = now+ if len(self._seen_message_ids) > _DEDUP_SET_MAX:+ # Keep the most recent half by clearing the whole set.+ # This is a simple strategy; messages arriving during the clean+ # window are unlikely to be duplicates.+ excess = len(self._seen_message_ids) - _DEDUP_SET_MAX // 2+ # Sets don't have ordering, so just discard arbitrary elements+ to_remove = list(self._seen_message_ids)[:excess]+ for mid in to_remove:+ self._seen_message_ids.discard(mid)+ logger.debug(+ "Dedup set trimmed: removed %d, remaining %d",+ len(to_remove),+ len(self._seen_message_ids),+ )++ # ------------------------------------------------------------------+ # Sync buffer persistence+ # ------------------------------------------------------------------++ def _get_sync_buf_path(self) -> Path:+ """Return the path for persisting the getUpdates cursor."""+ state_dir = get_state_dir()+ state_dir.mkdir(parents=True, exist_ok=True)+ return state_dir / "wechat_sync_buf.json"++ def _load_sync_buf(self) -> None:+ """Load the persisted sync buffer from disk."""+ path = self._get_sync_buf_path()+ if not path.is_file():+ return+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ self._sync_buf = data.get("sync_buf", "")+ if self._sync_buf:+ logger.info("Loaded persisted sync buffer (%d chars)", len(self._sync_buf))+ except Exception as exc:+ logger.warning("Failed to load sync buffer: %s", exc)++ def _save_sync_buf(self) -> None:+ """Persist the current sync buffer to disk."""+ if not self._sync_buf:+ return+ try:+ path = self._get_sync_buf_path()+ path.write_text(+ json.dumps({"sync_buf": self._sync_buf}, ensure_ascii=False),+ encoding="utf-8",+ )+ except Exception as exc:+ logger.warning("Failed to save sync buffer: %s", exc)++ # ------------------------------------------------------------------+ # Context token helpers+ # ------------------------------------------------------------------++ def _get_context_token(self, context: MessageContext) -> str:+ """Resolve the context_token for a given message context.++ Tries platform_specific first, then falls back to the cached map.+ """+ ps = context.platform_specific or {}+ token = ps.get("context_token", "")+ if token:+ return token+ return self._context_tokens.get(context.user_id, "")++ # ------------------------------------------------------------------+ # Reactions (unsupported)+ # ------------------------------------------------------------------++ async def add_reaction(+ self,+ context: MessageContext,+ message_id: str,+ emoji: str,+ ) -> bool:+ """WeChat personal messaging does not support reactions."""+ return False++ async def remove_reaction(+ self,+ context: MessageContext,+ message_id: str,+ emoji: str,+ ) -> bool:+ """WeChat personal messaging does not support reactions."""+ return Falsediff --git a/modules/im/wechat_api.py b/modules/im/wechat_api.pynew file mode 100644index 000000000..353d22ade--- /dev/null+++ b/modules/im/wechat_api.py@@ -0,0 +1,412 @@+"""WeChat iLink bot HTTP API client.++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.++Ported from the TypeScript reference implementation.+"""++import base64+import logging+import struct+import uuid+from typing import Any, Dict, List, Optional+from urllib.parse import quote, urljoin++import aiohttp++logger = logging.getLogger(__name__)++# ---------------------------------------------------------------------------+# Constants+# ---------------------------------------------------------------------------++# Message types (proto: MessageType)+MESSAGE_TYPE_NONE = 0+MESSAGE_TYPE_USER = 1+MESSAGE_TYPE_BOT = 2++# Message item types (proto: MessageItemType)+ITEM_NONE = 0+ITEM_TEXT = 1+ITEM_IMAGE = 2+ITEM_VOICE = 3+ITEM_FILE = 4+ITEM_VIDEO = 5++# Message states (proto: MessageState)+STATE_NEW = 0+STATE_GENERATING = 1+STATE_FINISH = 2++# Typing status+TYPING_START = 1+TYPING_CANCEL = 2++# Upload media types (proto: UploadMediaType)+UPLOAD_MEDIA_IMAGE = 1+UPLOAD_MEDIA_VIDEO = 2+UPLOAD_MEDIA_FILE = 3+UPLOAD_MEDIA_VOICE = 4++# Timeouts (milliseconds)+DEFAULT_LONG_POLL_TIMEOUT_MS = 35_000+DEFAULT_API_TIMEOUT_MS = 15_000+DEFAULT_CONFIG_TIMEOUT_MS = 10_000++# Channel version reported in base_info+CHANNEL_VERSION = "vibe-remote"+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _random_wechat_uin() -> str:+ """Generate ``X-WECHAT-UIN`` header: random uint32 -> decimal string -> base64."""+ import os++ raw = os.urandom(4)+ uint32 = struct.unpack("!I", raw)[0]+ return base64.b64encode(str(uint32).encode("utf-8")).decode("ascii")+++def _ensure_trailing_slash(url: str) -> str:+ return url if url.endswith("/") else f"{url}/"+++def _build_base_info() -> Dict[str, str]:+ """Build the ``base_info`` payload included in every API request."""+ return {"channel_version": CHANNEL_VERSION}+++def _build_headers(token: Optional[str] = None, body_bytes: Optional[bytes] = None) -> Dict[str, str]:+ """Build common headers for iLink bot API requests."""+ headers: Dict[str, str] = {+ "Content-Type": "application/json",+ "AuthorizationType": "ilink_bot_token",+ "X-WECHAT-UIN": _random_wechat_uin(),+ }+ 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+++def _redact_token(token: Optional[str]) -> str:+ """Redact token for safe logging."""+ if not token:+ return "(none)"+ return f"{token[:8]}...{token[-4:]}" if len(token) > 16 else "***"+++# ---------------------------------------------------------------------------+# Core fetch wrapper+# ---------------------------------------------------------------------------+++async def _api_fetch(+ base_url: str,+ endpoint: str,+ body: dict,+ token: Optional[str] = None,+ timeout_ms: int = DEFAULT_API_TIMEOUT_MS,+) -> dict:+ """Common POST wrapper: POST JSON to a Weixin API endpoint.++ Returns the parsed JSON response dict.+ Raises ``aiohttp.ClientError`` or ``RuntimeError`` on HTTP error.+ """+ import json++ url = urljoin(_ensure_trailing_slash(base_url), endpoint)+ body_with_base = {**body, "base_info": _build_base_info()}+ body_str = json.dumps(body_with_base)+ body_bytes = body_str.encode("utf-8")+ headers = _build_headers(token=token, body_bytes=body_bytes)++ timeout = aiohttp.ClientTimeout(total=timeout_ms / 1000.0)+ logger.debug("POST %s body=%s", url, body_str[:200])++ async with aiohttp.ClientSession(timeout=timeout) as session:+ async with session.post(url, data=body_bytes, headers=headers) as resp:+ raw_text = await resp.text()+ logger.debug(+ "%s status=%d raw=%s",+ endpoint,+ resp.status,+ raw_text[:300] if raw_text else "(empty)",+ )+ if not resp.ok:+ raise RuntimeError(f"{endpoint} {resp.status}: {raw_text}")+ return json.loads(raw_text)+++# ---------------------------------------------------------------------------+# Public API methods+# ---------------------------------------------------------------------------+++async def get_updates(+ base_url: str,+ token: str,+ get_updates_buf: str = "",+ timeout_ms: int = DEFAULT_LONG_POLL_TIMEOUT_MS,+) -> dict:+ """Long-poll ``getUpdates``.++ Server holds the request until new messages arrive or the timeout elapses.+ On client-side timeout (no server response within *timeout_ms*), returns an+ empty response with ``ret=0`` so the caller can simply retry.++ Returns:+ Parsed JSON dict with keys ``ret``, ``msgs``, ``get_updates_buf``, etc.+ """+ import json++ url = urljoin(_ensure_trailing_slash(base_url), "ilink/bot/getupdates")+ body_dict = {+ "get_updates_buf": get_updates_buf,+ "base_info": _build_base_info(),+ }+ body_str = json.dumps(body_dict)+ body_bytes = body_str.encode("utf-8")+ headers = _build_headers(token=token, body_bytes=body_bytes)++ timeout = aiohttp.ClientTimeout(total=timeout_ms / 1000.0)+ logger.info(+ "get_updates: POST %s token=%s timeout=%dms buf_len=%d",+ url,+ _redact_token(token),+ timeout_ms,+ len(get_updates_buf),+ )++ try:+ async with aiohttp.ClientSession(timeout=timeout) as session:+ async with session.post(url, data=body_bytes, headers=headers) as resp:+ raw_text = await resp.text()+ logger.info(+ "getUpdates: status=%d body_len=%d raw=%s",+ resp.status,+ len(raw_text) if raw_text else 0,+ raw_text[:300] if raw_text else "(empty)",+ )+ if not resp.ok:+ raise RuntimeError(f"getUpdates {resp.status}: {raw_text}")+ return json.loads(raw_text)+ except (aiohttp.ServerTimeoutError, TimeoutError):+ logger.debug(+ "getUpdates: client-side timeout after %dms, returning empty response",+ timeout_ms,+ )+ return {"ret": 0, "msgs": [], "get_updates_buf": get_updates_buf}+++def _generate_client_id() -> str:+ """Generate a unique client ID for message deduplication."""+ return f"vibe-remote-{uuid.uuid4().hex[:16]}"+++async def send_message(+ base_url: str,+ token: str,+ to_user_id: str,+ context_token: str,+ item_list: List[Dict[str, Any]],+) -> dict:+ """Send a single message downstream.++ Wraps the items in a ``WeixinMessage`` with ``message_type=BOT``,+ ``message_state=FINISH``.++ Args:+ to_user_id: Recipient user ID.+ context_token: Conversation context token.+ item_list: List of message item dicts. Each item must use the+ iLink protobuf format, e.g.+ ``{"type": 1, "text_item": {"text": "hello"}}``.++ Returns:+ Parsed JSON response dict.+ """+ msg = {+ "msg": {+ "from_user_id": "",+ "to_user_id": to_user_id,+ "client_id": _generate_client_id(),+ "context_token": context_token,+ "message_type": MESSAGE_TYPE_BOT,+ "message_state": STATE_FINISH,+ "item_list": item_list,+ }+ }+ return await _api_fetch(+ base_url,+ "ilink/bot/sendmessage",+ msg,+ token=token,+ timeout_ms=DEFAULT_API_TIMEOUT_MS,+ )+++async def get_upload_url(+ base_url: str,+ token: str,+ params: Dict[str, Any],+) -> dict:+ """Get a pre-signed CDN upload URL for a file.++ *params* should contain fields such as ``filekey``, ``media_type``,+ ``to_user_id``, ``rawsize``, ``rawfilemd5``, ``filesize``, ``aeskey``,+ and optionally thumbnail fields.++ Returns:+ Parsed JSON dict with ``upload_param`` (and possibly ``thumb_upload_param``).+ """+ return await _api_fetch(+ base_url,+ "ilink/bot/getuploadurl",+ params,+ token=token,+ timeout_ms=DEFAULT_API_TIMEOUT_MS,+ )+++async def get_config(+ base_url: str,+ token: str,+ ilink_user_id: str,+ context_token: Optional[str] = None,+) -> dict:+ """Fetch bot config (includes ``typing_ticket``) for a given user.++ Returns:+ Parsed JSON dict with ``ret``, ``typing_ticket``, etc.+ """+ body: Dict[str, Any] = {"ilink_user_id": ilink_user_id}+ if context_token is not None:+ body["context_token"] = context_token+ return await _api_fetch(+ base_url,+ "ilink/bot/getconfig",+ body,+ token=token,+ timeout_ms=DEFAULT_CONFIG_TIMEOUT_MS,+ )+++async def send_typing(+ base_url: str,+ token: str,+ ilink_user_id: str,+ typing_ticket: str,+ status: int = TYPING_START,+) -> dict:+ """Send a typing indicator to a user.++ Args:+ status: ``TYPING_START`` (1) or ``TYPING_CANCEL`` (2).++ Returns:+ Parsed JSON response dict.+ """+ body = {+ "ilink_user_id": ilink_user_id,+ "typing_ticket": typing_ticket,+ "status": status,+ }+ return await _api_fetch(+ base_url,+ "ilink/bot/sendtyping",+ body,+ token=token,+ timeout_ms=DEFAULT_CONFIG_TIMEOUT_MS,+ )+++# ---------------------------------------------------------------------------+# Auth / QR code endpoints (GET requests, no token)+# ---------------------------------------------------------------------------+++async def get_bot_qrcode(+ base_url: str,+ bot_type: str = "3",+) -> dict:+ """Fetch a new QR code for bot login.++ GET ``ilink/bot/get_bot_qrcode?bot_type={bot_type}``++ Returns:+ Dict with ``qrcode`` (string token) and ``qrcode_img_content`` (URL/data).+ """+ url = urljoin(+ _ensure_trailing_slash(base_url),+ f"ilink/bot/get_bot_qrcode?bot_type={quote(bot_type)}",+ )+ logger.info("Fetching QR code from: %s", url)++ timeout = aiohttp.ClientTimeout(total=DEFAULT_API_TIMEOUT_MS / 1000.0)+ async with aiohttp.ClientSession(timeout=timeout) as session:+ async with session.get(url) as resp:+ if not resp.ok:+ body = await resp.text()+ logger.error(+ "QR code fetch failed: %d %s body=%s",+ resp.status,+ resp.reason,+ body[:200],+ )+ raise RuntimeError(f"Failed to fetch QR code: {resp.status} {resp.reason}")+ # iLink API may return application/octet-stream instead of application/json+ return await resp.json(content_type=None)+++async def get_qrcode_status(+ base_url: str,+ qrcode: str,+) -> 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"}``.++ Returns:+ Dict with ``status`` (``"wait"`` / ``"scaned"`` / ``"confirmed"`` / ``"expired"``),+ and on confirmation: ``bot_token``, ``ilink_bot_id``, ``baseurl``, ``ilink_user_id``.+ """+ import json++ url = urljoin(+ _ensure_trailing_slash(base_url),+ f"ilink/bot/get_qrcode_status?qrcode={quote(qrcode)}",+ )+ headers = {"iLink-App-ClientVersion": "1"}++ timeout = aiohttp.ClientTimeout(total=DEFAULT_LONG_POLL_TIMEOUT_MS / 1000.0)+ logger.debug("Long-poll QR status from: %s", url)++ try:+ async with aiohttp.ClientSession(timeout=timeout) as session:+ async with session.get(url, headers=headers) as resp:+ raw_text = await resp.text()+ logger.debug(+ "pollQRStatus: HTTP %d body=%s",+ resp.status,+ raw_text[:200],+ )+ if not resp.ok:+ raise RuntimeError(f"Failed to poll QR status: {resp.status} {resp.reason}")+ return json.loads(raw_text)+ except (aiohttp.ServerTimeoutError, TimeoutError):+ logger.debug(+ "pollQRStatus: client-side timeout after %dms, returning wait",+ DEFAULT_LONG_POLL_TIMEOUT_MS,+ )+ return {"status": "wait"}diff --git a/modules/im/wechat_auth.py b/modules/im/wechat_auth.pynew file mode 100644index 000000000..a2f50a7b5--- /dev/null+++ b/modules/im/wechat_auth.py@@ -0,0 +1,401 @@+"""WeChat QR code login flow for the vibe-remote setup wizard and CLI.++Ported from TypeScript: weixin-plugin-inspect/package/src/auth/login-qr.ts++Manages active login sessions in-memory (dict keyed by session_key).+Supports concurrent login sessions (for Web UI).+Auto-cleans expired sessions (5 min TTL).+"""++import asyncio+import logging+import time+import uuid+from dataclasses import dataclass, field+from typing import Dict, Optional++import aiohttp++logger = logging.getLogger(__name__)++# ---------------------------------------------------------------------------+# Short poll timeout for Web UI: the UI polls every 2s, so each individual+# status check should return quickly. The iLink server itself long-polls+# for ~30s, but we cut that short on the client side so the Flask+# _run_async wrapper (10s timeout) never kills us mid-request.+QR_POLL_TIMEOUT_S = 3+++# ---------------------------------------------------------------------------+# Data model+# ---------------------------------------------------------------------------+@dataclass+class WeChatLoginSession:+ """Tracks one QR code login attempt."""++ session_key: str+ qrcode: str = "" # opaque QR token from server+ qrcode_url: str = "" # URL to render as QR image+ started_at: float = field(default_factory=time.time)+ status: str = "wait" # "wait" | "scaned" | "confirmed" | "expired"+ 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+++# ---------------------------------------------------------------------------+# Low-level API helpers+# ---------------------------------------------------------------------------+async def get_bot_qrcode(+ base_url: str,+ bot_type: str,+ *,+ timeout: float = 30,+) -> dict:+ """Fetch a new QR code from the iLink server.++ GET {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)+++async def get_qrcode_status(+ base_url: str,+ qrcode: str,+ *,+ timeout: float = QR_POLL_TIMEOUT_S,+) -> dict:+ """Long-poll the QR code scan status.++ GET {base_url}/ilink/bot/get_qrcode_status?qrcode={qrcode}++ Returns:+ dict with at least ``status`` ("wait" | "scaned" | "confirmed" | "expired").+ 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)+ except asyncio.TimeoutError:+ logger.debug(+ "get_qrcode_status: client-side timeout after %ss, returning wait",+ timeout,+ )+ return {"status": "wait"}+++# ---------------------------------------------------------------------------+# Auth manager+# ---------------------------------------------------------------------------+class WeChatAuthManager:+ """Manages QR code login sessions."""++ DEFAULT_BASE_URL = "https://ilinkai.weixin.qq.com"+ BOT_TYPE = "3"+ SESSION_TTL = 300 # 5 minutes+ MAX_QR_REFRESH = 3++ def __init__(self) -> None:+ self._sessions: Dict[str, WeChatLoginSession] = {}++ # -- helpers ----------------------------------------------------------++ def _is_session_fresh(self, session: WeChatLoginSession) -> bool:+ return (time.time() - session.started_at) < self.SESSION_TTL++ def cleanup_expired(self) -> None:+ """Remove sessions older than TTL."""+ expired_keys = [key for key, sess in self._sessions.items() if not self._is_session_fresh(sess)]+ for key in expired_keys:+ logger.debug("Cleaning up expired session: %s", key)+ del self._sessions[key]++ def get_session(self, session_key: str) -> Optional[WeChatLoginSession]:+ """Get current session state (for UI polling)."""+ self.cleanup_expired()+ return self._sessions.get(session_key)++ # -- public API -------------------------------------------------------++ async def start_login(+ self,+ session_key: Optional[str] = None,+ base_url: Optional[str] = None,+ ) -> dict:+ """Start a new QR code login.++ Returns:+ dict with ``session_key``, ``qrcode_url`` (may be empty on error),+ and ``message``.+ """+ session_key = session_key or str(uuid.uuid4())+ base_url = base_url or self.DEFAULT_BASE_URL++ self.cleanup_expired()++ # 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:+ return {+ "session_key": session_key,+ "qrcode_url": existing.qrcode_url,+ "message": "QR code is ready. Please scan with WeChat.",+ }++ if not base_url:+ return {+ "session_key": session_key,+ "qrcode_url": "",+ "message": "No base URL configured. Please set the WeChat base URL before logging in.",+ }++ try:+ logger.info("Starting WeChat login with bot_type=%s", self.BOT_TYPE)+ qr_response = await get_bot_qrcode(base_url, self.BOT_TYPE)+ qrcode = qr_response.get("qrcode", "")+ qrcode_url = qr_response.get("qrcode_img_content", "")++ logger.info(+ "QR code received, qrcode=%s...%s img_url_len=%d",+ qrcode[:8] if len(qrcode) > 8 else qrcode,+ qrcode[-4:] if len(qrcode) > 4 else "",+ len(qrcode_url),+ )++ session = WeChatLoginSession(+ session_key=session_key,+ qrcode=qrcode,+ qrcode_url=qrcode_url,+ started_at=time.time(),+ status="wait",+ )+ self._sessions[session_key] = session++ return {+ "session_key": session_key,+ "qrcode_url": qrcode_url,+ "message": "Scan the QR code with WeChat to connect.",+ }+ except Exception as exc:+ logger.error("Failed to start WeChat login: %s", exc)+ return {+ "session_key": session_key,+ "qrcode_url": "",+ "message": f"Failed to start login: {exc}",+ }++ async def poll_status(self, session_key: str) -> dict:+ """Poll login status for a single cycle.++ Returns:+ dict with ``status``, ``message``, and on success also+ ``bot_token``, ``bot_id``, ``base_url``, ``user_id``.+ """+ session = self._sessions.get(session_key)+ if session is None:+ return {+ "status": "error",+ "message": "No active login session. Please start a new login.",+ }++ if not self._is_session_fresh(session):+ del self._sessions[session_key]+ return {+ "status": "expired",+ "message": "QR code has expired. Please start a new login.",+ }++ base_url = session.base_url or self.DEFAULT_BASE_URL++ try:+ status_resp = await get_qrcode_status(base_url, session.qrcode)+ except Exception as exc:+ # Don't delete session on transient errors (timeouts, network blips).+ # The UI will retry on the next poll cycle.+ logger.warning("Transient error polling QR status (session kept): %s", exc)+ return {+ "status": "wait",+ "message": "Waiting for QR code scan...",+ }++ status = status_resp.get("status", "wait")+ session.status = status+ logger.debug(+ "poll_status: session=%s status=%s has_bot_token=%s has_bot_id=%s",+ session_key,+ status,+ bool(status_resp.get("bot_token")),+ bool(status_resp.get("ilink_bot_id")),+ )++ if status == "wait":+ return {"status": "wait", "message": "Waiting for QR code scan..."}++ if status == "scaned":+ return {"status": "scaned", "message": "QR code scanned. Please confirm in WeChat."}++ if status == "expired":+ session.qr_refresh_count += 1+ if session.qr_refresh_count > self.MAX_QR_REFRESH:+ logger.warning(+ "QR expired %d times, giving up session=%s",+ self.MAX_QR_REFRESH,+ session_key,+ )+ del self._sessions[session_key]+ return {+ "status": "expired",+ "message": "Login timed out: QR code expired multiple times. Please restart the login flow.",+ }++ logger.info(+ "QR expired, refreshing (%d/%d) session=%s",+ session.qr_refresh_count,+ self.MAX_QR_REFRESH,+ 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."+ ),+ }+ except Exception as exc:+ logger.error("Failed to refresh QR code: %s", exc)+ del self._sessions[session_key]+ return {+ "status": "error",+ "message": f"Failed to refresh QR code: {exc}",+ }++ if status == "confirmed":+ bot_id = status_resp.get("ilink_bot_id")+ if not bot_id:+ del self._sessions[session_key]+ logger.error("Login confirmed but ilink_bot_id missing from response")+ return {+ "status": "error",+ "message": "Login failed: server did not return ilink_bot_id.",+ }++ bot_token = status_resp.get("bot_token")+ resp_base_url = status_resp.get("baseurl")+ user_id = status_resp.get("ilink_user_id")++ # Store on session before removing+ session.bot_token = bot_token+ session.bot_id = bot_id+ session.base_url = resp_base_url+ session.user_id = user_id+ session.status = "confirmed"++ del self._sessions[session_key]++ logger.info(+ "Login confirmed! bot_id=%s user_id=%s...",+ bot_id,+ (user_id[:8] + "...") if user_id and len(user_id) > 8 else user_id,+ )+ return {+ "status": "confirmed",+ "bot_token": bot_token,+ "bot_id": bot_id,+ "base_url": resp_base_url,+ "user_id": user_id,+ "message": "Successfully connected to WeChat!",+ }++ # Unknown status fallback+ return {"status": status, "message": f"Unknown status: {status}"}++ async def wait_for_login(+ self,+ session_key: str,+ timeout_s: int = 480,+ ) -> dict:+ """Block until login completes or times out. Intended for CLI use.++ Returns:+ dict with ``status``, ``message``, and credentials on success.+ """+ deadline = time.time() + max(timeout_s, 1)++ while time.time() < deadline:+ result = await self.poll_status(session_key)+ status = result.get("status")++ if status in ("confirmed", "error"):+ return result++ if status == "expired" and "restart" in result.get("message", "").lower():+ # Max refreshes exhausted+ return result++ # For "wait", "scaned", "refreshed" — keep polling+ await asyncio.sleep(1)++ # Timed out+ if session_key in self._sessions:+ del self._sessions[session_key]+ logger.warning(+ "wait_for_login: timed out after %ds session=%s",+ timeout_s,+ session_key,+ )+ return {+ "status": "expired",+ "message": "Login timed out. Please try again.",+ }diff --git a/modules/im/wechat_cdn.py b/modules/im/wechat_cdn.pynew file mode 100644index 000000000..afe4a4c9e--- /dev/null+++ b/modules/im/wechat_cdn.py@@ -0,0 +1,450 @@+"""WeChat iLink CDN encryption and media upload/download.++Handles AES-128-ECB encryption for CDN file transfers, including:+- Encrypting files before upload to the WeChat CDN+- Decrypting files downloaded from the CDN+- High-level upload workflows for images, files, and videos++Ported from the TypeScript reference implementation.+"""++import base64+import hashlib+import logging+import os+from pathlib import Path+from typing import Any, Dict, Optional+from urllib.parse import quote++import aiohttp+from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes+from cryptography.hazmat.primitives.padding import PKCS7++from modules.im.wechat_api import (+ UPLOAD_MEDIA_FILE,+ UPLOAD_MEDIA_IMAGE,+ UPLOAD_MEDIA_VIDEO,+ get_upload_url,+)++logger = logging.getLogger(__name__)++# AES-128 block size in bits (for PKCS7 padding)+_AES_BLOCK_BITS = 128+# AES-128 block size in bytes+_AES_BLOCK_BYTES = 16+# Maximum retry attempts for CDN upload+_UPLOAD_MAX_RETRIES = 3+++# ---------------------------------------------------------------------------+# AES-128-ECB primitives+# ---------------------------------------------------------------------------+++def aes_ecb_encrypt(plaintext: bytes, key: bytes) -> bytes:+ """Encrypt *plaintext* with AES-128-ECB and PKCS7 padding.++ Args:+ plaintext: Data to encrypt.+ key: 16-byte AES key.++ Returns:+ Ciphertext bytes (always a multiple of 16 bytes).+ """+ padder = PKCS7(_AES_BLOCK_BITS).padder()+ padded = padder.update(plaintext) + padder.finalize()+ cipher = Cipher(algorithms.AES(key), modes.ECB())+ encryptor = cipher.encryptor()+ return encryptor.update(padded) + encryptor.finalize()+++def aes_ecb_decrypt(ciphertext: bytes, key: bytes) -> bytes:+ """Decrypt *ciphertext* with AES-128-ECB and remove PKCS7 padding.++ Args:+ ciphertext: Encrypted data (must be a multiple of 16 bytes).+ key: 16-byte AES key.++ Returns:+ Decrypted plaintext bytes.+ """+ cipher = Cipher(algorithms.AES(key), modes.ECB())+ decryptor = cipher.decryptor()+ padded = decryptor.update(ciphertext) + decryptor.finalize()+ unpadder = PKCS7(_AES_BLOCK_BITS).unpadder()+ return unpadder.update(padded) + unpadder.finalize()+++def aes_ecb_padded_size(plaintext_size: int) -> int:+ """Compute AES-128-ECB ciphertext size after PKCS7 padding.++ PKCS7 always adds at least 1 byte of padding, so the result is+ ``ceil((plaintext_size + 1) / 16) * 16``.+ """+ return ((plaintext_size + 1 + _AES_BLOCK_BYTES - 1) // _AES_BLOCK_BYTES) * _AES_BLOCK_BYTES+++# ---------------------------------------------------------------------------+# AES key parsing+# ---------------------------------------------------------------------------+++def parse_aes_key(aes_key_b64: str) -> bytes:+ """Parse a CDNMedia ``aes_key`` field into a raw 16-byte AES key.++ Two encodings are seen in the wild:++ - ``base64(raw 16 bytes)`` -- images (aes_key from media field)+ - ``base64(hex string of 16 bytes)`` -- file / voice / video++ In the second case, base64-decoding yields 32 ASCII hex chars which must+ then be parsed as hex to recover the actual 16-byte key.++ Args:+ aes_key_b64: Base64-encoded AES key string from the API.++ Returns:+ Raw 16-byte AES key.++ Raises:+ ValueError: If the decoded key is neither 16 raw bytes nor a 32-char+ hex string.+ """+ decoded = base64.b64decode(aes_key_b64)+ if len(decoded) == _AES_BLOCK_BYTES:+ return decoded+ if len(decoded) == 32:+ try:+ ascii_str = decoded.decode("ascii")+ # Verify it's a valid hex string+ key = bytes.fromhex(ascii_str)+ if len(key) == _AES_BLOCK_BYTES:+ return key+ except (UnicodeDecodeError, ValueError):+ pass+ raise ValueError(+ f"aes_key must decode to 16 raw bytes or 32-char hex string, got {len(decoded)} bytes (base64={aes_key_b64!r})"+ )+++# ---------------------------------------------------------------------------+# CDN URL construction+# ---------------------------------------------------------------------------+++def _build_cdn_upload_url(cdn_base_url: str, upload_param: str, filekey: str) -> str:+ """Build a CDN upload URL from upload_param and filekey."""+ return f"{cdn_base_url}/upload?encrypted_query_param={quote(upload_param)}&filekey={quote(filekey)}"+++def _build_cdn_download_url(cdn_base_url: str, encrypted_query_param: str) -> str:+ """Build a CDN download URL from encrypted_query_param."""+ return f"{cdn_base_url}/download?encrypted_query_param={quote(encrypted_query_param)}"+++# ---------------------------------------------------------------------------+# CDN upload / download+# ---------------------------------------------------------------------------+++async def upload_buffer_to_cdn(+ cdn_base_url: str,+ upload_param: str,+ filekey: str,+ data: bytes,+ aes_key: bytes,+) -> str:+ """Upload a buffer to the WeChat CDN with AES-128-ECB encryption.++ Encrypts *data* then POSTs the ciphertext to the CDN. Retries up to 3+ times on server errors (5xx); client errors (4xx) abort immediately.++ Args:+ cdn_base_url: Base URL of the CDN (e.g. ``https://cdn.example.com``).+ upload_param: Encrypted query param from ``get_upload_url``.+ filekey: File key for the upload.+ data: Raw plaintext bytes to upload.+ aes_key: 16-byte AES key for encryption.++ Returns:+ The ``x-encrypted-param`` response header value (download param).++ Raises:+ RuntimeError: If all upload attempts fail or the response is missing+ the expected header.+ """+ ciphertext = aes_ecb_encrypt(data, aes_key)+ url = _build_cdn_upload_url(cdn_base_url, upload_param, filekey)+ logger.debug("CDN upload: POST url=%s ciphertext_size=%d", url[:80], len(ciphertext))++ download_param: Optional[str] = None+ last_error: Optional[Exception] = None++ timeout = aiohttp.ClientTimeout(total=60)+ async with aiohttp.ClientSession(timeout=timeout) as session:+ for attempt in range(1, _UPLOAD_MAX_RETRIES + 1):+ try:+ async with session.post(+ url,+ data=ciphertext,+ headers={"Content-Type": "application/octet-stream"},+ ) as resp:+ if 400 <= resp.status < 500:+ err_msg = resp.headers.get("x-error-message") or await resp.text()+ logger.error(+ "CDN client error attempt=%d status=%d err=%s",+ attempt,+ resp.status,+ err_msg,+ )+ raise RuntimeError(f"CDN upload client error {resp.status}: {err_msg}")+ if resp.status != 200:+ err_msg = resp.headers.get("x-error-message") or f"status {resp.status}"+ logger.error(+ "CDN server error attempt=%d status=%d err=%s",+ attempt,+ resp.status,+ err_msg,+ )+ raise RuntimeError(f"CDN upload server error: {err_msg}")++ download_param = resp.headers.get("x-encrypted-param")+ if not download_param:+ logger.error(+ "CDN response missing x-encrypted-param header attempt=%d",+ attempt,+ )+ raise RuntimeError("CDN upload response missing x-encrypted-param header")+ logger.debug("CDN upload success attempt=%d", attempt)+ return download_param++ except RuntimeError as e:+ last_error = e+ if "client error" in str(e):+ raise+ if attempt < _UPLOAD_MAX_RETRIES:+ logger.error(+ "CDN upload attempt %d failed, retrying: %s",+ attempt,+ e,+ )+ else:+ logger.error(+ "CDN upload all %d attempts failed: %s",+ _UPLOAD_MAX_RETRIES,+ e,+ )+ except aiohttp.ClientError as e:+ last_error = e+ if attempt < _UPLOAD_MAX_RETRIES:+ logger.error(+ "CDN upload attempt %d network error, retrying: %s",+ attempt,+ e,+ )+ else:+ logger.error(+ "CDN upload all %d attempts failed: %s",+ _UPLOAD_MAX_RETRIES,+ e,+ )++ raise last_error or RuntimeError(f"CDN upload failed after {_UPLOAD_MAX_RETRIES} attempts")+++async def download_and_decrypt(+ cdn_base_url: str,+ encrypted_query_param: str,+ aes_key_b64: str,+) -> bytes:+ """Download and AES-128-ECB decrypt a CDN media file.++ Handles dual key encoding via :func:`parse_aes_key`.++ Args:+ cdn_base_url: Base URL of the CDN.+ encrypted_query_param: Encrypted query param identifying the file.+ aes_key_b64: Base64-encoded AES key (see :func:`parse_aes_key`).++ Returns:+ Decrypted plaintext bytes.++ Raises:+ RuntimeError: On HTTP error.+ ValueError: If the AES key cannot be parsed.+ """+ key = parse_aes_key(aes_key_b64)+ url = _build_cdn_download_url(cdn_base_url, encrypted_query_param)+ logger.debug("CDN download: GET %s", url[:80])++ timeout = aiohttp.ClientTimeout(total=60)+ async with aiohttp.ClientSession(timeout=timeout) as session:+ async with session.get(url) as resp:+ logger.debug("CDN download: status=%d", resp.status)+ if not resp.ok:+ body = await resp.text()+ raise RuntimeError(f"CDN download {resp.status} {resp.reason}: {body[:200]}")+ encrypted = await resp.read()++ logger.debug("CDN download: %d bytes, decrypting", len(encrypted))+ decrypted = aes_ecb_decrypt(encrypted, key)+ logger.debug("CDN download: decrypted %d bytes", len(decrypted))+ return decrypted+++# ---------------------------------------------------------------------------+# High-level upload workflows+# ---------------------------------------------------------------------------+++async def _upload_media_to_cdn(+ base_url: str,+ token: str,+ cdn_base_url: str,+ to_user_id: str,+ file_path: str,+ media_type: int,+ label: str,+) -> Dict[str, Any]:+ """Common upload pipeline: read file -> hash -> gen aeskey -> getUploadUrl -> upload -> return info.++ Args:+ base_url: iLink API base URL.+ token: Bot auth token.+ cdn_base_url: CDN base URL.+ to_user_id: Recipient user ID.+ file_path: Local path to the file.+ media_type: Upload media type constant.+ label: Logging label.++ Returns:+ Dict with ``encrypt_query_param``, ``aes_key`` (base64), ``file_size``,+ ``file_size_ciphertext``, ``filekey``, ``raw_md5``.+ """+ path = Path(file_path)+ plaintext = path.read_bytes()+ rawsize = len(plaintext)+ rawfilemd5 = hashlib.md5(plaintext).hexdigest()+ filesize = aes_ecb_padded_size(rawsize)+ filekey = os.urandom(16).hex()+ aes_key = os.urandom(16)++ logger.debug(+ "%s: file=%s rawsize=%d filesize=%d md5=%s filekey=%s",+ label,+ file_path,+ rawsize,+ filesize,+ rawfilemd5,+ filekey,+ )++ upload_resp = await get_upload_url(+ base_url,+ token,+ params={+ "filekey": filekey,+ "media_type": media_type,+ "to_user_id": to_user_id,+ "rawsize": rawsize,+ "rawfilemd5": rawfilemd5,+ "filesize": filesize,+ "no_need_thumb": True,+ "aeskey": aes_key.hex(),+ },+ )++ upload_param = upload_resp.get("upload_param")+ if not upload_param:+ logger.error(+ "%s: getUploadUrl returned no upload_param, resp=%s",+ label,+ upload_resp,+ )+ raise RuntimeError(f"{label}: getUploadUrl returned no upload_param")++ download_param = await upload_buffer_to_cdn(+ cdn_base_url=cdn_base_url,+ upload_param=upload_param,+ filekey=filekey,+ data=plaintext,+ aes_key=aes_key,+ )++ # Encode the AES key as hex then base64 for the CDNMedia.aes_key field+ aes_key_b64 = base64.b64encode(aes_key.hex().encode("ascii")).decode("ascii")++ return {+ "encrypt_query_param": download_param,+ "aes_key": aes_key_b64,+ "file_size": rawsize,+ "file_size_ciphertext": filesize,+ "filekey": filekey,+ "raw_md5": rawfilemd5,+ }+++async def upload_image_to_cdn(+ base_url: str,+ token: str,+ cdn_base_url: str,+ to_user_id: str,+ file_path: str,+) -> Dict[str, Any]:+ """Upload a local image file to the WeChat CDN with AES-128-ECB encryption.++ Args:+ base_url: iLink API base URL.+ token: Bot auth token.+ cdn_base_url: CDN base URL.+ to_user_id: Recipient user ID.+ file_path: Local path to the image file.++ Returns:+ Dict with ``encrypt_query_param``, ``aes_key``, ``file_size``,+ ``file_size_ciphertext``, ``filekey``, ``raw_md5``.+ """+ return await _upload_media_to_cdn(+ base_url=base_url,+ token=token,+ cdn_base_url=cdn_base_url,+ to_user_id=to_user_id,+ file_path=file_path,+ media_type=UPLOAD_MEDIA_IMAGE,+ label="upload_image_to_cdn",+ )+++async def upload_file_to_cdn(+ base_url: str,+ token: str,+ cdn_base_url: str,+ to_user_id: str,+ file_path: str,+ media_type: int = UPLOAD_MEDIA_FILE,+) -> Dict[str, Any]:+ """Upload a local file (or video) to the WeChat CDN.++ Args:+ base_url: iLink API base URL.+ token: Bot auth token.+ cdn_base_url: CDN base URL.+ to_user_id: Recipient user ID.+ file_path: Local path to the file.+ media_type: ``UPLOAD_MEDIA_FILE`` (3, default) or ``UPLOAD_MEDIA_VIDEO`` (2).++ Returns:+ Dict with ``encrypt_query_param``, ``aes_key``, ``file_size``,+ ``file_size_ciphertext``, ``filekey``, ``raw_md5``.+ """+ label = "upload_video_to_cdn" if media_type == UPLOAD_MEDIA_VIDEO else "upload_file_to_cdn"+ return await _upload_media_to_cdn(+ base_url=base_url,+ token=token,+ cdn_base_url=cdn_base_url,+ to_user_id=to_user_id,+ file_path=file_path,+ media_type=media_type,+ label=label,+ )diff --git a/scripts/prepare_three_regression.py b/scripts/prepare_three_regression.pyindex 26a1474ab..7eeb48afc 100755--- a/scripts/prepare_three_regression.py+++ b/scripts/prepare_three_regression.py@@ -33,6 +33,11 @@ SERVICE_DEFS = {"THREE_REGRESSION_FEISHU_APP_SECRET",),},+ "wechat": {+ "platform": "wechat",+ "channel_env": "THREE_REGRESSION_WECHAT_CHANNEL",+ "required_envs": (), # bot_token obtained via QR login, not env+ },}SUPPORTED_BACKENDS = {"opencode", "claude", "codex"}@@ -122,6 +127,7 @@ def _build_config_payload(service_name: str) -> dict:slack_payload = _base_slack_payload()discord_payload = Nonelark_payload = None+ wechat_payload = Noneif service_name == "slack":slack_payload = {@@ -145,6 +151,13 @@ def _build_config_payload(service_name: str) -> dict:"require_mention": require_mention,"domain": _env("THREE_REGRESSION_FEISHU_DOMAIN", "feishu"),}+ elif service_name == "wechat":+ wechat_payload = {+ "bot_token": _env("THREE_REGRESSION_WECHAT_BOT_TOKEN"),+ "base_url": _env("THREE_REGRESSION_WECHAT_BASE_URL", "https://ilinkai.weixin.qq.com"),+ "cdn_base_url": _env("THREE_REGRESSION_WECHAT_CDN_BASE_URL", "https://novac2c.cdn.weixin.qq.com/c2c"),+ "require_mention": require_mention,+ }return {"platform": service["platform"],@@ -153,6 +166,7 @@ def _build_config_payload(service_name: str) -> dict:"slack": slack_payload,"discord": discord_payload,"lark": lark_payload,+ "wechat": wechat_payload,"runtime": {"default_cwd": _service_default_cwd(service_name),"log_level": _env("THREE_REGRESSION_LOG_LEVEL", "INFO"),diff --git a/scripts/run_three_regression.sh b/scripts/run_three_regression.shindex eb5668033..424958608 100755--- a/scripts/run_three_regression.sh+++ b/scripts/run_three_regression.sh@@ -54,7 +54,7 @@ Usage:./scripts/run_three_regression.sh --reset-all./scripts/run_three_regression.sh --down./scripts/run_three_regression.sh --status- ./scripts/run_three_regression.sh --logs [slack|discord|feishu]+ ./scripts/run_three_regression.sh --logs [slack|discord|feishu|wechat]./scripts/run_three_regression.sh --env-file /path/to/.env.three-regressionEOF}@@ -139,6 +139,7 @@ print_summary() {local slack_channel="${THREE_REGRESSION_SLACK_CHANNEL:-}"local discord_channel="${THREE_REGRESSION_DISCORD_CHANNEL:-}"local feishu_channel="${THREE_REGRESSION_FEISHU_CHAT_ID:-}"+ local wechat_channel="${THREE_REGRESSION_WECHAT_CHANNEL:-}"local ui_host="${THREE_REGRESSION_UI_HOST:-127.0.0.1}"if [ -z "$slack_channel" ]; then@@ -150,12 +151,16 @@ print_summary() {if [ -z "$feishu_channel" ]; thenfeishu_channel="(configure later in UI)"fi+ if [ -z "$wechat_channel" ]; then+ wechat_channel="(QR login required in UI)"+ ficat <<EOF-Three-end regression environment is ready:-- Slack: http://${ui_host}:${THREE_REGRESSION_SLACK_PORT:-15131} channel=${slack_channel} backend=${THREE_REGRESSION_SLACK_BACKEND}+Four-platform regression environment is ready:+- Slack: http://${ui_host}:${THREE_REGRESSION_SLACK_PORT:-15131} channel=${slack_channel} backend=${THREE_REGRESSION_SLACK_BACKEND}- Discord: http://${ui_host}:${THREE_REGRESSION_DISCORD_PORT:-15132} channel=${discord_channel} backend=${THREE_REGRESSION_DISCORD_BACKEND}-- Feishu: http://${ui_host}:${THREE_REGRESSION_FEISHU_PORT:-15133} channel=${feishu_channel} backend=${THREE_REGRESSION_FEISHU_BACKEND}+- Feishu: http://${ui_host}:${THREE_REGRESSION_FEISHU_PORT:-15133} channel=${feishu_channel} backend=${THREE_REGRESSION_FEISHU_BACKEND}+- WeChat: http://${ui_host}:${THREE_REGRESSION_WECHAT_PORT:-15134} channel=${wechat_channel} backend=${THREE_REGRESSION_WECHAT_BACKEND:-opencode}EOF}@@ -218,5 +223,6 @@ echo "Waiting for services to become healthy..."wait_for_service slack "${THREE_REGRESSION_SLACK_PORT:-15131}"wait_for_service discord "${THREE_REGRESSION_DISCORD_PORT:-15132}"wait_for_service feishu "${THREE_REGRESSION_FEISHU_PORT:-15133}"+wait_for_service wechat "${THREE_REGRESSION_WECHAT_PORT:-15134}"print_summarydiff --git a/ui/package-lock.json b/ui/package-lock.jsonindex 79024b74e..cdb946f7e 100644--- a/ui/package-lock.json+++ b/ui/package-lock.json@@ -15,6 +15,7 @@"i18next": "^25.7.4","i18next-browser-languagedetector": "^8.2.0","lucide-react": "^0.562.0",+ "qrcode.react": "^4.2.0","react": "^19.2.0","react-dom": "^19.2.0","react-i18next": "^16.5.3",@@ -4175,6 +4176,15 @@"node": ">=6"}},+ "node_modules/qrcode.react": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz",+ "integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==",+ "license": "ISC",+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },"node_modules/react": {"version": "19.2.3","resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz",diff --git a/ui/package.json b/ui/package.jsonindex 269198988..9bf84b85f 100644--- a/ui/package.json+++ b/ui/package.json@@ -17,6 +17,7 @@"i18next": "^25.7.4","i18next-browser-languagedetector": "^8.2.0","lucide-react": "^0.562.0",+ "qrcode.react": "^4.2.0","react": "^19.2.0","react-dom": "^19.2.0","react-i18next": "^16.5.3",diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex c71f33447..68fccac5f 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -24,7 +24,9 @@ const AuthGuard = ({ children }: { children: any }) => {? !!config?.discord?.bot_token: platform === 'lark'? !!(config?.lark?.app_id && config?.lark?.app_secret)- : !!config?.slack?.bot_token;+ : platform === 'wechat'+ ? !!config?.wechat?.bot_token+ : !!config?.slack?.bot_token;if (!config || !config.mode || !hasToken) {setNeedsSetup(true);}diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsxindex 65d24ab7c..c9410e300 100644--- a/ui/src/components/AppShell.tsx+++ b/ui/src/components/AppShell.tsx@@ -1,8 +1,9 @@-import React from 'react';+import React, { useEffect, useState } from 'react';import { NavLink, Outlet, useLocation } from 'react-router-dom';import { LayoutDashboard, MessageSquare, Activity, Users } from 'lucide-react';import { useTranslation } from 'react-i18next';import { useStatus } from '../context/StatusContext';+import { useApi } from '../context/ApiContext';import { LanguageSwitcher } from './LanguageSwitcher';import { VersionBadge } from './VersionBadge';import clsx from 'clsx';@@ -26,9 +27,16 @@ const NavItem = ({ to, icon: Icon, children }: { to: string; icon: any; childrenexport const AppShell: React.FC = () => {const { t } = useTranslation();const { status } = useStatus();+ const api = useApi();const location = useLocation();+ const [platform, setPlatform] = useState<string>('');++ useEffect(() => {+ api.getConfig().then((c: any) => setPlatform(c?.platform || '')).catch(() => {});+ }, []);const isRunning = status.state === 'running';+ const isWechat = platform === 'wechat';if (location.pathname === '/setup') {return <Outlet />;@@ -52,7 +60,7 @@ export const AppShell: React.FC = () => {<nav className="flex-1 p-4 space-y-1"><NavItem to="/dashboard" icon={LayoutDashboard}>{t('nav.dashboard')}</NavItem>- <NavItem to="/channels" icon={MessageSquare}>{t('nav.channels')}</NavItem>+ {!isWechat && <NavItem to="/channels" icon={MessageSquare}>{t('nav.channels')}</NavItem>}<NavItem to="/users" icon={Users}>{t('nav.users')}</NavItem><NavItem to="/doctor" icon={Activity}>{t('nav.doctor')}</NavItem></nav>@@ -76,7 +84,7 @@ export const AppShell: React.FC = () => {{/* Mobile Nav */}<nav className="md:hidden fixed bottom-0 left-0 right-0 bg-panel border-t border-border flex justify-around p-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] z-50"><NavLink to="/dashboard" className={({isActive}) => clsx("p-2 rounded-lg", isActive ? "text-accent" : "text-muted")}><LayoutDashboard /></NavLink>- <NavLink to="/channels" className={({isActive}) => clsx("p-2 rounded-lg", isActive ? "text-accent" : "text-muted")}><MessageSquare /></NavLink>+ {!isWechat && <NavLink to="/channels" className={({isActive}) => clsx("p-2 rounded-lg", isActive ? "text-accent" : "text-muted")}><MessageSquare /></NavLink>}<NavLink to="/users" className={({isActive}) => clsx("p-2 rounded-lg", isActive ? "text-accent" : "text-muted")}><Users /></NavLink><NavLink to="/doctor" className={({isActive}) => clsx("p-2 rounded-lg", isActive ? "text-accent" : "text-muted")}><Activity /></NavLink></nav>diff --git a/ui/src/components/Wizard.tsx b/ui/src/components/Wizard.tsxindex 69ce6d126..c9fe9551a 100644--- a/ui/src/components/Wizard.tsx+++ b/ui/src/components/Wizard.tsx@@ -8,6 +8,7 @@ import { AgentDetection } from './steps/AgentDetection';import { SlackConfig } from './steps/SlackConfig';import { DiscordConfig } from './steps/DiscordConfig';import { LarkConfig } from './steps/LarkConfig';+import { WeChatConfig } from './steps/WeChatConfig';import { ChannelList } from './steps/ChannelList';import { Summary } from './steps/Summary';import { useApi } from '../context/ApiContext';@@ -40,6 +41,13 @@ const buildConfigPayload = (data: any) => ({domain: data.lark?.domain || 'feishu',require_mention: data.lark?.require_mention || false,},+ wechat: {+ ...data.wechat,+ bot_token: data.wechat?.bot_token || '',+ base_url: data.wechat?.base_url || 'https://ilinkai.weixin.qq.com',+ cdn_base_url: data.wechat?.cdn_base_url || 'https://novac2c.cdn.weixin.qq.com/c2c',+ require_mention: data.wechat?.require_mention || false,+ },runtime: {// Preserve existing runtime config...data.runtime,@@ -105,7 +113,9 @@ export const Wizard: React.FC = () => {? { id: 'discord', title: 'Discord', component: DiscordConfig }: platform === 'lark'? { id: 'lark', title: 'Lark', component: LarkConfig }- : { id: 'slack', title: 'Slack', component: SlackConfig },+ : platform === 'wechat'+ ? { id: 'wechat', title: 'WeChat', component: WeChatConfig }+ : { id: 'slack', title: 'Slack', component: SlackConfig },{ id: 'channels', title: 'Channels', component: ChannelList },{ id: 'summary', title: 'Finish', component: Summary },];@@ -167,6 +177,7 @@ export const Wizard: React.FC = () => {mergedData.slack ||mergedData.discord ||mergedData.lark ||+ mergedData.wechat ||mergedData.mode ||mergedData.platform ||mergedData.channelConfigsdiff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsxindex ca8e893dd..88e3643fa 100644--- a/ui/src/components/steps/ChannelList.tsx+++ b/ui/src/components/steps/ChannelList.tsx@@ -1,10 +1,11 @@import React, { useEffect, useState } from 'react';-import { Hash, CheckSquare, Square, RefreshCw, HelpCircle, Globe, FolderOpen } from 'lucide-react';+import { Hash, CheckSquare, Square, RefreshCw, HelpCircle, Globe, FolderOpen, MessageSquare, Users } from 'lucide-react';import { useTranslation } from 'react-i18next';import { useApi } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';import { Combobox } from '../ui/combobox';import { DirectoryBrowser } from '../ui/directory-browser';+import { useNavigate } from 'react-router-dom';import clsx from 'clsx';/** Input that only commits value on blur */@@ -412,6 +413,60 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB);}, [channels, configs]);+ const navigate = useNavigate();++ // WeChat: no channels, redirect to user settings+ if (platform === 'wechat') {+ // In wizard mode, skip channel step entirely+ if (!isPage) {+ return (+ <div className="flex flex-col h-full items-center justify-center">+ <div className="w-16 h-16 bg-accent/10 text-accent rounded-full flex items-center justify-center border border-accent/20 mb-6">+ <MessageSquare size={32} />+ </div>+ <h2 className="text-2xl font-display font-bold text-text mb-2">{t('channelList.title')}</h2>+ <p className="text-muted mb-8">{t('wechat.noChannels')}</p>+ <div className="mt-auto flex justify-between w-full">+ <button onClick={onBack} className="px-6 py-2 text-muted hover:text-text font-medium">+ {t('common.back')}+ </button>+ <button+ onClick={() => onNext && onNext({})}+ className="px-6 py-2 bg-accent hover:bg-accent/90 text-white rounded-lg font-medium shadow-sm"+ >+ {t('common.continue')}+ </button>+ </div>+ </div>+ );+ }++ // In page mode, show notice and link to user settings+ return (+ <div className="max-w-5xl mx-auto flex flex-col h-full">+ <div className="flex justify-between items-center mb-6">+ <div>+ <h2 className="text-3xl font-display font-bold">{t('channelList.title')}</h2>+ <p className="text-muted">{t('wechat.noChannels')}</p>+ </div>+ </div>+ <div className="bg-panel border border-border rounded-xl p-8 text-center shadow-sm">+ <div className="w-16 h-16 bg-accent/10 text-accent rounded-full flex items-center justify-center border border-accent/20 mx-auto mb-4">+ <MessageSquare size={32} />+ </div>+ <p className="text-muted mb-6">{t('wechat.noChannels')}</p>+ <button+ onClick={() => navigate('/users')}+ className="inline-flex items-center gap-2 px-6 py-3 bg-accent hover:bg-accent/90 text-white rounded-lg font-medium transition-colors shadow-sm"+ >+ <Users size={18} />+ {t('wechat.manageUserSettings')}+ </button>+ </div>+ </div>+ );+ }+return (<><div className={clsx('flex flex-col h-full', isPage ? 'max-w-5xl mx-auto' : '')}>diff --git a/ui/src/components/steps/PlatformSelection.tsx b/ui/src/components/steps/PlatformSelection.tsxindex 3bee9181c..11287f3bd 100644--- a/ui/src/components/steps/PlatformSelection.tsx+++ b/ui/src/components/steps/PlatformSelection.tsx@@ -19,8 +19,8 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNe<p className="text-muted mt-1">{t('platform.subtitle')}</p></div>- <div className="grid grid-cols-1 md:grid-cols-3 gap-4 flex-1">- {['slack', 'discord', 'lark'].map((option) => (+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 flex-1">+ {['slack', 'discord', 'lark', 'wechat'].map((option) => (<buttonkey={option}onClick={() => onNext({ platform: option })}diff --git a/ui/src/components/steps/Summary.tsx b/ui/src/components/steps/Summary.tsxindex 85a76c7de..f0e67574c 100644--- a/ui/src/components/steps/Summary.tsx+++ b/ui/src/components/steps/Summary.tsx@@ -28,6 +28,7 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {const [requireMention, setRequireMention] = useState(platform === 'discord' ? (data.discord?.require_mention || false): platform === 'lark' ? (data.lark?.require_mention || false)+ : platform === 'wechat' ? (data.wechat?.require_mention || false): (data.slack?.require_mention || false));const [autoUpdate, setAutoUpdate] = useState(data.update?.auto_update ?? true);@@ -63,6 +64,10 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {...data.lark,require_mention: platform === 'lark' ? requireMention : data.lark?.require_mention,},+ wechat: {+ ...data.wechat,+ require_mention: platform === 'wechat' ? requireMention : data.wechat?.require_mention,+ },update: {...data.update,auto_update: autoUpdate,@@ -75,6 +80,16 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {// Start serviceawait control('start');+ // WeChat: skip bind code, auto-bind happens on QR login+ if (platform === 'wechat') {+ setSaving(false);+ showToast(t('wechat.setupComplete'));+ setTimeout(() => {+ navigate('/dashboard');+ }, 1000);+ return;+ }+// Fetch first bind code (auto-generated on first access)try {const resp = await api.getFirstBindCode();@@ -165,6 +180,14 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {<Section title={t('summary.discordBotToken')} value={mask(data.discord?.bot_token || '')} /><Section title={t('summary.discordGuild')} value={(data.discord?.guild_allowlist || [])[0] || t('summary.notSet')} /></>+ ) : platform === 'lark' ? (+ <>+ <Section title={t('summary.larkAppId')} value={mask(data.lark?.app_id || '')} />+ </>+ ) : platform === 'wechat' ? (+ <>+ <Section title={t('summary.wechatBotToken')} value={mask(data.wechat?.bot_token || '')} />+ </>) : (<><Section title={t('summary.slackBotToken')} value={mask(data.slack?.bot_token || '')} />@@ -314,6 +337,12 @@ const buildConfigPayload = (data: any) => {domain: data.lark?.domain || 'feishu',require_mention: data.lark?.require_mention || false,},+ wechat: {+ ...data.wechat,+ bot_token: data.wechat?.bot_token || '',+ base_url: data.wechat?.base_url || '',+ require_mention: data.wechat?.require_mention || false,+ },runtime: {// Preserve existing runtime config...data.runtime,diff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsxindex 859923902..3ac87d74e 100644--- a/ui/src/components/steps/UserList.tsx+++ b/ui/src/components/steps/UserList.tsx@@ -490,7 +490,13 @@ export const UserList: React.FC = () => {</div></div>- <BindCodeSection />+ {config.platform === 'wechat' ? (+ <div className="mb-6 bg-panel border border-border rounded-xl p-4 shadow-sm">+ <p className="text-sm text-muted">{t('wechat.userBound')}</p>+ </div>+ ) : (+ <BindCodeSection />+ )}<div className="flex-1 overflow-y-auto border border-border rounded-xl divide-y divide-border bg-panel shadow-sm">{userEntries.length === 0 ? (diff --git a/ui/src/components/steps/WeChatConfig.tsx b/ui/src/components/steps/WeChatConfig.tsxnew file mode 100644index 000000000..ebb5e2f3a--- /dev/null+++ b/ui/src/components/steps/WeChatConfig.tsx@@ -0,0 +1,278 @@+import React, { useCallback, useEffect, useRef, useState } from 'react';+import { QRCodeSVG } from 'qrcode.react';+import { Check, RefreshCw, Smartphone, Wifi, AlertTriangle, Loader2 } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import clsx from 'clsx';+import { useApi } from '../../context/ApiContext';++interface WeChatConfigProps {+ data: Record<string, any>;+ onNext: (data: Record<string, any>) => void;+ onBack: () => void;+}++export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBack }) => {+ const { t } = useTranslation();+ const api = useApi();++ const [loginState, setLoginState] = useState<'idle' | 'qr_ready' | 'scanning' | 'confirming' | 'connected' | 'error'>('idle');+ const [qrCodeUrl, setQrCodeUrl] = useState<string>('');+ const [message, setMessage] = useState<string>('');+ const [botToken, setBotToken] = useState<string>(data.wechat?.bot_token || '');+ const [baseUrl, setBaseUrl] = useState<string>(data.wechat?.base_url || '');+ const [starting, setStarting] = useState(false);++ const pollTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);++ const stopPolling = useCallback(() => {+ if (pollTimerRef.current) {+ clearInterval(pollTimerRef.current);+ pollTimerRef.current = null;+ }+ }, []);++ // Cleanup on unmount+ useEffect(() => {+ return () => {+ stopPolling();+ };+ }, [stopPolling]);++ const startLogin = async () => {+ setStarting(true);+ setLoginState('idle');+ setMessage('');+ setQrCodeUrl('');+ setBotToken('');+ setBaseUrl('');+ stopPolling();++ try {+ const result = await api.wechatStartLogin();+ if (result.error) {+ setLoginState('error');+ setMessage(result.error);+ return;+ }+ setQrCodeUrl(result.qrcode_url || '');+ setMessage(result.message || '');+ setLoginState('qr_ready');++ // Start polling+ if (result.session_key) {+ startPolling(result.session_key);+ }+ } catch (err: any) {+ setLoginState('error');+ setMessage(err?.message || t('wechatConfig.startFailed'));+ } finally {+ setStarting(false);+ }+ };++ const startPolling = (key: string) => {+ stopPolling();+ pollTimerRef.current = setInterval(async () => {+ try {+ const result = await api.wechatPollLogin(key);+ if (!result) return;++ const status = result.status;+ if (status === 'scaned') {+ setLoginState('confirming');+ setMessage(result.message || t('wechatConfig.confirmOnPhone'));+ } else if (status === 'confirmed') {+ setLoginState('connected');+ setMessage(result.message || t('wechatConfig.connected'));+ setBotToken(result.bot_token || '');+ setBaseUrl(result.base_url || '');+ stopPolling();+ } else if (status === 'expired') {+ setLoginState('error');+ setMessage(result.message || t('wechatConfig.qrExpired'));+ stopPolling();+ } else if (status === 'error') {+ setLoginState('error');+ setMessage(result.message || t('wechatConfig.pollError'));+ stopPolling();+ }+ // status === 'wait' — keep polling+ } catch {+ // Ignore transient errors, keep polling+ }+ }, 2000);+ };++ const isConnected = loginState === 'connected' && !!botToken;++ const stepIndicator = (stepNum: number, label: string, active: boolean, completed: boolean) => (+ <div className="flex items-center gap-2">+ <span+ className={clsx(+ 'w-7 h-7 rounded-full text-sm font-bold flex items-center justify-center transition-colors',+ completed ? 'bg-success text-white' : active ? 'bg-accent text-white' : 'bg-neutral-200 text-muted'+ )}+ >+ {completed ? <Check size={14} /> : stepNum}+ </span>+ <span className={clsx('text-sm font-medium', active || completed ? 'text-text' : 'text-muted')}>{label}</span>+ </div>+ );++ const getStepState = () => {+ if (loginState === 'idle') return { step: 1, scanning: false, connected: false };+ if (loginState === 'qr_ready') return { step: 2, scanning: false, connected: false };+ if (loginState === 'scanning' || loginState === 'confirming') return { step: 2, scanning: true, connected: false };+ if (loginState === 'connected') return { step: 3, scanning: false, connected: true };+ return { step: 1, scanning: false, connected: false }; // error+ };++ const { step, connected } = getStepState();++ return (+ <div className="flex flex-col h-full max-w-2xl mx-auto">+ <div className="mb-4">+ <h2 className="text-3xl font-display font-bold text-text">{t('wechatConfig.title')}</h2>+ <p className="text-muted mt-1">{t('wechatConfig.subtitle')}</p>+ </div>++ {/* Step indicators */}+ <div className="mb-6 bg-panel border border-border rounded-xl p-4">+ <div className="flex items-center justify-between">+ {stepIndicator(1, t('wechatConfig.stepStart'), step === 1 && loginState !== 'error', step > 1)}+ <div className="flex-1 h-px bg-border mx-3" />+ {stepIndicator(2, t('wechatConfig.stepScan'), step === 2, step > 2)}+ <div className="flex-1 h-px bg-border mx-3" />+ {stepIndicator(3, t('wechatConfig.stepDone'), false, connected)}+ </div>+ </div>++ <div className="flex-1 space-y-4 overflow-y-auto pr-1">+ {/* Start Login */}+ {loginState === 'idle' && (+ <div className="bg-panel border border-border rounded-xl p-6 text-center space-y-4">+ <div className="w-16 h-16 bg-accent/10 text-accent rounded-full flex items-center justify-center mx-auto">+ <Smartphone size={32} />+ </div>+ <p className="text-sm text-muted">{t('wechatConfig.startDescription')}</p>+ <button+ onClick={startLogin}+ disabled={starting}+ className="px-6 py-3 bg-accent text-white rounded-lg flex items-center gap-2 mx-auto font-medium shadow-sm hover:bg-accent/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {starting ? <RefreshCw size={16} className="animate-spin" /> : <Smartphone size={16} />}+ {starting ? t('wechatConfig.starting') : t('wechatConfig.startLogin')}+ </button>+ </div>+ )}++ {/* QR Code Display */}+ {(loginState === 'qr_ready' || loginState === 'scanning' || loginState === 'confirming') && (+ <div className="bg-panel border border-border rounded-xl p-6 space-y-4">+ <div className="flex flex-col items-center space-y-4">+ {/* QR Code */}+ <div className="bg-white p-4 rounded-xl shadow-sm border border-neutral-100">+ <QRCodeSVG+ value={qrCodeUrl}+ size={256}+ level="M"+ includeMargin={false}+ />+ </div>++ {/* Status indicator */}+ <div className={clsx(+ 'flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium border',+ loginState === 'qr_ready' && 'bg-blue-50 border-blue-200 text-blue-800',+ loginState === 'scanning' && 'bg-amber-50 border-amber-200 text-amber-800',+ loginState === 'confirming' && 'bg-amber-50 border-amber-200 text-amber-800',+ )}>+ {loginState === 'qr_ready' && (+ <>+ <Loader2 size={16} className="animate-spin" />+ {t('wechatConfig.waitingForScan')}+ </>+ )}+ {(loginState === 'scanning' || loginState === 'confirming') && (+ <>+ <Smartphone size={16} />+ {t('wechatConfig.confirmOnPhone')}+ </>+ )}+ </div>++ <p className="text-xs text-muted text-center">{t('wechatConfig.scanHint')}</p>+ </div>+ </div>+ )}++ {/* Connected */}+ {loginState === 'connected' && (+ <div className="bg-panel border border-border rounded-xl p-6 space-y-4">+ <div className="flex flex-col items-center space-y-4">+ <div className="w-20 h-20 bg-success/10 text-success rounded-full flex items-center justify-center animate-in fade-in zoom-in duration-300">+ <Check size={40} />+ </div>+ <div className="text-center">+ <h3 className="text-lg font-semibold text-text">{t('wechatConfig.connectedTitle')}</h3>+ <p className="text-sm text-muted mt-1">{message}</p>+ </div>+ <div className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium bg-success/10 border border-success/20 text-success">+ <Wifi size={16} />+ {t('wechatConfig.connectionEstablished')}+ </div>+ </div>+ </div>+ )}++ {/* Error / Retry */}+ {loginState === 'error' && (+ <div className="bg-panel border border-border rounded-xl p-6 space-y-4">+ <div className="flex flex-col items-center space-y-4">+ <div className="w-16 h-16 bg-danger/10 text-danger rounded-full flex items-center justify-center">+ <AlertTriangle size={32} />+ </div>+ <div className="text-center">+ <h3 className="text-lg font-semibold text-text">{t('wechatConfig.errorTitle')}</h3>+ <p className="text-sm text-danger mt-1">{message}</p>+ </div>+ <button+ onClick={startLogin}+ disabled={starting}+ className="px-6 py-3 bg-accent text-white rounded-lg flex items-center gap-2 font-medium shadow-sm hover:bg-accent/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"+ >+ <RefreshCw size={16} />+ {t('wechatConfig.retry')}+ </button>+ </div>+ </div>+ )}+ </div>++ <div className="mt-auto flex justify-between pt-6 border-t border-border">+ <button onClick={onBack} className="px-6 py-2 text-muted hover:text-text font-medium transition-colors">+ {t('common.back')}+ </button>+ <button+ onClick={() => {+ onNext({+ platform: 'wechat',+ wechat: {+ ...(data.wechat || {}),+ bot_token: botToken,+ base_url: baseUrl,+ },+ });+ }}+ disabled={!isConnected}+ className={clsx(+ 'px-8 py-3 rounded-lg font-medium transition-colors shadow-sm',+ isConnected ? 'bg-accent hover:bg-accent/90 text-white' : 'bg-neutral-200 text-muted cursor-not-allowed'+ )}+ >+ {t('common.continue')}+ </button>+ </div>+ </div>+ );+};diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 068209644..29a2e9a6b 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -26,6 +26,8 @@ export type ApiContextType = {larkChats: (appId: string, appSecret: string, domain?: string) => Promise<any>;larkTempWsStart: (appId: string, appSecret: string, domain?: string) => Promise<any>;larkTempWsStop: () => Promise<any>;+ wechatStartLogin: () => Promise<any>;+ wechatPollLogin: (sessionKey: string) => Promise<any>;doctor: () => Promise<any>;opencodeOptions: (cwd: string) => Promise<any>;opencodeSetupPermission: () => Promise<{ ok: boolean; message: string; config_path: string }>;@@ -150,6 +152,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenlarkChats: (appId, appSecret, domain) => postJson('/lark/chats', { app_id: appId, app_secret: appSecret, domain: domain || 'feishu' }),larkTempWsStart: (appId, appSecret, domain) => postJson('/lark/temp_ws/start', { app_id: appId, app_secret: appSecret, domain: domain || 'feishu' }),larkTempWsStop: () => postJson('/lark/temp_ws/stop', {}),+ wechatStartLogin: () => postJson('/wechat/qr_login/start', {}),+ wechatPollLogin: (sessionKey) => postJson('/wechat/qr_login/poll', { session_key: sessionKey }),doctor: () => postJson('/doctor', {}),opencodeOptions: (cwd) => postJson('/opencode/options', { cwd }),opencodeSetupPermission: () => postJson('/opencode/setup-permission', {}),diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 869183f21..f00af134f 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -79,6 +79,10 @@"lark": {"title": "Lark","desc": "Connect to Feishu/Lark workspace for team collaboration"+ },+ "wechat": {+ "title": "WeChat",+ "desc": "Connect to WeChat personal messaging via iLink bot"}},"discordConfig": {@@ -201,6 +205,28 @@"step5Tip": "After publishing, all configurations (permissions, events, bot capability) will take effect.","step5OpenLink": "Open Version Management"},+ "wechatConfig": {+ "title": "WeChat Setup",+ "subtitle": "Scan the QR code with your WeChat to connect.",+ "stepStart": "Start",+ "stepScan": "Scan",+ "stepDone": "Done",+ "startDescription": "Click the button below to generate a WeChat login QR code. You will scan it with your phone to connect.",+ "startLogin": "Generate QR Code",+ "starting": "Generating...",+ "startFailed": "Failed to start login flow",+ "waitingForScan": "Waiting for you to scan the QR code...",+ "confirmOnPhone": "Scanned! Please confirm on your phone.",+ "scanHint": "Open WeChat on your phone and scan this QR code to log in.",+ "connected": "WeChat connected successfully!",+ "connectedTitle": "Connected",+ "connectionEstablished": "WeChat connection established",+ "qrExpired": "QR code expired. Please try again.",+ "pollError": "An error occurred while checking status.",+ "errorTitle": "Connection Failed",+ "retry": "Try Again",+ "refreshQr": "Refresh QR Code"+ },"slackConfig": {"title": "Slack Configuration","saasDescription": "Authorize the official Slack app and wait for workspace binding.",@@ -273,6 +299,7 @@"inviteBotHint": "Invite the bot to your channel first:\n1. Open the channel, click ⚙️ Settings → Integrations → Add apps\n2. Or type /invite @YourBotName in the channel","discordInviteBotHint": "Add the bot to your guild and grant access to the channel.","larkInviteBotHint": "Add the bot to a group chat: Open the group → Settings → Bots → Add Bot.",+ "wechatInviteBotHint": "Send a message to your WeChat bot account to start a conversation.","guild": "Guild","guildPlaceholder": "Select a guild","discordText": "Text",@@ -318,6 +345,8 @@"slackBotToken": "Slack Bot Token","slackAppToken": "Slack App Token","discordBotToken": "Discord Bot Token",+ "larkAppId": "Lark App ID",+ "wechatBotToken": "WeChat Bot Token","discordGuild": "Discord Guild","notSet": "Not set","enabledAgents": "Enabled Agents",@@ -435,6 +464,12 @@"showHidden": "Show hidden directories","hideHidden": "Hide hidden directories"},+ "wechat": {+ "userBound": "Your WeChat account is automatically configured as the bot owner.",+ "noChannels": "WeChat uses direct messaging — no channel configuration needed.",+ "setupComplete": "WeChat bot connected! Your account has been automatically configured.",+ "manageUserSettings": "Manage User Settings"+ },"userList": {"title": "Users","subtitle": "Manage bound users and their settings",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 7659d2160..26722aba9 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -79,6 +79,10 @@"lark": {"title": "飞书","desc": "连接飞书工作区,实现团队协作"+ },+ "wechat": {+ "title": "微信",+ "desc": "通过 iLink Bot 连接微信个人消息"}},"discordConfig": {@@ -201,6 +205,28 @@"step5Tip": "发布后,所有配置(权限、事件、机器人能力)才会正式生效。","step5OpenLink": "打开版本管理"},+ "wechatConfig": {+ "title": "微信设置",+ "subtitle": "使用微信扫描二维码以连接。",+ "stepStart": "开始",+ "stepScan": "扫码",+ "stepDone": "完成",+ "startDescription": "点击下方按钮生成微信登录二维码,然后用手机扫码完成连接。",+ "startLogin": "生成二维码",+ "starting": "正在生成...",+ "startFailed": "启动登录流程失败",+ "waitingForScan": "等待扫描二维码...",+ "confirmOnPhone": "已扫描!请在手机上确认。",+ "scanHint": "打开手机微信,扫描此二维码登录。",+ "connected": "微信连接成功!",+ "connectedTitle": "已连接",+ "connectionEstablished": "微信连接已建立",+ "qrExpired": "二维码已过期,请重试。",+ "pollError": "检查状态时发生错误。",+ "errorTitle": "连接失败",+ "retry": "重试",+ "refreshQr": "刷新二维码"+ },"slackConfig": {"title": "Slack 配置","saasDescription": "授权官方 Slack 应用并等待工作区绑定",@@ -273,6 +299,7 @@"inviteBotHint": "请先将 Bot 邀请到频道:\n1. 打开频道,点击 ⚙️ 设置 → 集成 → 添加应用\n2. 或在频道中输入 /invite @你的Bot名称","discordInviteBotHint": "请确保机器人已加入服务器并具备访问频道的权限。","larkInviteBotHint": "将机器人添加到群聊:打开群 → 设置 → 群机器人 → 添加机器人。",+ "wechatInviteBotHint": "向微信机器人账号发送消息即可开始对话。","guild": "服务器","guildPlaceholder": "选择服务器","discordText": "文本",@@ -318,6 +345,8 @@"slackBotToken": "Slack Bot 令牌","slackAppToken": "Slack App 令牌","discordBotToken": "Discord 机器人令牌",+ "larkAppId": "飞书 App ID",+ "wechatBotToken": "微信 Bot Token","discordGuild": "Discord 服务器","notSet": "未设置","enabledAgents": "已启用的 Agent",@@ -435,6 +464,12 @@"showHidden": "显示隐藏目录","hideHidden": "隐藏隐藏目录"},+ "wechat": {+ "userBound": "您的微信账号已自动配置为机器人所有者。",+ "noChannels": "微信使用私聊模式,无需配置频道。",+ "setupComplete": "微信机器人已连接!您的账号已自动配置。",+ "manageUserSettings": "管理用户设置"+ },"userList": {"title": "用户","subtitle": "管理已绑定的用户及其设置",diff --git a/vibe/api.py b/vibe/api.pyindex 3e72dbecd..3e28eaa40 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -240,6 +240,7 @@ def config_to_payload(config: V2Config) -> dict:},"discord": config.discord.__dict__ if config.discord else None,"lark": config.lark.__dict__ if config.lark else None,+ "wechat": config.wechat.__dict__ if config.wechat else None,"runtime": {"default_cwd": config.runtime.default_cwd,"log_level": config.runtime.log_level,@@ -1383,6 +1384,42 @@ def get_first_bind_code() -> dict:return {"ok": True, "code": bc.code, "is_new": True}+def auto_bind_wechat_user(user_id: str) -> dict:+ """Auto-create a UserSettings entry for the WeChat user on QR login.++ WeChat is 1:1 DM only — no channels, no bind codes needed.+ The QR scan itself is the authentication, so we auto-bind the user+ as admin with default settings.+ """+ from config.v2_settings import _now_iso++ store = SettingsStore.get_instance()+ platform = "wechat"++ # Skip if already bound+ if store.is_bound_user(user_id, platform=platform):+ logger.info("WeChat user %s already bound, skipping auto-bind", user_id)+ return {"ok": True, "already_bound": True}++ config = load_config()+ user = UserSettings(+ display_name=user_id,+ is_admin=True,+ bound_at=_now_iso(),+ enabled=True,+ custom_cwd=config.runtime.default_cwd or None,+ routing=RoutingSettings(agent_backend=config.agents.default_backend or None),+ )++ current_users = store.get_users_for_platform(platform)+ current_users[user_id] = user+ store.set_users_for_platform(platform, current_users)+ store.save()++ logger.info("Auto-bound WeChat user %s as admin", user_id)+ return {"ok": True, "already_bound": False}++# ---------------------------------------------------------------------------# Lark temporary WebSocket connection (for setup wizard)# ---------------------------------------------------------------------------diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 8444c3c3e..07d2bbbe9 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -339,6 +339,103 @@ def lark_temp_ws_stop():return jsonify(api.lark_temp_ws_stop())+# WeChat auth singleton+_wechat_auth_manager = None+++def _get_wechat_auth():+ global _wechat_auth_manager+ if _wechat_auth_manager is None:+ from modules.im.wechat_auth import WeChatAuthManager++ _wechat_auth_manager = WeChatAuthManager()+ return _wechat_auth_manager++[email protected]("/wechat/qr_login/start", methods=["POST"])+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 = _run_async(auth.start_login(base_url=base_url), timeout=15.0)+ if result.get("ok") is False:+ return jsonify(result), 500+ return jsonify(result)++[email protected]("/wechat/qr_login/poll", methods=["POST"])+def wechat_qr_login_poll():+ """Poll WeChat QR code login status."""+ payload = request.json or {}+ session_key = payload.get("session_key", "")+ if not session_key:+ return jsonify({"error": "session_key required"}), 400++ auth = _get_wechat_auth()+ result = _run_async(auth.poll_status(session_key), timeout=15.0)+ if result.get("ok") is False:+ return jsonify(result), 500++ # If confirmed, auto-bind the WeChat user and send welcome message+ if result.get("status") == "confirmed" and result.get("bot_token"):+ bot_token = result["bot_token"]+ base_url = result.get("base_url") or "https://ilinkai.weixin.qq.com"+ user_id = result.get("user_id", "wechat_user")++ # Auto-bind user+ try:+ from vibe import api as vibe_api++ vibe_api.auto_bind_wechat_user(user_id)+ except Exception as e:+ logger.warning("Failed to auto-bind WeChat user: %s", e)++ # Send welcome message to verify the send path works+ try:+ from modules.im import wechat_api as _wc_api++ welcome_text = (+ "WeChat bot connected successfully!\nYou can now send messages to interact with the AI agent."+ )+ _run_async(+ _wc_api.send_message(+ base_url,+ bot_token,+ user_id,+ "", # context_token: empty for first message+ [{"type": 1, "text_item": {"text": welcome_text}}],+ ),+ timeout=10.0,+ )+ logger.info("Sent welcome message to WeChat user %s", user_id)+ except Exception as e:+ logger.warning("Failed to send welcome message: %s", e)++ # Schedule service restart so the new token takes effect+ def _restart_after_login():+ import time++ time.sleep(2) # let the response go out first+ try:+ from vibe import runtime++ runtime.stop_service()+ time.sleep(1)+ runtime.ensure_config()+ service_pid = runtime.start_service()+ st = runtime.read_status()+ runtime.write_status("running", "restarted", service_pid, st.get("ui_pid"))+ logger.info("Service restarted after WeChat QR login")+ except Exception as exc:+ logger.warning("Failed to restart service after QR login: %s", exc)++ threading.Thread(target=_restart_after_login, daemon=True).start()++ return jsonify(result)++@app.route("/doctor", methods=["POST"])def doctor_post():from vibe.cli import _doctor