Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8549 feat(weixin): add native QR-linked WeChat IM channel (#9869)

Pogačar425cf08b6286
diff --git a/.env.example b/.env.example
index 92f9b8fb99..03565c2cf8 100644
--- a/.env.example
+++ b/.env.example
@@ -780,3 +780,7 @@ ANALYTICS_DISABLED=
# Server-managed Qoder Cloud Agents connections require
# MULTICA_VCS_SECRET_KEY: it encrypts the saved Qoder and GitHub tokens
# and the run journal in the database. Keep it stable across restarts.
+
+# WeChat iLink QR connection. Generate once with: openssl rand -base64 32
+# Keep the same key on every API replica; it encrypts bot tokens and QR state.
+MULTICA_WEIXIN_SECRET_KEY=
diff --git a/apps/docs/content/docs/channels.mdx b/apps/docs/content/docs/channels.mdx
index fe47a8b56b..56905d65de 100644
--- a/apps/docs/content/docs/channels.mdx
+++ b/apps/docs/content/docs/channels.mdx
@@ -1,6 +1,6 @@
---
title: Chat integrations
-description: Connect Multica agents to Feishu, Lark, Slack, DingTalk, WeCom, or Telegram and use them from the chat tools your team already uses.
+description: Connect Multica agents to Feishu, Lark, Slack, DingTalk, WeCom, Telegram, or WeChat and use them from the chat tools your team already uses.
---
import { Callout } from "fumadocs-ui/components/callout";
@@ -8,7 +8,7 @@ import { ChannelChatDemo } from "@/components/demos/channel-chat-demo";
Chat integrations let the team ask an agent questions in a DM, @-mention it in a group chat, or create issues from the chat window, without opening Multica.
-Feishu/Lark, Slack, DingTalk, WeCom, and Telegram are supported today. They share the same session, identity, and execution mechanics but install differently.
+Feishu/Lark, Slack, DingTalk, WeCom, Telegram, and WeChat are available. WeChat accepts private messages only from the account that scans the connection QR code. They share the same session, identity, and execution mechanics but install differently.
## Choose a platform
@@ -39,6 +39,8 @@ Step-by-step guides:
- [DingTalk Bot integration](/dingtalk-bot-integration)
- [Telegram Bot integration](/telegram-bot-integration)
+[WeChat Bot](/weixin-bot-integration) connects by QR code and binds the scanner to the initiating Multica user. It does not use the first-message binding-link flow below.
+
## How a message is processed
1. Multica resolves the Bot to its workspace and agent.
@@ -97,6 +99,7 @@ MULTICA_SLACK_SECRET_KEY=<base64-encoded 32-byte key>
MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>
MULTICA_WECOM_SECRET_KEY=<base64-encoded 32-byte key>
MULTICA_TELEGRAM_SECRET_KEY=<base64-encoded 32-byte key>
+MULTICA_WEIXIN_SECRET_KEY=<base64-encoded 32-byte key>
```
These keys encrypt stored Bot credentials. See [Environment variables](/environment-variables) for how to generate, store, and rotate them. Multica Cloud already has this configured.
diff --git a/apps/docs/content/docs/channels.zh-Hant.mdx b/apps/docs/content/docs/channels.zh-Hant.mdx
index e6597c117a..a90350c501 100644
--- a/apps/docs/content/docs/channels.zh-Hant.mdx
+++ b/apps/docs/content/docs/channels.zh-Hant.mdx
@@ -1,6 +1,6 @@
---
title: 聊天整合
-description: 把 Multica AI 代理接入飛書、Lark、Slack、釘釘、企業微信或 Telegram,在團隊已有的聊天工具中使用。
+description: 把 Multica AI 代理接入飛書、Lark、Slack、釘釘、企業微信、Telegram 或微信,在團隊已有的聊天工具中使用。
---
import { Callout } from "fumadocs-ui/components/callout";
@@ -8,7 +8,7 @@ import { ChannelChatDemo } from "@/components/demos/channel-chat-demo";
接入聊天工具後,團隊不用開啟 Multica,就能在私聊裡向 AI 代理提問、在群聊中 @ 它,或者直接在聊天視窗建立任務。
-目前支援飛書/Lark、Slack、釘釘、企業微信和 Telegram。它們使用相同的會話、身份和執行機制,但安裝方式不同。
+目前支援飛書/Lark、Slack、釘釘、企業微信、Telegram 和微信。微信只接收掃描連線 QR 碼帳號的私訊。它們使用相同的會話、身份和執行機制,但安裝方式不同。
## 選擇平臺
@@ -39,6 +39,8 @@ Telegram 會把圖片、檔案、影片和音訊作為附件轉交給 AI 代理
- [釘釘 Bot 接入](/dingtalk-bot-integration)
- [Telegram Bot 接入](/telegram-bot-integration)
+[微信 Bot](/weixin-bot-integration) 透過掃碼連線,將掃碼帳號繫結到發起連線的 Multica 使用者,不使用下方首次傳送訊息時的繫結連結流程。
+
## 訊息的執行流程
1. Multica 根據 Bot 找到對應的工作區和 AI 代理。
@@ -97,6 +99,7 @@ MULTICA_SLACK_SECRET_KEY=<base64 編碼的 32 位元組金鑰>
MULTICA_DINGTALK_SECRET_KEY=<base64 編碼的 32 位元組金鑰>
MULTICA_WECOM_SECRET_KEY=<base64 編碼的 32 位元組金鑰>
MULTICA_TELEGRAM_SECRET_KEY=<base64 編碼的 32 位元組金鑰>
+MULTICA_WEIXIN_SECRET_KEY=<base64 編碼的 32 位元組金鑰>
```
這些金鑰用於加密儲存 Bot 憑據。生成、儲存和輪換方法見[環境變數](/environment-variables)。Multica Cloud 已完成這項配置。
diff --git a/apps/docs/content/docs/environment-variables.fr.mdx b/apps/docs/content/docs/environment-variables.fr.mdx
index a96f20286e..ae9d412e43 100644
--- a/apps/docs/content/docs/environment-variables.fr.mdx
+++ b/apps/docs/content/docs/environment-variables.fr.mdx
@@ -192,6 +192,7 @@ Les limites de débit d'authentification nécessitent `REDIS_URL` ; sans cette v
| Lark | `MULTICA_LARK_SECRET_KEY` | Clé de chiffrement des identifiants de 32 octets, encodée en Base64 |
| Slack | `MULTICA_SLACK_SECRET_KEY` | Clé de chiffrement des jetons de 32 octets, encodée en Base64 |
| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | Clé de chiffrement du jeton du bot de 32 octets, encodée en Base64 |
+| WeChat | `MULTICA_WEIXIN_SECRET_KEY` | Clé de 32 octets encodée en Base64 pour chiffrer les identifiants WeChat et l’état du QR code |
| Telegram | `MULTICA_TELEGRAM_TOOL_PROGRESS` | Étapes d'outils affichées dans la réponse diffusée : `auto` (par défaut : détails en conversation privée, type de travail dans les groupes), `off`, `summary` ou `detail` |
| Composio | `COMPOSIO_API_KEY` | Active les connexions d'outils Composio |
| Composio | `COMPOSIO_CALLBACK_BASE_URL` | URL de l'API de rappel ; peut se rabattre sur `MULTICA_PUBLIC_URL` |
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index 620d53ec82..0d8269d8c9 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -192,6 +192,7 @@ allowlist の正確な判定順序は[ログインとサインアップ](/auth-s
| Lark | `MULTICA_LARK_SECRET_KEY` | base64 エンコードされた 32 バイトの資格情報暗号化キー |
| Slack | `MULTICA_SLACK_SECRET_KEY` | base64 エンコードされた 32 バイトの token 暗号化キー |
| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | base64 エンコードされた 32 バイトの Bot token 暗号化キー |
+| WeChat | `MULTICA_WEIXIN_SECRET_KEY` | WeChat の認証情報と QR 状態を暗号化する Base64 エンコードの 32 バイトキー |
| Telegram | `MULTICA_TELEGRAM_TOOL_PROGRESS` | ストリーミング返信に表示するツールのステップ。`auto`(既定。DM では詳細、グループでは作業の種類のみ)、`off`、`summary`、`detail` |
| Composio | `COMPOSIO_API_KEY` | Composio ツール接続を有効化 |
| Composio | `COMPOSIO_CALLBACK_BASE_URL` | コールバック API アドレス。`MULTICA_PUBLIC_URL` にフォールバック可能 |
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index 3ae7834b7a..a8bfdee65f 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -192,6 +192,7 @@ reverse proxy 뒤에 배포한다면 실제 proxy 네트워크를 입력해야
| Feishu | `MULTICA_LARK_SECRET_KEY` | base64로 인코딩한 32바이트 자격 증명 암호화 키 |
| Slack | `MULTICA_SLACK_SECRET_KEY` | base64로 인코딩한 32바이트 token 암호화 키 |
| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | base64로 인코딩한 32바이트 Bot token 암호화 키 |
+| WeChat | `MULTICA_WEIXIN_SECRET_KEY` | WeChat 자격 증명과 QR 상태를 암호화하는 Base64 인코딩 32바이트 키 |
| Telegram | `MULTICA_TELEGRAM_TOOL_PROGRESS` | 스트리밍 응답에 표시할 도구 단계. `auto`(기본값: 개인 채팅은 상세, 그룹은 작업 종류만), `off`, `summary`, `detail` |
| Composio | `COMPOSIO_API_KEY` | Composio 도구 연결 활성화 |
| Composio | `COMPOSIO_CALLBACK_BASE_URL` | callback API 주소. `MULTICA_PUBLIC_URL`로 fallback 가능 |
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 661d72f500..88f2801852 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -192,6 +192,7 @@ The auth rate limits require `REDIS_URL`; without it, the startup log notes that
| Lark | `MULTICA_LARK_SECRET_KEY` | Base64-encoded 32-byte credential encryption key |
| Slack | `MULTICA_SLACK_SECRET_KEY` | Base64-encoded 32-byte token encryption key |
| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | Base64-encoded 32-byte Bot token encryption key |
+| WeChat | `MULTICA_WEIXIN_SECRET_KEY` | Base64-encoded 32-byte encryption key for WeChat bot credentials and QR state |
| Telegram | `MULTICA_TELEGRAM_TOOL_PROGRESS` | Tool steps shown in the streamed reply: `auto` (default: details in private chats, kind of work in groups), `off`, `summary` or `detail` |
| Composio | `COMPOSIO_API_KEY` | Enables Composio tool connections |
| Composio | `COMPOSIO_CALLBACK_BASE_URL` | Callback API URL; can fall back to `MULTICA_PUBLIC_URL` |
diff --git a/apps/docs/content/docs/environment-variables.zh-Hant.mdx b/apps/docs/content/docs/environment-variables.zh-Hant.mdx
index bbe5f09a72..d6c3a7d4a6 100644
--- a/apps/docs/content/docs/environment-variables.zh-Hant.mdx
+++ b/apps/docs/content/docs/environment-variables.zh-Hant.mdx
@@ -188,6 +188,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| 飛書 | `MULTICA_LARK_SECRET_KEY` | base64 編碼的 32 位元組憑據加密金鑰 |
| Slack | `MULTICA_SLACK_SECRET_KEY` | base64 編碼的 32 位元組 token 加密金鑰 |
| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | base64 編碼的 32 位元組 Bot token 加密金鑰 |
+| 微信 | `MULTICA_WEIXIN_SECRET_KEY` | base64 編碼的 32 位元組金鑰,用於加密 iLink 憑據、登入狀態與回覆上下文;未設定時不開放微信連線 |
| Telegram | `MULTICA_TELEGRAM_TOOL_PROGRESS` | 流式回覆中展示的工具步驟:`auto`(預設,私聊顯示細節,群聊只顯示工作型別)、`off`、`summary` 或 `detail` |
| Composio | `COMPOSIO_API_KEY` | 啟用 Composio 工具連線 |
| Composio | `COMPOSIO_CALLBACK_BASE_URL` | 回撥 API 地址;可回退到 `MULTICA_PUBLIC_URL` |
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index 3f2758ebaa..4030e2809f 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -192,6 +192,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| 飞书 | `MULTICA_LARK_SECRET_KEY` | base64 编码的 32 字节凭据加密密钥 |
| Slack | `MULTICA_SLACK_SECRET_KEY` | base64 编码的 32 字节 token 加密密钥 |
| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | base64 编码的 32 字节 Bot token 加密密钥 |
+| WeChat | `MULTICA_WEIXIN_SECRET_KEY` | Base64 编码的 32 字节密钥,加密微信机器人凭据和扫码状态 |
| Telegram | `MULTICA_TELEGRAM_TOOL_PROGRESS` | 流式回复中展示的工具步骤:`auto`(默认,私聊显示细节,群聊只显示工作类型)、`off`、`summary` 或 `detail` |
| Composio | `COMPOSIO_API_KEY` | 启用 Composio 工具连接 |
| Composio | `COMPOSIO_CALLBACK_BASE_URL` | 回调 API 地址;可回退到 `MULTICA_PUBLIC_URL` |
diff --git a/apps/docs/content/docs/meta.fr.json b/apps/docs/content/docs/meta.fr.json
index 3cf441b934..78fbe522d8 100644
--- a/apps/docs/content/docs/meta.fr.json
+++ b/apps/docs/content/docs/meta.fr.json
@@ -47,6 +47,7 @@
"slack-bot-integration",
"dingtalk-bot-integration",
"telegram-bot-integration",
+ "weixin-bot-integration",
"github-integration",
"vcs-integration",
"---Applications---",
diff --git a/apps/docs/content/docs/meta.ja.json b/apps/docs/content/docs/meta.ja.json
index 7f0e056161..323faddbba 100644
--- a/apps/docs/content/docs/meta.ja.json
+++ b/apps/docs/content/docs/meta.ja.json
@@ -47,6 +47,7 @@
"slack-bot-integration",
"dingtalk-bot-integration",
"telegram-bot-integration",
+ "weixin-bot-integration",
"github-integration",
"vcs-integration",
"---アプリ---",
diff --git a/apps/docs/content/docs/meta.json b/apps/docs/content/docs/meta.json
index 488132164e..d67506796d 100644
--- a/apps/docs/content/docs/meta.json
+++ b/apps/docs/content/docs/meta.json
@@ -47,6 +47,7 @@
"slack-bot-integration",
"dingtalk-bot-integration",
"telegram-bot-integration",
+ "weixin-bot-integration",
"github-integration",
"vcs-integration",
"---Apps---",
diff --git a/apps/docs/content/docs/meta.ko.json b/apps/docs/content/docs/meta.ko.json
index 6f61ec9b85..6aaf859571 100644
--- a/apps/docs/content/docs/meta.ko.json
+++ b/apps/docs/content/docs/meta.ko.json
@@ -47,6 +47,7 @@
"slack-bot-integration",
"dingtalk-bot-integration",
"telegram-bot-integration",
+ "weixin-bot-integration",
"github-integration",
"vcs-integration",
"---앱---",
diff --git a/apps/docs/content/docs/meta.zh-Hant.json b/apps/docs/content/docs/meta.zh-Hant.json
index 75aaa25a34..3eadbc64cc 100644
--- a/apps/docs/content/docs/meta.zh-Hant.json
+++ b/apps/docs/content/docs/meta.zh-Hant.json
@@ -46,6 +46,7 @@
"lark-bot-integration",
"slack-bot-integration",
"dingtalk-bot-integration",
+ "weixin-bot-integration",
"telegram-bot-integration",
"github-integration",
"vcs-integration",
diff --git a/apps/docs/content/docs/meta.zh.json b/apps/docs/content/docs/meta.zh.json
index 23ec6c4a15..b3c3240560 100644
--- a/apps/docs/content/docs/meta.zh.json
+++ b/apps/docs/content/docs/meta.zh.json
@@ -47,6 +47,7 @@
"slack-bot-integration",
"dingtalk-bot-integration",
"telegram-bot-integration",
+ "weixin-bot-integration",
"github-integration",
"vcs-integration",
"---客户端---",
diff --git a/apps/docs/content/docs/weixin-bot-integration.mdx b/apps/docs/content/docs/weixin-bot-integration.mdx
new file mode 100644
index 0000000000..361a9aa4ed
--- /dev/null
+++ b/apps/docs/content/docs/weixin-bot-integration.mdx
@@ -0,0 +1,55 @@
+---
+title: WeChat Bot
+description: Scan a QR code to connect your WeChat account to a Multica agent through iLink.
+---
+
+Multica connects to WeChat's iLink Bot service using the protocol implemented by Tencent's [OpenClaw Weixin plugin](https://github.com/Tencent/openclaw-weixin). This is a separate channel from WeCom. You do not need to install OpenClaw or run a desktop WeChat automation tool.
+
+## Connect
+
+1. Sign in as a workspace owner or admin. Open an agent, choose **Add messaging channel** under **Messaging**, select **WeChat**, then select **Connect WeChat**.
+2. Scan the QR code with **your own** WeChat account and confirm on your phone. If WeChat requests a numeric verification code, enter it in the dialog.
+3. Send a new private message to the bot in WeChat. The agent needs an online runtime to execute work.
+
+The account that scans is linked to the Multica user who opened this dialog. Its messages execute with that user's workspace permissions. Do not share the QR code or ask someone else to scan it. Other WeChat accounts and group messages are not accepted.
+
+The login window lasts at most five minutes; the provider can expire a code sooner. Generate a new QR code after expiry. Closing the dialog cancels the pending login. A bot already connected to another agent or workspace must be disconnected there first. WeChat controls account eligibility and may refuse or challenge a connection.
+
+![WeChat QR login in an agent's settings](/images/docs/weixin/qr-login.png)
+
+The QR code in this illustration is a test fixture, not a live authorization code.
+
+## Messages and commands
+
+- Text messages continue the same Multica chat. Final answers return to WeChat in plain text; long answers are split into Unicode-safe messages. There is no streaming message editing.
+- While the agent works, Multica renews WeChat's typing indicator when available. It stops after completion, failure, or cancellation. A failed renewal is retried at the next five-second interval. Missing typing permission or a failed indicator request does not interrupt messages or replies.
+- `/new [message]` starts a new Multica chat. `/clear [message]` resets agent-visible context in the current chat. `/issue <title>` creates an issue assigned to the connected agent.
+- With object storage configured, incoming images, files, video, and untranscribed voice notes are attached to the Multica chat. Voice transcription supplied by WeChat is used as text; Multica does not add a speech-to-text service or convert SILK audio.
+- Files attached to an agent's final answer return to WeChat. Supported images and MP4 video use native media messages; other formats, including audio, use file messages. Each transfer is limited to **20 MiB** by this adapter. A failed outgoing file transfer produces a notice; the file remains in Multica.
+- Group chats, contact access, proactive notifications, forwarded-message expansion, and fetching quoted-message history are not supported.
+
+Replies require the context credential issued by WeChat for this conversation. If a reply is rejected because its context has expired, send a new message. Multica does not assume a fixed context lifetime. A successful API response means provider acceptance, not proof of delivery or reading. If a send response is lost, Multica records an unknown outcome and does not resend it automatically.
+
+Under heavy load, a WeChat reply notification may be skipped; the answer remains available in the Multica chat.
+
+## Disconnect
+
+Use **Manage WeChat → Disconnect** in the agent's **Messaging** section. New messages stop reaching the agent and the saved reply context is removed. Multica chat history remains available. An explicit iLink authorization-expired response also disables the connection and shows an expired-authorization notice; reconnect by scanning a new QR code. Reauthorizing an existing connection to the same agent preserves its chat and receive cursor. When a bot is already connected to another agent in this workspace, the connection dialog names that agent so you can disconnect it there first; other workspaces' agent identities remain private.
+
+![Connected WeChat account in workspace messaging settings](/images/docs/weixin/connected.png)
+
+## Self-hosting
+
+Generate a persistent encryption key:
+
+```sh
+openssl rand -base64 32
+```
+
+Store it as `MULTICA_WEIXIN_SECRET_KEY` on the API server and restart the server. Use the same key on every replica. Keep it with your deployment secrets and backups; changing it prevents existing credentials from being decrypted and requires reconnecting the bots. Without this key, connection controls are disabled. Docker Compose passes this variable through.
+
+The API server needs outbound HTTPS access to `ilinkai.weixin.qq.com`, WeChat's returned `*.weixin.qq.com` regional hosts, and `novac2c.cdn.weixin.qq.com`. No public webhook or inbound tunnel is needed. Browser clients receive only the QR display content and status; bot credentials and reply context are encrypted at rest on the server.
+
+Apply the normal database migrations. The shared channel supervisor owns one long poll per installation across replicas, and the update cursor is saved after the shared inbound engine accepts a batch. Final replies use the shared database delivery lease to avoid duplicate sends. Pending outbound events are in memory: a server restart can interrupt a reply, and an ambiguous send is intentionally not replayed. The answer and attachments remain in Multica.
+
+Protocol reference: Tencent `@tencent-weixin/openclaw-weixin` **2.4.10**, source commit [`874637a`](https://github.com/Tencent/openclaw-weixin/tree/874637a0dbc24050f72d1385add4fc6170a2d726), including its [protocol documentation](https://github.com/Tencent/openclaw-weixin/blob/874637a0dbc24050f72d1385add4fc6170a2d726/docs/protocol_zh_CN.md). This adapter is a native Go implementation and has no runtime dependency on that package. Provider behavior and account eligibility can change independently of Multica releases.
diff --git a/apps/docs/content/docs/weixin-bot-integration.zh-Hant.mdx b/apps/docs/content/docs/weixin-bot-integration.zh-Hant.mdx
new file mode 100644
index 0000000000..16300512f6
--- /dev/null
+++ b/apps/docs/content/docs/weixin-bot-integration.zh-Hant.mdx
@@ -0,0 +1,49 @@
+---
+title: 微信 Bot
+description: 掃碼透過 iLink 將微信帳號連接到 Multica AI 代理。
+---
+
+Multica 參考騰訊 [OpenClaw Weixin 外掛](https://github.com/Tencent/openclaw-weixin) 的協定,直接連接微信 iLink Bot 服務。這與企業微信渠道獨立,不需要安裝 OpenClaw,也不透過桌面微信自動化收發訊息。
+
+## 連線
+
+1. 以工作區 owner 或 admin 身分登入,開啟 AI 代理,在 "訊息渠道" 中選擇 "新增訊息管道",選擇微信後點選 "連接微信"。
+2. 用**你自己的微信帳號**掃碼,並在手機上確認。微信要求驗證碼時,在彈窗中輸入手機顯示的數字。
+3. 在微信中向機器人傳送一條新私訊。AI 代理需要線上的執行環境才能執行任務。
+
+掃碼的微信帳號會繫結到發起連線的 Multica 使用者,訊息按該使用者的工作區權限執行。請勿分享 QR 碼或讓他人代掃。其他微信帳號和群聊訊息不會被接收。
+
+登入視窗最多保留五分鐘,微信也可能提前讓 QR 碼失效。過期後重新產生即可。關閉彈窗會取消待確認的登入。已連接到其他 AI 代理或工作區的機器人必須先中斷原連線。帳號是否可用由微信決定,微信可能要求驗證或拒絕連線。
+
+## 訊息與命令
+
+- 文字訊息會繼續同一個 Multica 聊天,最終回覆以純文字返回微信。長回覆按完整 Unicode 字元分段,不提供串流編輯。
+- AI 代理執行期間,微信支援時會顯示「正在輸入」,完成、失敗或取消後停止提示。單次續期失敗後,會在下一個 5 秒週期繼續嘗試。無法取得輸入狀態憑證或提示請求失敗,不影響正常收發。
+- `/new [訊息]` 新建聊天;`/clear [訊息]` 重設目前聊天的 AI 代理上下文;`/issue <標題>` 建立任務並分配給此 AI 代理。
+- 配置物件儲存後,圖片、檔案、影片和未轉寫的語音會作為附件進入聊天。微信提供的語音轉寫作為文字處理;Multica 不額外提供語音辨識,也不轉換 SILK 音訊。
+- AI 代理最終回覆中的附件會傳送回微信。支援的圖片和 MP4 影片使用原生媒體訊息,其他格式(包括音訊)使用檔案訊息。本適配器限制每次傳輸不超過 **20 MiB**。檔案傳送失敗時會提示,檔案仍保留在 Multica 中。
+- 暫不支援群聊、通訊錄、主動通知、展開合併轉傳訊息或讀取引用訊息的歷史內文。
+
+回覆需要微信簽發的目前會話上下文憑據。如果上下文過期導致拒絕傳送,請傳送一條新訊息。Multica 不假定固定的上下文有效期。API 成功僅表示微信接受了請求,不代表對方已收到或已讀;傳送回應遺失時記錄為結果不明,不自動重傳。
+
+負載過高時,微信回覆推播可能被略過;完整答案仍保存在 Multica 聊天中。
+
+## 中斷連線
+
+在 AI 代理的 "訊息渠道" 中選擇 "管理微信 → 中斷連接"。新訊息停止進入 AI 代理,已儲存的回覆上下文會刪除,Multica 聊天記錄保留。微信明確返回授權過期時也會停用連線並顯示授權過期提示,需要重新掃碼。重複授權同一 AI 代理的現有連線會保留聊天和接收游標。如果機器人已連接本工作區的其他 AI 代理,彈窗會指出該 AI 代理,請先在該處中斷連線;其他工作區的 AI 代理資訊不會顯示。
+
+## 自託管配置
+
+產生一個持久儲存的加密金鑰:
+
+```sh
+openssl rand -base64 32
+```
+
+將結果配置為 API 服務的 `MULTICA_WEIXIN_SECRET_KEY`,然後重新啟動服務。所有副本使用相同金鑰,並與部署金鑰和備份一起妥善儲存。更換金鑰會導致原憑據無法解密,需要重新連接機器人。未配置時不開放連線入口,Docker Compose 已傳遞此變數。
+
+API 服務需要透過 HTTPS 存取 `ilinkai.weixin.qq.com`、微信返回的 `*.weixin.qq.com` 區域位址和 `novac2c.cdn.weixin.qq.com`。無需公網 webhook 或入站通道。瀏覽器只接收 QR 碼顯示內容及狀態;機器人憑據和回覆上下文在伺服器端加密儲存。
+
+執行常規資料庫遷移。共用渠道管理器跨副本確保每個安裝只有一條長輪詢,入站引擎接受整個批次後才儲存游標。最終回覆透過資料庫投遞租約去重。待傳送事件位於記憶體中,服務重新啟動可能中斷回覆;結果不明的傳送不會重播,答案與附件仍可在 Multica 檢視。
+
+協定參考:騰訊 `@tencent-weixin/openclaw-weixin` **2.4.10**,原始碼提交 [`874637a`](https://github.com/Tencent/openclaw-weixin/tree/874637a0dbc24050f72d1385add4fc6170a2d726) 及其[協定文件](https://github.com/Tencent/openclaw-weixin/blob/874637a0dbc24050f72d1385add4fc6170a2d726/docs/protocol_zh_CN.md)。本適配器由 Go 原生實作,不依賴該外掛執行。微信的協定行為和帳號資格可能獨立於 Multica 版本變更。
diff --git a/apps/docs/content/docs/weixin-bot-integration.zh.mdx b/apps/docs/content/docs/weixin-bot-integration.zh.mdx
new file mode 100644
index 0000000000..fdcf7a64cd
--- /dev/null
+++ b/apps/docs/content/docs/weixin-bot-integration.zh.mdx
@@ -0,0 +1,49 @@
+---
+title: 微信 Bot
+description: 扫码通过 iLink 将微信账号连接到 Multica 智能体。
+---
+
+Multica 参考腾讯 [OpenClaw Weixin 插件](https://github.com/Tencent/openclaw-weixin) 的协议,直接连接微信 iLink Bot 服务。这与企业微信通道独立,不需要安装 OpenClaw,也不通过桌面微信自动化收发消息。
+
+## 连接
+
+1. 以工作区所有者或管理员身份登录,打开智能体,在「消息渠道」中选择「添加消息渠道」,选择微信后点击「连接微信」。
+2. 用**你自己的微信账号**扫码,并在手机上确认。微信要求验证码时,在弹窗中输入手机显示的数字。
+3. 在微信中向机器人发送一条新私聊消息。智能体需要在线的运行环境才能执行任务。
+
+扫码的微信账号会绑定到发起连接的 Multica 用户,消息按该用户的工作区权限执行。请勿分享二维码或让他人代扫。其他微信账号和群聊消息不会被接收。
+
+登录窗口最长保留五分钟,微信也可能提前让二维码失效。过期后重新生成即可。关闭弹窗会取消待确认的登录。已连接到其他智能体或工作区的机器人必须先断开原连接。账号是否可用由微信决定,微信可能要求验证或拒绝连接。
+
+## 消息与命令
+
+- 文字消息会继续同一个 Multica 聊天,最终回复以纯文本返回微信。长回复按完整 Unicode 字符分段,不提供流式编辑。
+- 智能体运行期间,微信支持时会显示「正在输入」,完成、失败或取消后停止提示。单次续期失败后,会在下一个 5 秒周期继续尝试。无法获取输入状态凭据或提示请求失败,不影响正常收发。
+- `/new [消息]` 新建聊天;`/clear [消息]` 重置当前聊天的智能体上下文;`/issue <标题>` 创建任务并分配给此智能体。
+- 配置对象存储后,图片、文件、视频和未转写的语音会作为附件进入聊天。微信提供的语音转写作为文字处理;Multica 不额外提供语音识别,也不转换 SILK 音频。
+- 智能体最终回复中的附件会发送回微信。支持的图片和 MP4 视频使用原生媒体消息,其他格式(包括音频)使用文件消息。本适配器限制每次传输不超过 **20 MiB**。文件发送失败时会提示,文件仍保留在 Multica 中。
+- 暂不支持群聊、通讯录、主动通知、展开合并转发消息或读取引用消息的历史正文。
+
+回复需要微信签发的当前会话上下文凭据。如果上下文过期导致拒绝发送,请发一条新消息。Multica 不假定固定的上下文有效期。API 成功仅表示微信接受了请求,不代表对方已收到或已读;发送响应丢失时记录为结果不明,不自动重发。
+
+负载过高时,微信回复推送可能被跳过;完整答案仍保存在 Multica 聊天中。
+
+## 断开连接
+
+在智能体的「消息渠道」中选择「管理微信 → 断开连接」。新消息停止进入智能体,已保存的回复上下文会删除,Multica 聊天记录保留。微信明确返回授权过期时也会停用连接并显示授权过期提示,需要重新扫码。重复授权同一智能体的现有连接会保留聊天和接收游标。如果机器人已连接本工作区的另一个智能体,弹窗会指出该智能体,请先在那里断开;其他工作区的智能体信息不会显示。
+
+## 自托管配置
+
+生成一个持久保存的加密密钥:
+
+```sh
+openssl rand -base64 32
+```
+
+将结果配置为 API 服务的 `MULTICA_WEIXIN_SECRET_KEY`,然后重启服务。所有副本使用相同密钥,并与部署密钥和备份一起妥善保存。更换密钥会导致原凭据无法解密,需要重新连接机器人。未配置时不开放连接入口,Docker Compose 已透传此变量。
+
+API 服务需要通过 HTTPS 访问 `ilinkai.weixin.qq.com`、微信返回的 `*.weixin.qq.com` 区域地址和 `novac2c.cdn.weixin.qq.com`。无需公网 webhook 或入站隧道。浏览器只接收二维码展示内容及状态;机器人凭据和回复上下文在服务端加密保存。
+
+执行常规数据库迁移。共用通道管理器跨副本保证每个安装只有一条长轮询,入站引擎接受整个批次后才保存游标。最终回复通过数据库投递租约去重。待发送事件位于内存中,服务重启可能中断回复;结果不明的发送不会重放,答案与附件仍可在 Multica 查看。
+
+协议参考:腾讯 `@tencent-weixin/openclaw-weixin` **2.4.10**,源码提交 [`874637a`](https://github.com/Tencent/openclaw-weixin/tree/874637a0dbc24050f72d1385add4fc6170a2d726) 及其[协议文档](https://github.com/Tencent/openclaw-weixin/blob/874637a0dbc24050f72d1385add4fc6170a2d726/docs/protocol_zh_CN.md)。本适配器由 Go 原生实现,不依赖该插件运行。微信的协议行为和账号资格可能独立于 Multica 版本变化。
diff --git a/apps/docs/public/images/docs/weixin/before-connect.png b/apps/docs/public/images/docs/weixin/before-connect.png
new file mode 100644
index 0000000000..8a17dd84b9
Binary files /dev/null and b/apps/docs/public/images/docs/weixin/before-connect.png differ
diff --git a/apps/docs/public/images/docs/weixin/connected.png b/apps/docs/public/images/docs/weixin/connected.png
new file mode 100644
index 0000000000..1f0a297218
Binary files /dev/null and b/apps/docs/public/images/docs/weixin/connected.png differ
diff --git a/apps/docs/public/images/docs/weixin/qr-login.png b/apps/docs/public/images/docs/weixin/qr-login.png
new file mode 100644
index 0000000000..80a42a1b0a
Binary files /dev/null and b/apps/docs/public/images/docs/weixin/qr-login.png differ
diff --git a/apps/web/features/landing/i18n/en.ts b/apps/web/features/landing/i18n/en.ts
index c6baca961e..fb19b674b5 100644
--- a/apps/web/features/landing/i18n/en.ts
+++ b/apps/web/features/landing/i18n/en.ts
@@ -9,6 +9,7 @@ export function createEnDict(): LandingDict {
label: "FAQ",
headline: "Questions & answers.",
items: [
+ { question: "Can I chat with an agent from WeChat?", answer: "Yes. A workspace admin can connect an agent by scanning a WeChat QR code from its Integrations tab. Private messages from the scanning account run with that admin’s workspace permissions. Replies and supported attachments return to the same conversation. Group chats are not supported; self-hosted servers must enable the WeChat integration." },
{
question: "What coding agents does Multica support?",
answer:
diff --git a/apps/web/features/landing/i18n/ja.ts b/apps/web/features/landing/i18n/ja.ts
index 20828f868f..db581590fa 100644
--- a/apps/web/features/landing/i18n/ja.ts
+++ b/apps/web/features/landing/i18n/ja.ts
@@ -13,6 +13,7 @@ export function createJaDict(): LandingDict {
label: "FAQ",
headline: "よくある質問。",
items: [
+ { question: "WeChat からエージェントとチャットできますか?", answer: "はい。ワークスペース管理者がエージェントの「連携」タブで自分の WeChat アカウントを使って QR コードを読み取ると接続できます。そのアカウントからの個別メッセージは管理者の権限で実行され、返信と対応する添付ファイルが同じ会話に届きます。グループチャットは非対応です。セルフホストでは WeChat 連携を有効にする必要があります。" },
{
question: "Multica はどのコーディングエージェントに対応していますか?",
answer:
diff --git a/apps/web/features/landing/i18n/ko.ts b/apps/web/features/landing/i18n/ko.ts
index ed66c122cc..fbc5434712 100644
--- a/apps/web/features/landing/i18n/ko.ts
+++ b/apps/web/features/landing/i18n/ko.ts
@@ -13,6 +13,7 @@ export function createKoDict(): LandingDict {
label: "FAQ",
headline: "자주 묻는 질문.",
items: [
+ { question: "WeChat에서 에이전트와 채팅할 수 있나요?", answer: "네. 워크스페이스 관리자가 에이전트의 연동 탭에서 본인의 WeChat 계정으로 QR 코드를 스캔하면 연결됩니다. 스캔한 계정의 개인 메시지는 해당 관리자의 권한으로 실행되며 답변과 지원되는 첨부 파일이 같은 대화로 돌아옵니다. 그룹 채팅은 지원하지 않으며 자체 호스팅 서버에서는 WeChat 연동을 먼저 활성화해야 합니다." },
{
question: "Multica는 어떤 코딩 에이전트를 지원하나요?",
answer:
diff --git a/apps/web/features/landing/i18n/zh.ts b/apps/web/features/landing/i18n/zh.ts
index 44ac22888b..93b43c5b80 100644
--- a/apps/web/features/landing/i18n/zh.ts
+++ b/apps/web/features/landing/i18n/zh.ts
@@ -9,6 +9,7 @@ export function createZhDict(): LandingDict {
label: "\u5e38\u89c1\u95ee\u9898",
headline: "\u95ee\u4e0e\u7b54\u3002",
items: [
+ { question: "可以在微信里与智能体聊天吗?", answer: "可以。工作区管理员在智能体的「集成」页签中用自己的微信扫码连接,扫码账号的私聊消息会按该管理员的工作区权限执行,回复和支持的附件会返回同一会话。暂不支持群聊;自托管服务需先启用微信集成。" },
{
question: "Multica \u652f\u6301\u54ea\u4e9b\u7f16\u7801 智能体\uff1f",
answer:
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 158d4301c0..54d3688280 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -236,6 +236,7 @@ services:
# (bot_token_encrypted), so this single deployment-wide key is all
# the operator needs to set here.
MULTICA_TELEGRAM_SECRET_KEY: ${MULTICA_TELEGRAM_SECRET_KEY:-}
+ MULTICA_WEIXIN_SECRET_KEY: ${MULTICA_WEIXIN_SECRET_KEY:-}
# Tool steps shown in the streamed reply: auto (default; details in
# private chats, kind of work in groups), off, summary or detail.
MULTICA_TELEGRAM_TOOL_PROGRESS: ${MULTICA_TELEGRAM_TOOL_PROGRESS:-}
diff --git a/e2e/weixin.spec.ts b/e2e/weixin.spec.ts
new file mode 100644
index 0000000000..396b76427d
--- /dev/null
+++ b/e2e/weixin.spec.ts
@@ -0,0 +1,159 @@
+import { test, expect } from "@playwright/test";
+import { TestApiClient } from "./fixtures";
+
+// Real Multica login and workspace with a fixture agent and channel responses.
+// Never needs a WeChat account or launches an agent CLI.
+test("WeChat QR verification, connection listing, and disconnect", async ({
+ page,
+}, testInfo) => {
+ const api = new TestApiClient();
+ const run = `${Date.now()}-${process.pid}`;
+ const identity = await api.login(
+ `e2e-weixin-${run}@multica.ai`,
+ "WeChat E2E",
+ );
+ const workspace = await api.ensureWorkspace("WeChat review", `weixin-${run}`);
+ await api.markUserOnboarded();
+ const token = api.getToken();
+ if (!token) throw new Error("test login returned no token");
+ await page.addInitScript((value) => {
+ localStorage.setItem("multica_token", value);
+ localStorage.setItem("multica:chat:isOpen", "false");
+ }, token);
+ const agentID = "11111111-1111-4111-8111-111111111111";
+ const agent = {
+ id: agentID,
+ workspace_id: workspace.id,
+ owner_id: identity.user.id,
+ name: "WeChat Assistant",
+ description: "",
+ instructions: "",
+ status: "idle",
+ runtime_mode: "local",
+ runtime_config: {},
+ custom_args: [],
+ visibility: "workspace",
+ max_concurrent_tasks: 1,
+ model: "",
+ skills: [],
+ archived_at: null,
+ created_at: "2026-11-03T00:00:00Z",
+ updated_at: "2026-11-03T00:00:00Z",
+ };
+ let connected = false;
+ let polls = 0;
+ const login = {
+ id: "22222222-2222-4222-8222-222222222222",
+ status: "wait",
+ qr_code_url: "https://weixin.qq.com/multica-test-fixture-not-a-live-login",
+ expires_at: new Date(Date.now() + 300_000).toISOString(),
+ };
+ await page.route("**/api/agents**", (route) => {
+ const url = new URL(route.request().url());
+ if (url.pathname.endsWith("/api/agents"))
+ return route.fulfill({ json: [agent] });
+ if (url.pathname.endsWith(`/api/agents/${agentID}`))
+ return route.fulfill({ json: agent });
+ return route.fallback();
+ });
+ await page.route("**/weixin/**", (route) => {
+ const request = route.request();
+ const url = new URL(request.url());
+ if (request.method() === "DELETE") {
+ connected = false;
+ return route.fulfill({ status: 204 });
+ }
+ if (url.pathname.endsWith("/installations"))
+ return route.fulfill({
+ json: {
+ configured: true,
+ install_supported: true,
+ installations: connected
+ ? [
+ {
+ id: "bot-1",
+ workspace_id: workspace.id,
+ agent_id: agentID,
+ status: "active",
+ bot_id: "test-bot",
+ user_id: "test-scanner",
+ installed_at: new Date().toISOString(),
+ },
+ ]
+ : [],
+ },
+ });
+ if (url.pathname.endsWith("/logins")) return route.fulfill({ json: login });
+ if (url.pathname.endsWith("/poll")) {
+ const body = request.postDataJSON();
+ if (body.verify_code) {
+ expect(body.verify_code).toBe("001234");
+ connected = true;
+ return route.fulfill({
+ json: {
+ ...login,
+ status: "confirmed",
+ installation_id: "bot-1",
+ qr_code_url: undefined,
+ },
+ });
+ }
+ polls++;
+ return route.fulfill({
+ json: { ...login, status: polls > 1 ? "confirmed_but_need_verifycode" : "scaned" },
+ });
+ }
+ return route.fallback();
+ });
+ try {
+ await page.goto(`/${workspace.slug}/agents/${agentID}`, {
+ waitUntil: "domcontentloaded",
+ });
+ const channels = page.locator("#messaging-channels");
+ await channels.getByRole("button", { name: "Add messaging channel" }).first().click();
+ const connectDialog = page.getByRole("dialog", { name: "Connect messaging channel" });
+ await connectDialog.getByRole("button", { name: "WeChat" }).click();
+ await expect(connectDialog.getByRole("button", { name: "Connect WeChat" })).toBeVisible();
+ await page.screenshot({
+ path: testInfo.outputPath("weixin-agent.png"),
+ fullPage: true,
+ });
+ await page
+ .getByRole("button", { name: "Connect WeChat", exact: true })
+ .click();
+ const dialog = page.getByRole("dialog", {
+ name: "Connect WeChat to WeChat Assistant",
+ });
+ await expect(dialog.getByRole("img", { name: "WeChat connection QR code" })).toBeVisible();
+ await page.screenshot({
+ path: testInfo.outputPath("weixin-qr.png"),
+ fullPage: true,
+ });
+ await expect(dialog.getByLabel("Verification code")).toBeVisible();
+ await page.screenshot({
+ path: testInfo.outputPath("weixin-verification.png"),
+ fullPage: true,
+ });
+ await dialog.getByLabel("Verification code").fill("001234");
+ await dialog.getByRole("button", { name: "Verify", exact: true }).click();
+ await expect(connectDialog.getByText("Connected", { exact: true })).toBeVisible();
+ await connectDialog.getByRole("button", { name: "Close" }).click();
+ await expect(page.getByRole("button", { name: "Manage WeChat" })).toBeVisible();
+ await page.goto(
+ `/${workspace.slug}/settings?tab=channels&integration=weixin`,
+ { waitUntil: "domcontentloaded" },
+ );
+ await expect(page.getByRole("link", { name: "WeChat Assistant" })).toBeVisible({ timeout: 30_000 });
+ await page.screenshot({
+ path: testInfo.outputPath("weixin-connected.png"),
+ fullPage: true,
+ });
+ await page.getByRole("link", { name: "WeChat Assistant" }).click();
+ await page.getByRole("button", { name: "Manage WeChat" }).click();
+ await page.getByRole("menuitem", { name: "Disconnect" }).click();
+ await page.getByRole("alertdialog").getByRole("button", { name: "Disconnect", exact: true }).click();
+ await expect(page.getByRole("button", { name: "Manage WeChat" })).toHaveCount(0);
+ } finally {
+ await api.cleanup();
+ }
+});
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 0def60adba..2a7457d63b 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -1,3 +1,5 @@
+import type { ListWeixinInstallationsResponse, WeixinLogin } from "../types/weixin";
+import { ListWeixinInstallationsSchema, WeixinLoginSchema, EMPTY_WEIXIN_INSTALLATIONS, INVALID_WEIXIN_LOGIN } from "../weixin/schema";
import type { ZodType } from "zod";
import { AgentRuntimeSchema, EMPTY_RUNTIME } from "../runtimes/schema";
import type { IssueWakeup, IssueWakeupInput, IssueWakeupSummaryRow, PausedWakeup, SystemWakeup, WakeupRun, WorkspaceSystemWakeup } from "../types/issue-wakeup";
@@ -6081,6 +6083,30 @@ export class ApiClient {
);
}
+ async listWeixinInstallations(workspaceId: string): Promise<ListWeixinInstallationsResponse> {
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/weixin/installations`);
+ return parseWithFallback(raw, ListWeixinInstallationsSchema, EMPTY_WEIXIN_INSTALLATIONS, { endpoint: "GET /api/workspaces/:id/weixin/installations" });
+ }
+
+ async beginWeixinLogin(workspaceId: string, agentId: string): Promise<WeixinLogin> {
+ const search = new URLSearchParams({ agent_id: agentId });
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/weixin/logins?${search}`, { method: "POST" });
+ return parseWithFallback(raw, WeixinLoginSchema, INVALID_WEIXIN_LOGIN, { endpoint: "POST /api/workspaces/:id/weixin/logins" });
+ }
+
+ async pollWeixinLogin(workspaceId: string, loginId: string, verifyCode = "", signal?: AbortSignal): Promise<WeixinLogin> {
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/weixin/logins/${loginId}/poll`, { method: "POST", body: JSON.stringify({ verify_code: verifyCode }), signal });
+ return parseWithFallback(raw, WeixinLoginSchema, INVALID_WEIXIN_LOGIN, { endpoint: "POST /api/workspaces/:id/weixin/logins/:loginId/poll" });
+ }
+
+ async cancelWeixinLogin(workspaceId: string, loginId: string): Promise<void> {
+ await this.fetch(`/api/workspaces/${workspaceId}/weixin/logins/${loginId}`, { method: "DELETE" });
+ }
+
+ async deleteWeixinInstallation(workspaceId: string, installationId: string): Promise<void> {
+ await this.fetch(`/api/workspaces/${workspaceId}/weixin/installations/${installationId}`, { method: "DELETE" });
+ }
+
async listTelegramInstallations(
workspaceId: string,
): Promise<ListTelegramInstallationsResponse> {
diff --git a/packages/core/package.json b/packages/core/package.json
index 87df9550b1..1a6cff429a 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -169,6 +169,7 @@
"./dingtalk/queries": "./dingtalk/queries.ts",
"./wecom": "./wecom/index.ts",
"./wecom/queries": "./wecom/queries.ts",
+ "./weixin": "./weixin/index.ts",
"./telegram": "./telegram/index.ts",
"./telegram/queries": "./telegram/queries.ts",
"./feedback": "./feedback/index.ts",
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index f4b6eb7328..92fb7975df 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -1,5 +1,8 @@
"use client";
+import { weixinKeys } from "../weixin/queries";
+
+
import { useEffect, useRef } from "react";
import { forgetLocalSearchIndex } from "../search-index/instance";
import { useQueryClient, type InfiniteData, type QueryClient, type QueryFilters } from "@tanstack/react-query";
@@ -1077,6 +1080,10 @@ export function useRealtimeSync(
const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: wecomKeys.installations(wsId) });
},
+ weixin_installation: () => {
+ const wsId = getCurrentWsId();
+ if (wsId) qc.invalidateQueries({ queryKey: weixinKeys.installations(wsId) });
+ },
telegram_installation: () => {
const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: telegramKeys.installations(wsId) });
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 3e566465b1..ab198a820f 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -416,3 +416,5 @@ export type {
export type { IssueWakeup, IssueWakeupInput, SystemWakeup, WorkspaceSystemWakeup, WakeupPreview, IssueWakeupSummaryRow, WakeupCondition, WakeupPausedReason, WakeupRun, PausedWakeup, WakeupSource } from "./issue-wakeup";
export type { WorkspaceWakeup, WorkspaceWakeupPage, WorkspaceWakeupFilters, WakeupScope } from "./issue-wakeup";
+
+export type { WeixinInstallation, ListWeixinInstallationsResponse, WeixinLogin } from "./weixin";
diff --git a/packages/core/types/weixin.ts b/packages/core/types/weixin.ts
new file mode 100644
index 0000000000..fb14cb721c
--- /dev/null
+++ b/packages/core/types/weixin.ts
@@ -0,0 +1,24 @@
+export interface WeixinInstallation {
+ id: string;
+ workspace_id: string;
+ agent_id: string;
+ bot_id: string;
+ user_id: string;
+ installer_user_id: string;
+ status: string;
+ installed_at: string;
+}
+
+export interface ListWeixinInstallationsResponse {
+ installations: WeixinInstallation[];
+ configured: boolean;
+ install_supported?: boolean;
+}
+
+export interface WeixinLogin {
+ id: string;
+ status: string;
+ qr_code_url?: string;
+ installation_id?: string;
+ expires_at: string;
+}
diff --git a/packages/core/weixin/errors.test.ts b/packages/core/weixin/errors.test.ts
new file mode 100644
index 0000000000..8b1ea0c9d0
--- /dev/null
+++ b/packages/core/weixin/errors.test.ts
@@ -0,0 +1,17 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { ApiError } from "../api/client";
+import { weixinConflict } from "./errors";
+
+describe("WeChat conflict responses", () => {
+ it("accepts scoped agent identity and tolerates older or malformed responses", () => {
+ expect(weixinConflict(new ApiError("conflict", 409, "Conflict", {
+ code: "weixin_already_connected", agent_id: "agent-1", agent_name: "Assistant",
+ }))?.agent_name).toBe("Assistant");
+ expect(weixinConflict(new ApiError("conflict", 409, "Conflict", {
+ code: "weixin_already_connected", agent_name: { secret: "invalid" },
+ }))).toEqual({ code: "weixin_already_connected" });
+ expect(weixinConflict(new ApiError("conflict", 409, "Conflict"))).toBeUndefined();
+ expect(weixinConflict(new Error("offline"))).toBeUndefined();
+ });
+});
diff --git a/packages/core/weixin/errors.ts b/packages/core/weixin/errors.ts
new file mode 100644
index 0000000000..c956569b1c
--- /dev/null
+++ b/packages/core/weixin/errors.ts
@@ -0,0 +1,14 @@
+import { z } from "zod";
+import { ApiError } from "../api/client";
+
+const WeixinConflictSchema = z.object({
+ code: z.literal("weixin_already_connected"),
+ agent_id: z.string().optional().catch(undefined),
+ agent_name: z.string().optional().catch(undefined),
+});
+
+export function weixinConflict(error: unknown) {
+ if (!(error instanceof ApiError) || error.status !== 409) return undefined;
+ const parsed = WeixinConflictSchema.safeParse(error.body);
+ return parsed.success ? parsed.data : undefined;
+}
diff --git a/packages/core/weixin/index.ts b/packages/core/weixin/index.ts
new file mode 100644
index 0000000000..46b07cbae8
--- /dev/null
+++ b/packages/core/weixin/index.ts
@@ -0,0 +1,3 @@
+export { weixinInstallationsOptions, weixinKeys } from "./queries";
+export { isWeixinLoginPending, isWeixinVerificationRequired } from "./schema";
+export { weixinConflict } from "./errors";
diff --git a/packages/core/weixin/queries.ts b/packages/core/weixin/queries.ts
new file mode 100644
index 0000000000..74d766facc
--- /dev/null
+++ b/packages/core/weixin/queries.ts
@@ -0,0 +1,17 @@
+import { queryOptions } from "@tanstack/react-query";
+import { api } from "../api";
+
+export const weixinKeys = {
+ all: (wsId: string) => ["weixin", wsId] as const,
+ installations: (wsId: string) =>
+ [...weixinKeys.all(wsId), "installations"] as const,
+ login: (wsId: string, id: string) =>
+ [...weixinKeys.all(wsId), "login", id] as const,
+};
+
+export const weixinInstallationsOptions = (wsId: string) =>
+ queryOptions({
+ queryKey: weixinKeys.installations(wsId),
+ queryFn: () => api.listWeixinInstallations(wsId),
+ enabled: !!wsId,
+ });
diff --git a/packages/core/weixin/schema.test.ts b/packages/core/weixin/schema.test.ts
new file mode 100644
index 0000000000..5256be5cb4
--- /dev/null
+++ b/packages/core/weixin/schema.test.ts
@@ -0,0 +1,86 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { parseWithFallback } from "../api/schema";
+import {
+ EMPTY_WEIXIN_INSTALLATIONS,
+ INVALID_WEIXIN_LOGIN,
+ ListWeixinInstallationsSchema,
+ WeixinLoginSchema,
+ isWeixinLoginPending,
+} from "./schema";
+
+describe("WeChat API compatibility", () => {
+ it("never treats malformed or partial confirmation as a successful binding", () => {
+ for (const raw of [
+ null,
+ [],
+ {},
+ { id: "login", status: "confirmed" },
+ { id: 1, status: "confirmed", installation_id: "bot" },
+ ]) {
+ expect(
+ parseWithFallback(raw, WeixinLoginSchema, INVALID_WEIXIN_LOGIN, {
+ endpoint: "weixin/login",
+ }),
+ ).toEqual(INVALID_WEIXIN_LOGIN);
+ }
+ expect(
+ WeixinLoginSchema.parse({ id: "login", status: "future-status" }).status,
+ ).toBe("error");
+ expect(
+ WeixinLoginSchema.parse({
+ id: "login",
+ status: "confirmed",
+ installation_id: "bot",
+ }).status,
+ ).toBe("confirmed");
+ });
+ it("defaults absent deployment capabilities to unavailable", () => {
+ expect(ListWeixinInstallationsSchema.parse({})).toEqual(
+ EMPTY_WEIXIN_INSTALLATIONS,
+ );
+ expect(
+ parseWithFallback(
+ { installations: [null], configured: true },
+ ListWeixinInstallationsSchema,
+ EMPTY_WEIXIN_INSTALLATIONS,
+ { endpoint: "weixin/installations" },
+ ),
+ ).toEqual(EMPTY_WEIXIN_INSTALLATIONS);
+ expect(
+ ListWeixinInstallationsSchema.parse({ installations: [{ id: "bot" }] })
+ .installations[0]?.status,
+ ).toBe("revoked");
+ });
+ it("stops polling every terminal or unknown status", () => {
+ for (const status of [
+ "wait",
+ "scaned",
+ "need_verifycode",
+ "confirmed_but_need_verifycode",
+ "future_need_verifycode",
+ "scaned_but_redirect",
+ ])
+ expect(isWeixinLoginPending(status)).toBe(true);
+ for (const status of [
+ "confirmed",
+ "expired",
+ "verify_code_blocked",
+ "binded_redirect",
+ "cancelled",
+ "error",
+ "new",
+ ])
+ expect(isWeixinLoginPending(status)).toBe(false);
+ });
+ it.each([
+ "need_verifycode",
+ "confirmed_but_need_verifycode",
+ "future_need_verifycode",
+ ])(
+ "preserves the pending verification status %s",
+ (status) => {
+ expect(WeixinLoginSchema.parse({ id: "login", status }).status).toBe(status);
+ },
+ );
+});
diff --git a/packages/core/weixin/schema.ts b/packages/core/weixin/schema.ts
new file mode 100644
index 0000000000..5f21675808
--- /dev/null
+++ b/packages/core/weixin/schema.ts
@@ -0,0 +1,72 @@
+import { z } from "zod";
+import type {
+ ListWeixinInstallationsResponse,
+ WeixinLogin,
+} from "../types/weixin";
+
+export const WeixinInstallationSchema = z
+ .object({
+ id: z.string(),
+ workspace_id: z.string().default(""),
+ agent_id: z.string().default(""),
+ bot_id: z.string().default(""),
+ user_id: z.string().default(""),
+ installer_user_id: z.string().default(""),
+ status: z.string().default("revoked"),
+ installed_at: z.string().default(""),
+ })
+ .loose();
+
+export const ListWeixinInstallationsSchema = z
+ .object({
+ installations: z.array(WeixinInstallationSchema).default([]),
+ configured: z.boolean().default(false),
+ install_supported: z.boolean().optional(),
+ })
+ .loose();
+
+export const EMPTY_WEIXIN_INSTALLATIONS: ListWeixinInstallationsResponse = {
+ installations: [],
+ configured: false,
+};
+
+export const isWeixinVerificationRequired = (status?: string) =>
+ status?.includes("need_verifycode") === true;
+
+export const WeixinLoginSchema = z
+ .object({
+ id: z.string().min(1),
+ status: z
+ .union([
+ z.enum([
+ "wait",
+ "scaned",
+ "scaned_but_redirect",
+ "confirmed",
+ "expired",
+ "verify_code_blocked",
+ "binded_redirect",
+ "cancelled",
+ "error",
+ ]),
+ z.string().refine(isWeixinVerificationRequired),
+ ])
+ .catch("error"),
+ qr_code_url: z.string().optional(),
+ installation_id: z.string().optional(),
+ expires_at: z.string().default(""),
+ })
+ .loose()
+ .refine((login) => login.status !== "confirmed" || !!login.installation_id);
+
+export const INVALID_WEIXIN_LOGIN: WeixinLogin = {
+ id: "",
+ status: "error",
+ expires_at: "",
+};
+
+export const isWeixinLoginPending = (status?: string) =>
+ status === "wait" ||
+ status === "scaned" ||
+ isWeixinVerificationRequired(status) ||
+ status === "scaned_but_redirect";
diff --git a/packages/ui/icons/drawings/drawings.mjs b/packages/ui/icons/drawings/drawings.mjs
index 745666e6e2..88117a6b8a 100644
--- a/packages/ui/icons/drawings/drawings.mjs
+++ b/packages/ui/icons/drawings/drawings.mjs
@@ -27,6 +27,10 @@ const wifi = (arcs) => [
].slice(0, arcs + 1).join("");
export const DRAWINGS = {
+ WeChat: `<path d="M9 16.5l-4.75 2 1-3.25C3.7 14.05 2.75 12.35 2.75 10.5c0-3.6 3.65-6.5 8.15-6.5 3.85 0 7.1 2.1 7.95 5"/>
+ <path class="b" d="M21.25 14.75c0-3.2-3-5.75-6.75-5.75s-6.75 2.55-6.75 5.75 3 5.75 6.75 5.75c1.15 0 2.25-.25 3.2-.7l3.2 1.45-.75-2.85c.7-1.05 1.1-2.3 1.1-3.65Z"/>
+ ${dot(12, 14.25, 1.1)}${dot(17, 14.25, 1.1)}`,
+
Inbox: `<path class="b" d="${rect(2.75, 3, 18.5, 18, 8)}"/>
<path class="k" d="M2.75 14h4.4c.75 0 1.35.55 1.75 1.2.55.95 1.6 1.8 3.1 1.8s2.55-.85 3.1-1.8c.4-.65 1-1.2 1.75-1.2h4.4"/>`,
CircleUser: `<circle class="b" cx="12" cy="12" r="9.25"/><circle class="k" cx="12" cy="10" r="3"/>
diff --git a/packages/ui/icons/glyphs.ts b/packages/ui/icons/glyphs.ts
index 0a6c424224..b5ba86e30d 100644
--- a/packages/ui/icons/glyphs.ts
+++ b/packages/ui/icons/glyphs.ts
@@ -260,6 +260,7 @@ export const UserPlus: IconNode = [["circle",{"cx":"10","cy":"7.75","r":"4.25","
export const UserRound: IconNode = [["circle",{"cx":"12","cy":"7.75","r":"4.25","className":"icon-body"}],["path",{"d":"M5 20.75c0-3.6 3.13-6.25 7-6.25s7 2.65 7 6.25"}]];
export const Users: IconNode = [["path",{"d":"M6.25 14.5 L4.38 14.5 C3.44 14.5 3.05 14.5 2.77 14.23 C2.5 13.95 2.5 13.56 2.5 12.63 L2.5 8.5 C2.5 6.25 2.5 5.32 3.16 4.66 C3.82 4 4.75 4 7 4 L12.63 4 C13.56 4 13.95 4 14.23 4.27 C14.5 4.55 14.5 4.94 14.5 5.88 L14.5 7.75"}],["path",{"d":"M8.25 14.75 C8.25 12.25 8.25 11.21 8.98 10.48 C9.71 9.75 10.75 9.75 13.25 9.75 L16.5 9.75 C19 9.75 20.04 9.75 20.77 10.48 C21.5 11.21 21.5 12.25 21.5 14.75 L21.5 16 C21.5 18.5 21.5 19.54 20.77 20.27 C20.04 21 19 21 16.5 21 L13.25 21 C10.75 21 9.71 21 8.98 20.27 C8.25 19.54 8.25 18.5 8.25 16 Z","className":"icon-body"}],["path",{"d":"M12.5 14.25v2M17.25 14.25v2","className":"icon-cut"}]];
export const Waves: IconNode = [["path",{"d":"M2.75 6.75c1.85 0 2.78-1.75 4.63-1.75s2.78 1.75 4.62 1.75 2.78-1.75 4.63-1.75 2.77 1.75 4.62 1.75M2.75 12c1.85 0 2.78-1.75 4.63-1.75s2.78 1.75 4.62 1.75 2.78-1.75 4.63-1.75 2.77 1.75 4.62 1.75M2.75 17.25c1.85 0 2.78-1.75 4.63-1.75s2.78 1.75 4.62 1.75 2.78-1.75 4.63-1.75 2.77 1.75 4.62 1.75"}]];
+export const WeChat: IconNode = [["path",{"d":"M9 16.5l-4.75 2 1-3.25C3.7 14.05 2.75 12.35 2.75 10.5c0-3.6 3.65-6.5 8.15-6.5 3.85 0 7.1 2.1 7.95 5"}],["path",{"d":"M21.25 14.75c0-3.2-3-5.75-6.75-5.75s-6.75 2.55-6.75 5.75 3 5.75 6.75 5.75c1.15 0 2.25-.25 3.2-.7l3.2 1.45-.75-2.85c.7-1.05 1.1-2.3 1.1-3.65Z","className":"icon-body"}],["circle",{"fill":"currentColor","stroke":"none","cx":"12","cy":"14.25","r":"1.1"}],["circle",{"fill":"currentColor","stroke":"none","cx":"17","cy":"14.25","r":"1.1"}]];
export const Webhook: IconNode = [["path",{"d":"M17.5 17.25h-5.75c-1.05 0-1.9.8-2.4 1.7a3.75 3.75 0 1 1-4.85-5.3"}],["path",{"d":"m5.75 17.25 3.15-5.5c.55-.95.15-2.1-.4-2.95a3.75 3.75 0 1 1 6.6-3.6"}],["path",{"d":"m12 6.5 3.15 5.45c.55.95 1.75 1.3 2.85 1.3a3.75 3.75 0 1 1-.5 7.5"}]];
export const Wifi: IconNode = [["circle",{"fill":"currentColor","stroke":"none","cx":"12","cy":"19","r":"1.3"}],["path",{"d":"M8.75 15.5a4.6 4.6 0 0 1 6.5 0"}],["path",{"d":"M5.5 12.25a9.2 9.2 0 0 1 13 0"}],["path",{"d":"M2.25 9a13.8 13.8 0 0 1 19.5 0"}]];
export const WifiHigh: IconNode = [["circle",{"fill":"currentColor","stroke":"none","cx":"12","cy":"19","r":"1.3"}],["path",{"d":"M8.75 15.5a4.6 4.6 0 0 1 6.5 0"}],["path",{"d":"M5.5 12.25a9.2 9.2 0 0 1 13 0"}]];
diff --git a/packages/ui/icons/index.ts b/packages/ui/icons/index.ts
index e6f7e870ad..e7ee770289 100644
--- a/packages/ui/icons/index.ts
+++ b/packages/ui/icons/index.ts
@@ -293,6 +293,7 @@ export const UserPlus = /* @__PURE__ */ createIcon("UserPlus", glyph.UserPlus);
export const UserRound = /* @__PURE__ */ createIcon("UserRound", glyph.UserRound);
export const Users = /* @__PURE__ */ createIcon("Users", glyph.Users);
export const Waves = /* @__PURE__ */ createIcon("Waves", glyph.Waves);
+export const WeChat = /* @__PURE__ */ createIcon("WeChat", glyph.WeChat);
export const Webhook = /* @__PURE__ */ createIcon("Webhook", glyph.Webhook);
export const Wifi = /* @__PURE__ */ createIcon("Wifi", glyph.Wifi);
export const WifiHigh = /* @__PURE__ */ createIcon("WifiHigh", glyph.WifiHigh);
diff --git a/packages/views/agents/components/agent-channels-section.tsx b/packages/views/agents/components/agent-channels-section.tsx
index 7e0fcf32ed..8fa65c001b 100644
--- a/packages/views/agents/components/agent-channels-section.tsx
+++ b/packages/views/agents/components/agent-channels-section.tsx
@@ -97,6 +97,9 @@ export function AgentChannelsSection({ agent }: { agent: Agent }) {
const installed = connections.filter(
(entry) => entry.installation.agent_id === agent.id,
);
+ const weixinExpired = queries.weixin.data?.installations.some(
+ (entry) => entry.agent_id === agent.id && entry.status === "expired",
+ );
const canAdd =
!agent.archived_at &&
CHANNEL_INTEGRATIONS.some(
@@ -106,7 +109,7 @@ export function AgentChannelsSection({ agent }: { agent: Agent }) {
!installed.some((entry) => entry.channel === id),
);
const failed = CHANNEL_INTEGRATIONS.filter((id) => queries[id].isError);
- const visible = installed.length > 0 || canAdd || failed.length > 0;
+ const visible = installed.length > 0 || canAdd || failed.length > 0 || weixinExpired;
useEffect(() => {
if (visible && (view === "channels" || view === "integrations"))
sectionRef.current?.scrollIntoView({ block: "start" });
@@ -130,6 +133,11 @@ export function AgentChannelsSection({ agent }: { agent: Agent }) {
) : undefined
}
>
+ {weixinExpired && (
+ <p role="status" className="mb-2 text-caption text-destructive">
+ {t(($) => $.weixin.authorization_expired)}
+ </p>
+ )}
{installed.length ? (
<div className="divide-y rounded-lg border">
{installed.map((connection) => (
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index dae410a245..ccb9599cbb 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -1711,6 +1711,40 @@
"apps": "Team or personal accounts connected through Multica and added to each agent.",
"plugins": "Installed packages that can add tools, scheduled hooks, and storage, each with its own permissions."
},
+ "weixin": {
+ "section_title": "WeChat",
+ "page_description": "Private messages with the account that scans the connection QR code.",
+ "loading": "Connecting…",
+ "load_failed": "Could not load WeChat connections.",
+ "not_enabled": "WeChat is not enabled on this server. Ask the administrator to enable it.",
+ "empty": "Connect WeChat from an agent’s Integrations tab.",
+ "admin_only": "A workspace administrator can connect WeChat.",
+ "connected": "Connected",
+ "connect": "Connect WeChat",
+ "disconnect": "Disconnect",
+ "disconnect_title": "Disconnect WeChat?",
+ "disconnect_description": "New messages will stop reaching this agent. Your Multica chat history stays available.",
+ "cancel": "Cancel",
+ "close": "Close",
+ "action_failed": "Could not complete this action. Try again.",
+ "connect_title": "Connect WeChat to {{agent}}",
+ "privacy_hint": "Scan with your own WeChat account. Its messages will run as you in this workspace. Do not share this QR code.",
+ "qr_label": "WeChat connection QR code",
+ "scan_hint": "Scan with WeChat and confirm on your phone.",
+ "scanned": "Scanned. Confirm the connection in WeChat.",
+ "verify_hint": "WeChat requires a verification code. Enter the code shown on your phone.",
+ "verify_label": "Verification code",
+ "verify": "Verify",
+ "success": "Connected. Send a new message to the bot in WeChat to start.",
+ "expired": "This QR code has expired. Generate a new one.",
+ "blocked": "WeChat has blocked further verification attempts. Try again later.",
+ "already_bound": "This bot is already bound in WeChat. Disconnect the previous client and try again.",
+ "refresh": "New QR code",
+ "retry": "Retry",
+ "already_connected": "This WeChat account is connected to {{agent}}. Disconnect it there first.",
+ "connected_elsewhere": "This WeChat account is connected elsewhere. Disconnect the existing connection first.",
+ "authorization_expired": "WeChat authorization expired. Scan again to reconnect."
+ },
"connected_apps": {
"description": "Accounts your agents use to access external apps. Allowed actions run immediately.",
"loading": "Loading apps…",
diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.json
index e19c7a51fb..3c8c0aaa85 100644
--- a/packages/views/locales/es/settings.json
+++ b/packages/views/locales/es/settings.json
@@ -1711,6 +1711,40 @@
"label": "Al fusionarse los PR, mover la tarea a",
"none": "No cambiar"
},
+ "weixin": {
+ "section_title": "WeChat",
+ "page_description": "Mensajes privados con la cuenta que escanea el código QR de conexión.",
+ "loading": "Conectando…",
+ "load_failed": "No se han podido cargar las conexiones de WeChat.",
+ "not_enabled": "WeChat no está activado en este servidor. Pide al administrador que lo active.",
+ "empty": "Conecta WeChat desde la pestaña Integraciones de un agente.",
+ "admin_only": "Un administrador del espacio de trabajo puede conectar WeChat.",
+ "connected": "Conectado",
+ "connect": "Conectar WeChat",
+ "disconnect": "Desconectar",
+ "disconnect_title": "¿Desconectar WeChat?",
+ "disconnect_description": "Los mensajes nuevos dejarán de llegar a este agente. Tu historial de chat de Multica seguirá disponible.",
+ "cancel": "Cancelar",
+ "close": "Cerrar",
+ "action_failed": "No se ha podido completar esta acción. Vuelve a intentarlo.",
+ "connect_title": "Conectar WeChat a {{agent}}",
+ "privacy_hint": "Escanea con tu propia cuenta de WeChat. Sus mensajes se ejecutarán con tu identidad en este espacio de trabajo. No compartas este código QR.",
+ "qr_label": "Código QR de conexión a WeChat",
+ "scan_hint": "Escanea con WeChat y confirma en tu teléfono.",
+ "scanned": "Código escaneado. Confirma la conexión en WeChat.",
+ "verify_hint": "WeChat requiere un código de verificación. Introduce el código que aparece en tu teléfono.",
+ "verify_label": "Código de verificación",
+ "verify": "Verificar",
+ "success": "Conectado. Envía un mensaje nuevo al bot en WeChat para empezar.",
+ "expired": "Este código QR ha caducado. Genera uno nuevo.",
+ "blocked": "WeChat ha bloqueado los intentos de verificación. Vuelve a intentarlo más tarde.",
+ "already_bound": "Este bot ya está vinculado en WeChat. Desconecta el cliente anterior y vuelve a intentarlo.",
+ "refresh": "Nuevo código QR",
+ "retry": "Reintentar",
+ "already_connected": "Esta cuenta de WeChat está conectada a {{agent}}. Desconéctala allí primero.",
+ "connected_elsewhere": "Esta cuenta de WeChat está conectada en otro lugar. Desconecta primero la conexión existente.",
+ "authorization_expired": "La autorización de WeChat ha caducado. Escanea de nuevo para reconectar."
+ },
"connected_apps": {
"description": "Cuentas que usan tus agentes para acceder a aplicaciones externas. Las acciones permitidas se ejecutan de inmediato.",
"loading": "Cargando aplicaciones…",
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index 2cd2d98c26..171a49301e 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -1711,6 +1711,40 @@
"apps": "Des comptes d'équipe ou personnels connectés via Multica et ajoutés à chaque agent.",
"plugins": "Paquets installés pouvant ajouter des outils, des hooks planifiés et du stockage, chacun avec ses propres autorisations."
},
+ "weixin": {
+ "section_title": "WeChat",
+ "page_description": "Messages privés avec le compte qui scanne le QR code de connexion.",
+ "loading": "Connexion…",
+ "load_failed": "Impossible de charger les connexions WeChat.",
+ "not_enabled": "WeChat n’est pas activé sur ce serveur. Contactez l’administrateur.",
+ "empty": "Connectez WeChat depuis l’onglet Intégrations d’un agent.",
+ "admin_only": "Un administrateur de l’espace de travail peut connecter WeChat.",
+ "connected": "Connecté",
+ "connect": "Connecter WeChat",
+ "disconnect": "Déconnecter",
+ "disconnect_title": "Déconnecter WeChat ?",
+ "disconnect_description": "Les nouveaux messages ne seront plus transmis à cet agent. L’historique Multica reste disponible.",
+ "cancel": "Annuler",
+ "close": "Fermer",
+ "action_failed": "Cette action n’a pas pu aboutir. Réessayez.",
+ "connect_title": "Connecter WeChat à {{agent}}",
+ "privacy_hint": "Scannez avec votre propre compte WeChat. Ses messages seront exécutés avec vos droits dans cet espace de travail. Ne partagez pas ce QR code.",
+ "qr_label": "QR code de connexion WeChat",
+ "scan_hint": "Scannez avec WeChat et confirmez sur votre téléphone.",
+ "scanned": "Code scanné. Confirmez la connexion dans WeChat.",
+ "verify_hint": "WeChat demande une vérification. Saisissez le code affiché sur votre téléphone.",
+ "verify_label": "Code de vérification",
+ "verify": "Vérifier",
+ "success": "Connexion établie. Envoyez un nouveau message au bot dans WeChat.",
+ "expired": "Ce QR code a expiré. Générez-en un nouveau.",
+ "blocked": "WeChat a bloqué les tentatives de vérification. Réessayez plus tard.",
+ "already_bound": "Ce bot est déjà lié dans WeChat. Déconnectez l’ancien client, puis réessayez.",
+ "refresh": "Nouveau QR code",
+ "retry": "Réessayer",
+ "already_connected": "Ce compte WeChat est connecté à {{agent}}. Déconnectez-le de cet agent avant de continuer.",
+ "connected_elsewhere": "Ce compte WeChat est connecté ailleurs. Déconnectez la connexion existante avant de continuer.",
+ "authorization_expired": "L’autorisation WeChat a expiré. Scannez à nouveau pour vous reconnecter."
+ },
"connected_apps": {
"description": "Les comptes que vos agents utilisent pour accéder aux apps externes. Les actions autorisées sont exécutées immédiatement.",
"loading": "Chargement des apps…",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index e1e3e19659..f6e1786168 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -1695,6 +1695,40 @@
"apps": "Multica で接続したチームまたは個人のアカウントを、各エージェントに追加します。",
"plugins": "インストールするとツール、定期フック、ストレージを追加でき、プラグインごとに権限を付与します。"
},
+ "weixin": {
+ "section_title": "WeChat",
+ "page_description": "接続用 QR コードを読み取ったアカウントとの個別メッセージ。",
+ "loading": "接続中…",
+ "load_failed": "WeChat の接続を読み込めませんでした。",
+ "not_enabled": "このサーバーでは WeChat が有効になっていません。管理者にお問い合わせください。",
+ "empty": "エージェントの「連携」タブから WeChat に接続してください。",
+ "admin_only": "ワークスペースの管理者が WeChat に接続できます。",
+ "connected": "接続済み",
+ "connect": "WeChat に接続",
+ "disconnect": "接続を解除",
+ "disconnect_title": "WeChat の接続を解除しますか?",
+ "disconnect_description": "新しいメッセージはこのエージェントに届かなくなります。Multica のチャット履歴は残ります。",
+ "cancel": "キャンセル",
+ "close": "閉じる",
+ "action_failed": "操作を完了できませんでした。もう一度お試しください。",
+ "connect_title": "WeChat を {{agent}} に接続",
+ "privacy_hint": "自分の WeChat アカウントで読み取ってください。メッセージはこのワークスペースであなたの権限で実行されます。QR コードを共有しないでください。",
+ "qr_label": "WeChat 接続用 QR コード",
+ "scan_hint": "WeChat で読み取り、スマートフォンで確認してください。",
+ "scanned": "読み取り済み。WeChat で接続を確認してください。",
+ "verify_hint": "WeChat による認証が必要です。スマートフォンに表示されたコードを入力してください。",
+ "verify_label": "認証コード",
+ "verify": "認証",
+ "success": "接続しました。WeChat でボットに新しいメッセージを送信してください。",
+ "expired": "QR コードの有効期限が切れました。新しく生成してください。",
+ "blocked": "WeChat により認証が制限されています。しばらくしてからお試しください。",
+ "already_bound": "このボットはすでに WeChat に接続されています。以前のクライアントの接続を解除して再試行してください。",
+ "refresh": "新しい QR コード",
+ "retry": "再試行",
+ "already_connected": "このWeChatアカウントは{{agent}}に接続されています。先にそちらで接続を解除してください。",
+ "connected_elsewhere": "このWeChatアカウントは別の場所で接続されています。先に既存の接続を解除してください。",
+ "authorization_expired": "WeChatの認証が失効しました。もう一度スキャンして接続してください。"
+ },
"connected_apps": {
"description": "エージェントが外部アプリを操作するアカウントです。許可された操作はすぐに実行されます。",
"loading": "アプリを読み込み中…",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 1673e242d7..73abb251e9 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -1695,6 +1695,40 @@
"apps": "Multica로 연결한 팀 또는 개인 계정을 각 에이전트에 추가합니다.",
"plugins": "설치하면 도구, 예약 훅, 저장소를 추가할 수 있으며 플러그인마다 권한을 부여합니다."
},
+ "weixin": {
+ "section_title": "WeChat",
+ "page_description": "연결 QR 코드를 스캔한 계정과의 개인 메시지입니다.",
+ "loading": "연결 중…",
+ "load_failed": "WeChat 연결을 불러오지 못했습니다.",
+ "not_enabled": "이 서버에서 WeChat이 활성화되지 않았습니다. 관리자에게 문의하세요.",
+ "empty": "에이전트의 연동 탭에서 WeChat을 연결하세요.",
+ "admin_only": "워크스페이스 관리자가 WeChat을 연결할 수 있습니다.",
+ "connected": "연결됨",
+ "connect": "WeChat 연결",
+ "disconnect": "연결 해제",
+ "disconnect_title": "WeChat 연결을 해제할까요?",
+ "disconnect_description": "새 메시지가 이 에이전트에 전달되지 않습니다. Multica 채팅 기록은 유지됩니다.",
+ "cancel": "취소",
+ "close": "닫기",
+ "action_failed": "작업을 완료하지 못했습니다. 다시 시도하세요.",
+ "connect_title": "{{agent}}에 WeChat 연결",
+ "privacy_hint": "본인의 WeChat 계정으로 스캔하세요. 메시지는 이 워크스페이스에서 본인의 권한으로 실행됩니다. QR 코드를 공유하지 마세요.",
+ "qr_label": "WeChat 연결 QR 코드",
+ "scan_hint": "WeChat으로 스캔한 후 휴대폰에서 확인하세요.",
+ "scanned": "스캔되었습니다. WeChat에서 연결을 확인하세요.",
+ "verify_hint": "WeChat 인증이 필요합니다. 휴대폰에 표시된 코드를 입력하세요.",
+ "verify_label": "인증 코드",
+ "verify": "인증",
+ "success": "연결되었습니다. WeChat에서 봇에게 새 메시지를 보내세요.",
+ "expired": "QR 코드가 만료되었습니다. 새로 생성하세요.",
+ "blocked": "WeChat이 추가 인증을 차단했습니다. 나중에 다시 시도하세요.",
+ "already_bound": "이 봇은 이미 WeChat에 연결되어 있습니다. 이전 클라이언트의 연결을 해제하고 다시 시도하세요.",
+ "refresh": "새 QR 코드",
+ "retry": "다시 시도",
+ "already_connected": "이 WeChat 계정은 {{agent}}에 연결되어 있습니다. 먼저 해당 연결을 해제하세요.",
+ "connected_elsewhere": "이 WeChat 계정은 다른 곳에 연결되어 있습니다. 먼저 기존 연결을 해제하세요.",
+ "authorization_expired": "WeChat 인증이 만료되었습니다. 다시 스캔하여 연결하세요."
+ },
"connected_apps": {
"description": "에이전트가 외부 앱을 사용할 때 쓰는 계정입니다. 허용된 작업은 즉시 실행됩니다.",
"loading": "앱을 불러오는 중…",
diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.json
index 868d39bd68..59454af3e6 100644
--- a/packages/views/locales/ru/settings.json
+++ b/packages/views/locales/ru/settings.json
@@ -1742,6 +1742,40 @@
"apps": "Аккаунты команды или личные аккаунты, подключённые через Multica и добавленные каждому агенту.",
"plugins": "Установленные пакеты, которые могут добавлять инструменты, запланированные хуки и хранилище, каждый со своими правами доступа."
},
+ "weixin": {
+ "section_title": "WeChat",
+ "page_description": "Личные сообщения аккаунта, который отсканировал QR-код подключения.",
+ "loading": "Подключение…",
+ "load_failed": "Не удалось загрузить подключения WeChat.",
+ "not_enabled": "WeChat не включён на этом сервере. Обратитесь к администратору.",
+ "empty": "Подключите WeChat на вкладке «Интеграции» агента.",
+ "admin_only": "Подключить WeChat может администратор рабочего пространства.",
+ "connected": "Подключено",
+ "connect": "Подключить WeChat",
+ "disconnect": "Отключить",
+ "disconnect_title": "Отключить WeChat?",
+ "disconnect_description": "Новые сообщения перестанут поступать этому агенту. История чата в Multica сохранится.",
+ "cancel": "Отмена",
+ "close": "Закрыть",
+ "action_failed": "Не удалось выполнить действие. Повторите попытку.",
+ "connect_title": "Подключить WeChat к {{agent}}",
+ "privacy_hint": "Отсканируйте QR-код своим аккаунтом WeChat. Его сообщения будут обрабатываться от вашего имени в этом рабочем пространстве. Не делитесь QR-кодом.",
+ "qr_label": "QR-код для подключения WeChat",
+ "scan_hint": "Отсканируйте QR-код в WeChat и подтвердите подключение на телефоне.",
+ "scanned": "QR-код отсканирован. Подтвердите подключение в WeChat.",
+ "verify_hint": "WeChat требует код подтверждения. Введите код, показанный на телефоне.",
+ "verify_label": "Код подтверждения",
+ "verify": "Подтвердить",
+ "success": "Подключено. Отправьте новое сообщение боту в WeChat, чтобы начать.",
+ "expired": "Срок действия QR-кода истёк. Создайте новый.",
+ "blocked": "WeChat заблокировал дальнейшие попытки подтверждения. Повторите позже.",
+ "already_bound": "Этот бот уже привязан в WeChat. Отключите предыдущий клиент и повторите попытку.",
+ "refresh": "Новый QR-код",
+ "retry": "Повторить",
+ "already_connected": "Этот аккаунт WeChat подключён к {{agent}}. Сначала отключите его там.",
+ "connected_elsewhere": "Этот аккаунт WeChat подключён в другом месте. Сначала отключите существующее подключение.",
+ "authorization_expired": "Авторизация WeChat истекла. Отсканируйте код повторно для подключения."
+ },
"connected_apps": {
"description": "Аккаунты, через которые ваши агенты работают с внешними приложениями. Разрешённые действия выполняются сразу.",
"loading": "Загрузка приложений…",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index b467070254..98be67768a 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -1695,6 +1695,40 @@
"apps": "通过 Multica 连接团队或个人账号,再将应用添加到智能体。",
"plugins": "安装后可提供工具、定时 hook 和存储,每个插件单独授权。"
},
+ "weixin": {
+ "section_title": "微信",
+ "page_description": "接收扫码账号的私聊消息。",
+ "loading": "正在连接…",
+ "load_failed": "无法加载微信连接。",
+ "not_enabled": "此服务器尚未启用微信,请联系管理员。",
+ "empty": "在智能体的「集成」页签中连接微信。",
+ "admin_only": "工作区管理员可以连接微信。",
+ "connected": "已连接",
+ "connect": "连接微信",
+ "disconnect": "断开连接",
+ "disconnect_title": "断开微信连接?",
+ "disconnect_description": "新消息将不再发送给此智能体,Multica 聊天记录会保留。",
+ "cancel": "取消",
+ "close": "关闭",
+ "action_failed": "操作未完成,请重试。",
+ "connect_title": "将微信连接到 {{agent}}",
+ "privacy_hint": "请用你自己的微信扫码,消息将以你的身份在此工作区执行。请勿分享二维码。",
+ "qr_label": "微信连接二维码",
+ "scan_hint": "使用微信扫码,并在手机上确认。",
+ "scanned": "已扫码,请在微信中确认连接。",
+ "verify_hint": "微信要求输入验证码,请填写手机上显示的数字。",
+ "verify_label": "验证码",
+ "verify": "验证",
+ "success": "已连接。请在微信中向机器人发送新消息。",
+ "expired": "二维码已过期,请重新生成。",
+ "blocked": "微信已暂停验证码验证,请稍后重试。",
+ "already_bound": "此机器人已在微信中绑定,请先断开原客户端,再重试。",
+ "refresh": "重新生成二维码",
+ "retry": "重试",
+ "already_connected": "这个微信已经连接到智能体 {{agent}},请先在那边断开。",
+ "connected_elsewhere": "这个微信已在其他位置连接,请先断开原连接。",
+ "authorization_expired": "微信授权已过期,请重新扫码连接。"
+ },
"connected_apps": {
"description": "智能体通过这些账号操作外部应用,允许的操作会直接执行。",
"loading": "正在加载应用…",
diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.json
index ac49d92a2a..aa7d83a3bd 100644
--- a/packages/views/locales/zh-Hant/settings.json
+++ b/packages/views/locales/zh-Hant/settings.json
@@ -1695,6 +1695,40 @@
"apps": "透過 Multica 連線團隊或個人帳號,再將應用新增至 AI 代理。",
"plugins": "安裝後可提供工具、定時 hook 和儲存,每個外掛單獨授權。"
},
+ "weixin": {
+ "section_title": "微信",
+ "page_description": "接收掃碼帳號的私訊。",
+ "loading": "正在連線…",
+ "load_failed": "無法載入微信連線。",
+ "not_enabled": "此伺服器尚未啟用微信,請聯絡管理員。",
+ "empty": "在 AI 代理的「整合」分頁中連接微信。",
+ "admin_only": "工作區管理員可以連接微信。",
+ "connected": "已連接",
+ "connect": "連接微信",
+ "disconnect": "中斷連線",
+ "disconnect_title": "中斷微信連線?",
+ "disconnect_description": "新訊息將不再傳送給此 AI 代理,Multica 聊天記錄會保留。",
+ "cancel": "取消",
+ "close": "關閉",
+ "action_failed": "操作未完成,請重試。",
+ "connect_title": "將微信連接到 {{agent}}",
+ "privacy_hint": "請用你自己的微信掃碼,訊息將以你的身分在此工作區執行。請勿分享 QR 碼。",
+ "qr_label": "微信連線 QR 碼",
+ "scan_hint": "使用微信掃碼,並在手機上確認。",
+ "scanned": "已掃碼,請在微信中確認連線。",
+ "verify_hint": "微信要求輸入驗證碼,請填寫手機上顯示的數字。",
+ "verify_label": "驗證碼",
+ "verify": "驗證",
+ "success": "已連接。請在微信中向機器人傳送新訊息。",
+ "expired": "QR 碼已過期,請重新產生。",
+ "blocked": "微信已暫停驗證碼驗證,請稍後重試。",
+ "already_bound": "此機器人已在微信中綁定,請先中斷原用戶端,再重試。",
+ "refresh": "重新產生 QR 碼",
+ "retry": "重試",
+ "already_connected": "此微信已連接至 AI 代理 {{agent}},請先在該處中斷連線。",
+ "connected_elsewhere": "此微信已在其他位置連接,請先中斷原連線。",
+ "authorization_expired": "微信授權已過期,請重新掃碼連接。"
+ },
"connected_apps": {
"description": "AI 代理透過這些帳號操作外部應用,允許的操作會直接執行。",
"loading": "正在載入應用…",
diff --git a/packages/views/settings/components/channel-connect-dialog.tsx b/packages/views/settings/components/channel-connect-dialog.tsx
index f93c6eb348..4fc5982712 100644
--- a/packages/views/settings/components/channel-connect-dialog.tsx
+++ b/packages/views/settings/components/channel-connect-dialog.tsx
@@ -27,6 +27,7 @@ import {
import { useMessagingChannels } from "./use-messaging-channels";
import { LarkChannelAuthorization } from "./lark-channel-authorization";
import { WecomChannelAuthorization } from "./wecom-channel-authorization";
+import { WeixinAgentBindButton } from "./weixin-tab";
export function ChannelConnectDialog({
agents,
@@ -268,6 +269,8 @@ function ChannelConnectSteps({
region="feishu"
onClose={onClose}
/>
+ ) : channel === "weixin" ? (
+ <WeixinAgentBindButton agentId={agent.id} agentName={agent.name} onBusyChange={onBusyChange} />
) : scanWecom ? (
<WecomChannelAuthorization
wsId={wsId}
@@ -296,7 +299,7 @@ function ChannelCredentials({
onClose,
onBusyChange,
}: {
- channel: Exclude<ChannelIntegration, "lark">;
+ channel: Exclude<ChannelIntegration, "lark" | "weixin">;
wsId: string;
agentId: string;
onClose: () => void;
diff --git a/packages/views/settings/components/channel-disconnect-dialog.tsx b/packages/views/settings/components/channel-disconnect-dialog.tsx
index 9e0577805f..57f6d08dc0 100644
--- a/packages/views/settings/components/channel-disconnect-dialog.tsx
+++ b/packages/views/settings/components/channel-disconnect-dialog.tsx
@@ -40,6 +40,7 @@ export function ChannelDisconnectDialog({
dingtalk: api.deleteDingTalkInstallation.bind(api),
wecom: api.deleteWecomInstallation.bind(api),
telegram: api.deleteTelegramInstallation.bind(api),
+ weixin: api.deleteWeixinInstallation.bind(api),
}[channel];
await revoke(installation.workspace_id, installation.id);
await qc.invalidateQueries({
diff --git a/packages/views/settings/components/channels-tab.tsx b/packages/views/settings/components/channels-tab.tsx
index 703a156d25..091430b341 100644
--- a/packages/views/settings/components/channels-tab.tsx
+++ b/packages/views/settings/components/channels-tab.tsx
@@ -181,7 +181,8 @@ export function ChannelsTab() {
<span>
{t(($) => $.slack.section_title)},{" "}
{t(($) => $.wecom.section_title)},{" "}
- {t(($) => $.telegram.section_title)}
+ {t(($) => $.telegram.section_title)},{" "}
+ {t(($) => $.weixin.section_title)}
</span>
<span className="text-muted-foreground">
{t(($) => $.channels.admin_only)}
diff --git a/packages/views/settings/components/integration-channel-icon.tsx b/packages/views/settings/components/integration-channel-icon.tsx
index 9949d3171a..fde93eb219 100644
--- a/packages/views/settings/components/integration-channel-icon.tsx
+++ b/packages/views/settings/components/integration-channel-icon.tsx
@@ -1,10 +1,11 @@
+import { WeChat } from "@multica/ui/icons";
import { DingTalkMark } from "./dingtalk-mark";
import { LarkMark } from "./lark-mark";
import { SlackMark } from "./slack-mark";
import { TelegramMark } from "./telegram-mark";
import { WecomMark } from "./wecom-mark";
-type IntegrationChannel = "lark" | "slack" | "dingtalk" | "wecom" | "telegram";
+type IntegrationChannel = "lark" | "slack" | "dingtalk" | "wecom" | "telegram" | "weixin";
// Every channel gets its own brand mark, never a generic lucide glyph: the icon
// is what tells a reader which platform the section belongs to, and a stand-in
@@ -17,6 +18,7 @@ export function IntegrationChannelIcon({ channel }: { channel: IntegrationChanne
slack: <SlackMark className="h-4 w-4" />,
dingtalk: <DingTalkMark className="h-5 w-5" />,
wecom: <WecomMark className="h-4 w-4" />,
+ weixin: <WeChat className="h-4 w-4" />,
telegram: <TelegramMark className="h-4 w-4" />,
}[channel];
diff --git a/packages/views/settings/components/messaging-channels.test.tsx b/packages/views/settings/components/messaging-channels.test.tsx
index 73d3bfe27d..61fa461de9 100644
--- a/packages/views/settings/components/messaging-channels.test.tsx
+++ b/packages/views/settings/components/messaging-channels.test.tsx
@@ -56,6 +56,10 @@ vi.mock("@multica/core/api", async (original) => ({
"listDingTalkInstallations",
"listWecomInstallations",
"listTelegramInstallations",
+ "listWeixinInstallations",
+ "beginWeixinLogin",
+ "pollWeixinLogin",
+ "cancelWeixinLogin",
"registerSlackBYO",
"registerDingTalkBYO",
"registerWecomBYO",
@@ -65,6 +69,7 @@ vi.mock("@multica/core/api", async (original) => ({
"deleteDingTalkInstallation",
"deleteWecomInstallation",
"deleteTelegramInstallation",
+ "deleteWeixinInstallation",
"listAgentDingTalkGroups",
"listAgents",
"beginLarkInstall",
@@ -122,6 +127,7 @@ beforeEach(() => {
"listDingTalkInstallations",
"listWecomInstallations",
"listTelegramInstallations",
+ "listWeixinInstallations",
] as const) {
vi.mocked(api[name]).mockResolvedValue(listing() as never);
}
@@ -339,7 +345,7 @@ describe("agent messaging channels", () => {
expect(screen.queryByText("Telegram")).toBeNull();
});
- it.each(["lark", "slack", "dingtalk", "wecom", "telegram"] as const)(
+ it.each(["lark", "slack", "dingtalk", "wecom", "telegram", "weixin"] as const)(
"confirms %s disconnect and preserves the connection on failure",
async (channel) => {
const methods = {
@@ -348,6 +354,7 @@ describe("agent messaging channels", () => {
dingtalk: ["listDingTalkInstallations", "deleteDingTalkInstallation"],
wecom: ["listWecomInstallations", "deleteWecomInstallation"],
telegram: ["listTelegramInstallations", "deleteTelegramInstallation"],
+ weixin: ["listWeixinInstallations", "deleteWeixinInstallation"],
} as const;
const [list, remove] = methods[channel];
vi.mocked(api[list]).mockResolvedValue(listing([active]) as never);
@@ -389,6 +396,37 @@ const platformName = {
} as const;
describe("shared connection dialog", () => {
+ it("starts and cancels a WeChat QR login for the selected agent", async () => {
+ const login = {
+ id: "login-1",
+ status: "wait",
+ qr_code_url: "https://weixin.qq.com/test-qr",
+ expires_at: new Date(Date.now() + 300_000).toISOString(),
+ };
+ vi.mocked(api.beginWeixinLogin).mockResolvedValue(login);
+ vi.mocked(api.pollWeixinLogin).mockResolvedValue(login);
+ vi.mocked(api.cancelWeixinLogin).mockResolvedValue(undefined);
+ show(
+ <ChannelConnectDialog
+ agents={[agent]}
+ initialAgent={agent}
+ initialChannel="weixin"
+ open
+ onOpenChange={vi.fn()}
+ />,
+ );
+ const platform = await screen.findByRole("button", { name: "WeChat" });
+ await waitFor(() => expect(platform).toBeEnabled());
+ fireEvent.click(platform);
+ fireEvent.click(await screen.findByRole("button", { name: "Connect WeChat" }));
+ expect(await screen.findByTitle("WeChat connection QR code")).toBeInTheDocument();
+ expect(api.beginWeixinLogin).toHaveBeenCalledWith("ws-1", agent.id);
+ const qrDialog = screen.getByRole("dialog", { name: "Connect WeChat to Mika" });
+ fireEvent.click(within(qrDialog).getAllByRole("button", { name: "Close" })[0]!);
+ await waitFor(() => expect(api.cancelWeixinLogin).toHaveBeenCalledWith("ws-1", login.id));
+ await waitFor(() => expect(screen.queryByRole("dialog", { name: "Connect WeChat to Mika" })).toBeNull());
+ });
+
it("offers only Feishu for new connections while international Lark is disabled", async () => {
show(
<ChannelConnectDialog
@@ -610,7 +648,7 @@ describe("workspace overview", () => {
);
expect(state.replace).toHaveBeenCalledWith("/acme/settings?tab=channels");
expect(screen.getByText("Who can connect")).toBeInTheDocument();
- expect(screen.getAllByRole("button", { name: "Connect" })).toHaveLength(5);
+ expect(screen.getAllByRole("button", { name: "Connect" })).toHaveLength(6);
});
it("reports failed reads as unavailable and keeps a retry control", async () => {
diff --git a/packages/views/settings/components/settings-navigation.ts b/packages/views/settings/components/settings-navigation.ts
index f2d745d214..6801ec8bbd 100644
--- a/packages/views/settings/components/settings-navigation.ts
+++ b/packages/views/settings/components/settings-navigation.ts
@@ -5,6 +5,7 @@ export const CHANNEL_INTEGRATIONS = [
"dingtalk",
"wecom",
"telegram",
+ "weixin",
] as const;
export type ChannelIntegration = (typeof CHANNEL_INTEGRATIONS)[number];
diff --git a/packages/views/settings/components/use-messaging-channels.ts b/packages/views/settings/components/use-messaging-channels.ts
index 1608254e48..ec2064ec7d 100644
--- a/packages/views/settings/components/use-messaging-channels.ts
+++ b/packages/views/settings/components/use-messaging-channels.ts
@@ -7,6 +7,7 @@ import { larkInstallationsOptions } from "@multica/core/lark";
import { slackInstallationsOptions } from "@multica/core/slack";
import { dingtalkInstallationsOptions } from "@multica/core/dingtalk";
import { wecomInstallationsOptions } from "@multica/core/wecom";
+import { weixinInstallationsOptions } from "@multica/core/weixin";
import { telegramInstallationsOptions } from "@multica/core/telegram";
import type {
Agent,
@@ -15,6 +16,7 @@ import type {
DingTalkInstallation,
WecomInstallation,
TelegramInstallation,
+ WeixinInstallation,
} from "@multica/core/types";
import type { ChannelIntegration } from "./settings-navigation";
@@ -23,7 +25,8 @@ export type ChannelConnection =
| { channel: "slack"; installation: SlackInstallation }
| { channel: "dingtalk"; installation: DingTalkInstallation }
| { channel: "wecom"; installation: WecomInstallation }
- | { channel: "telegram"; installation: TelegramInstallation };
+ | { channel: "telegram"; installation: TelegramInstallation }
+ | { channel: "weixin"; installation: WeixinInstallation };
export function channelChatLink(
connection: ChannelConnection,
@@ -56,7 +59,8 @@ export function useMessagingChannels() {
const dingtalk = useQuery({ ...dingtalkInstallationsOptions(wsId), enabled });
const wecom = useQuery({ ...wecomInstallationsOptions(wsId), enabled });
const telegram = useQuery({ ...telegramInstallationsOptions(wsId), enabled });
- const queries = { lark, slack, dingtalk, wecom, telegram };
+ const weixin = useQuery({ ...weixinInstallationsOptions(wsId), enabled });
+ const queries = { lark, slack, dingtalk, wecom, telegram, weixin };
const connections: ChannelConnection[] = [
...(lark.data?.installations ?? []).map((installation) => ({
channel: "lark" as const,
@@ -74,6 +78,10 @@ export function useMessagingChannels() {
channel: "wecom" as const,
installation,
})),
+ ...(weixin.data?.installations ?? []).map((installation) => ({
+ channel: "weixin" as const,
+ installation,
+ })),
...(telegram.data?.installations ?? []).map((installation) => ({
channel: "telegram" as const,
installation,
diff --git a/packages/views/settings/components/weixin-tab.test.tsx b/packages/views/settings/components/weixin-tab.test.tsx
new file mode 100644
index 0000000000..2b485e9666
--- /dev/null
+++ b/packages/views/settings/components/weixin-tab.test.tsx
@@ -0,0 +1,227 @@
+// @vitest-environment jsdom
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../../locales/en/common.json";
+import enSettings from "../../locales/en/settings.json";
+import { ApiError } from "@multica/core/api/client";
+
+const mocks = vi.hoisted(() => ({
+ list: vi.fn(),
+ begin: vi.fn(),
+ poll: vi.fn(),
+ cancel: vi.fn(),
+ revoke: vi.fn(),
+ member: { role: "admin" },
+}));
+vi.mock("@multica/core/api", () => ({
+ api: {
+ listWeixinInstallations: mocks.list,
+ beginWeixinLogin: mocks.begin,
+ pollWeixinLogin: mocks.poll,
+ cancelWeixinLogin: mocks.cancel,
+ deleteWeixinInstallation: mocks.revoke,
+ },
+ clientErrorMessage: () => undefined,
+}));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
+vi.mock("@multica/core/permissions", () => ({
+ useCurrentMember: () => ({ member: mocks.member }),
+}));
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({ getAgentName: () => "Assistant" }),
+}));
+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
+
+import { WeixinAgentBindButton } from "./weixin-tab";
+
+const login = {
+ id: "login-1",
+ status: "wait",
+ qr_code_url: "https://weixin.qq.com/test-qr",
+ expires_at: new Date(Date.now() + 300_000).toISOString(),
+};
+const active = { id: "bot-1", agent_id: "agent-1", status: "active" };
+
+function renderButton() {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ const result = render(
+ <QueryClientProvider client={client}>
+ <I18nProvider
+ locale="en"
+ resources={{ en: { common: enCommon, settings: enSettings } }}
+ >
+ <WeixinAgentBindButton agentId="agent-1" agentName="Assistant" />
+ </I18nProvider>
+ </QueryClientProvider>,
+ );
+ return { ...result, client };
+}
+
+describe("WeChat QR connection", () => {
+ beforeEach(() => {
+ cleanup();
+ vi.resetAllMocks();
+ mocks.member.role = "admin";
+ mocks.list.mockResolvedValue({
+ configured: true,
+ install_supported: true,
+ installations: [],
+ });
+ mocks.begin.mockResolvedValue(login);
+ mocks.poll.mockResolvedValue(login);
+ mocks.cancel.mockResolvedValue(undefined);
+ mocks.revoke.mockResolvedValue(undefined);
+ });
+
+ it.each(["need_verifycode", "confirmed_but_need_verifycode"])(
+ "submits the phone code for %s and refreshes the confirmed connection",
+ async (status) => {
+ const user = userEvent.setup();
+ mocks.poll
+ .mockResolvedValueOnce({ ...login, status })
+ .mockImplementation(async () => {
+ mocks.list.mockResolvedValue({
+ configured: true,
+ install_supported: true,
+ installations: [active],
+ });
+ return {
+ id: login.id,
+ status: "confirmed",
+ installation_id: active.id,
+ expires_at: login.expires_at,
+ };
+ });
+ renderButton();
+ await user.click(
+ await screen.findByRole("button", { name: "Connect WeChat" }),
+ );
+ expect(
+ await screen.findByRole("dialog", {
+ name: "Connect WeChat to Assistant",
+ }),
+ ).toBeVisible();
+ expect(
+ await screen.findByTitle("WeChat connection QR code"),
+ ).toBeInTheDocument();
+ await user.type(
+ await screen.findByLabelText("Verification code"),
+ "001234",
+ );
+ await user.click(screen.getByRole("button", { name: "Verify" }));
+ await waitFor(() =>
+ expect(mocks.poll).toHaveBeenCalledWith(
+ "workspace-1",
+ "login-1",
+ "001234",
+ ),
+ );
+ expect(await screen.findByText("Connected", { exact: true })).toBeVisible();
+ },
+ );
+
+ it("waits for server cancellation before closing and retains a failed cancellation", async () => {
+ const user = userEvent.setup();
+ mocks.cancel.mockRejectedValueOnce(new Error("offline"));
+ renderButton();
+ await user.click(
+ await screen.findByRole("button", { name: "Connect WeChat" }),
+ );
+ await screen.findByTitle("WeChat connection QR code");
+ await user.click(screen.getAllByRole("button", { name: "Close" })[0]!);
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Could not complete this action",
+ );
+ expect(screen.getByRole("dialog")).toBeVisible();
+ await user.click(screen.getAllByRole("button", { name: "Close" })[0]!);
+ await waitFor(() =>
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),
+ );
+ expect(mocks.cancel).toHaveBeenCalledWith("workspace-1", "login-1");
+ });
+
+ it("stops on expired QR and lets the user request a new one", async () => {
+ const user = userEvent.setup();
+ mocks.poll.mockResolvedValue({
+ ...login,
+ status: "expired",
+ qr_code_url: undefined,
+ });
+ renderButton();
+ await user.click(
+ await screen.findByRole("button", { name: "Connect WeChat" }),
+ );
+ expect(
+ await screen.findByText("This QR code has expired. Generate a new one."),
+ ).toBeVisible();
+ expect(
+ screen.queryByTitle("WeChat connection QR code"),
+ ).not.toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "New QR code" }));
+ await waitFor(() => expect(mocks.begin).toHaveBeenCalledTimes(2));
+ });
+
+ it("never offers connection to workspace members", async () => {
+ mocks.member.role = "member";
+ renderButton();
+ expect(
+ await screen.findByText("A workspace administrator can connect WeChat."),
+ ).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Connect WeChat" }),
+ ).not.toBeInTheDocument();
+ expect(mocks.begin).not.toHaveBeenCalled();
+ });
+
+ it("requires confirmation and keeps a failed disconnect visible", async () => {
+ const user = userEvent.setup();
+ mocks.list.mockResolvedValue({ configured: true, installations: [active] });
+ mocks.revoke.mockRejectedValue(new Error("offline"));
+ renderButton();
+ await user.click(await screen.findByRole("button", { name: "Disconnect" }));
+ expect(mocks.revoke).not.toHaveBeenCalled();
+ await user.click(
+ screen.getAllByRole("button", { name: "Disconnect" }).at(-1)!,
+ );
+ expect(await screen.findByRole("alert")).toBeVisible();
+ expect(screen.getByRole("dialog")).toBeVisible();
+ expect(mocks.revoke).toHaveBeenCalledWith("workspace-1", "bot-1");
+ });
+
+ it("names the agent owning a conflicting WeChat connection", async () => {
+ const user = userEvent.setup();
+ mocks.poll.mockRejectedValue(new ApiError("already connected", 409, "Conflict", {
+ code: "weixin_already_connected", agent_id: "other-agent", agent_name: "Research Assistant",
+ }));
+ renderButton();
+ await user.click(await screen.findByRole("button", { name: "Connect WeChat" }));
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "This WeChat account is connected to Research Assistant. Disconnect it there first.",
+ );
+ expect(screen.queryByTitle("WeChat connection QR code")).not.toBeInTheDocument();
+ });
+
+ it("keeps cross-workspace conflict details private", async () => {
+ const user = userEvent.setup();
+ mocks.poll.mockRejectedValue(new ApiError("already connected", 409, "Conflict", {
+ code: "weixin_already_connected",
+ }));
+ renderButton();
+ await user.click(await screen.findByRole("button", { name: "Connect WeChat" }));
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "This WeChat account is connected elsewhere. Disconnect the existing connection first.",
+ );
+ });
+
+ it("explains expired authorization and offers reconnection", async () => {
+ mocks.list.mockResolvedValue({ configured: true, install_supported: true, installations: [{ ...active, status: "expired" }] });
+ renderButton();
+ expect(await screen.findByText("WeChat authorization expired. Scan again to reconnect.")).toBeVisible();
+ expect(screen.getByRole("button", { name: "Connect WeChat" })).toBeVisible();
+ });
+});
diff --git a/packages/views/settings/components/weixin-tab.tsx b/packages/views/settings/components/weixin-tab.tsx
new file mode 100644
index 0000000000..2264593f1e
--- /dev/null
+++ b/packages/views/settings/components/weixin-tab.tsx
@@ -0,0 +1,391 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { QRCode } from "react-qr-code";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { api, clientErrorMessage } from "@multica/core/api";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useCurrentMember } from "@multica/core/permissions";
+import type { WeixinInstallation, WeixinLogin } from "@multica/core/types";
+import {
+ weixinInstallationsOptions,
+ weixinKeys,
+ isWeixinLoginPending,
+ isWeixinVerificationRequired,
+ weixinConflict,
+} from "@multica/core/weixin";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import { Label } from "@multica/ui/components/ui/label";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { WeChat } from "@multica/ui/icons";
+import { useT } from "../../i18n";
+
+export function WeixinAgentBindButton({
+ agentId,
+ agentName,
+ onBusyChange,
+}: {
+ agentId: string;
+ agentName: string;
+ onBusyChange?: (busy: boolean) => void;
+}) {
+ const wsId = useWorkspaceId();
+ const { t } = useT("settings");
+ const { member } = useCurrentMember(wsId);
+ const listing = useQuery(weixinInstallationsOptions(wsId));
+ const canManage = member?.role === "owner" || member?.role === "admin";
+ const active = listing.data?.installations.find(
+ (item) => item.agent_id === agentId && item.status === "active",
+ );
+ const expired = listing.data?.installations.some(
+ (item) => item.agent_id === agentId && item.status === "expired",
+ );
+ if (listing.isError)
+ return (
+ <p role="alert" className="text-caption">
+ {t(($) => $.weixin.load_failed)}
+ </p>
+ );
+ if (listing.isPending)
+ return (
+ <p role="status" className="text-caption">
+ {t(($) => $.weixin.loading)}
+ </p>
+ );
+ if (!listing.data.configured)
+ return (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.weixin.not_enabled)}
+ </p>
+ );
+ if (active)
+ return <WeixinDisconnect installation={active} canManage={canManage} />;
+ if (!canManage)
+ return (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.weixin.admin_only)}
+ </p>
+ );
+ if (listing.data.install_supported !== true)
+ return <p className="text-caption">{t(($) => $.weixin.not_enabled)}</p>;
+ return (
+ <div className="space-y-2">
+ {expired && <p role="status" className="text-caption text-destructive">{t(($) => $.weixin.authorization_expired)}</p>}
+ <WeixinConnect agentId={agentId} agentName={agentName} onBusyChange={onBusyChange} />
+ </div>
+ );
+}
+
+function WeixinDisconnect({
+ installation,
+ canManage,
+}: {
+ installation: WeixinInstallation;
+ canManage: boolean;
+}) {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+ const [open, setOpen] = useState(false);
+ const revoke = useMutation({
+ mutationFn: () => api.deleteWeixinInstallation(wsId, installation.id),
+ onSuccess: async () => {
+ await qc.invalidateQueries({ queryKey: weixinKeys.installations(wsId) });
+ setOpen(false);
+ },
+ });
+ return (
+ <div className="flex items-center gap-3">
+ <span className="text-caption text-muted-foreground">
+ {t(($) => $.weixin.connected)}
+ </span>
+ {canManage && (
+ <Button variant="outline" size="sm" onClick={() => setOpen(true)}>
+ {t(($) => $.weixin.disconnect)}
+ </Button>
+ )}
+ <Dialog
+ open={open}
+ onOpenChange={(value) => {
+ if (!revoke.isPending) setOpen(value);
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.weixin.disconnect_title)}</DialogTitle>
+ <DialogDescription>
+ {t(($) => $.weixin.disconnect_description)}
+ </DialogDescription>
+ </DialogHeader>
+ {revoke.isError && (
+ <p role="alert" className="text-caption text-destructive">
+ {t(($) => $.weixin.action_failed)}
+ </p>
+ )}
+ <DialogFooter>
+ <Button
+ variant="outline"
+ disabled={revoke.isPending}
+ onClick={() => setOpen(false)}
+ >
+ {t(($) => $.weixin.cancel)}
+ </Button>
+ <Button
+ variant="destructive"
+ disabled={revoke.isPending}
+ onClick={() => revoke.mutate()}
+ >
+ {t(($) => $.weixin.disconnect)}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
+
+function WeixinConnect({
+ agentId,
+ agentName,
+ onBusyChange,
+}: {
+ agentId: string;
+ agentName: string;
+ onBusyChange?: (busy: boolean) => void;
+}) {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+ const [open, setOpen] = useState(false);
+ const [loginId, setLoginId] = useState("");
+ const [code, setCode] = useState("");
+ const [closing, setClosing] = useState(false);
+ const [closeError, setCloseError] = useState(false);
+ useEffect(() => () => onBusyChange?.(false), [onBusyChange]);
+ const key = weixinKeys.login(wsId, loginId);
+ const begin = useMutation({
+ mutationFn: async () => {
+ const login = await api.beginWeixinLogin(wsId, agentId);
+ if (!login.id || login.status === "error")
+ throw new Error(t(($) => $.weixin.action_failed));
+ return login;
+ },
+ onSuccess: (login) => {
+ qc.setQueryData(weixinKeys.login(wsId, login.id), login);
+ setLoginId(login.id);
+ setCode("");
+ },
+ });
+ const poll = useQuery({
+ queryKey: key,
+ queryFn: ({ signal }) => api.pollWeixinLogin(wsId, loginId, "", signal),
+ enabled: (query) =>
+ open &&
+ !!loginId &&
+ !closing &&
+ isWeixinLoginPending(
+ (query.state.data as WeixinLogin | undefined)?.status,
+ ) &&
+ !isWeixinVerificationRequired(
+ (query.state.data as WeixinLogin | undefined)?.status,
+ ),
+ refetchInterval: (query) =>
+ !weixinConflict(query.state.error) &&
+ isWeixinLoginPending(
+ (query.state.data as WeixinLogin | undefined)?.status,
+ ) &&
+ !isWeixinVerificationRequired(
+ (query.state.data as WeixinLogin | undefined)?.status,
+ )
+ ? 2000
+ : false,
+ refetchOnWindowFocus: false,
+ retry: false,
+ gcTime: 0,
+ });
+ const login = poll.data;
+ const refetchLogin = poll.refetch;
+ const verify = useMutation({
+ mutationFn: () => api.pollWeixinLogin(wsId, loginId, code.trim()),
+ onSuccess: (value) => {
+ qc.setQueryData(key, value);
+ setCode("");
+ },
+ });
+ useEffect(() => {
+ if (login?.status === "confirmed")
+ void qc.invalidateQueries({ queryKey: weixinKeys.installations(wsId) });
+ }, [login?.status, qc, wsId]);
+ useEffect(() => {
+ if (!open || !login || !isWeixinLoginPending(login.status)) return;
+ const delay = Date.parse(login.expires_at) - Date.now();
+ if (!Number.isFinite(delay)) return;
+ const timer = setTimeout(
+ () => {
+ void refetchLogin();
+ },
+ Math.max(0, delay),
+ );
+ return () => clearTimeout(timer);
+ }, [open, login, refetchLogin]);
+
+ async function close() {
+ if (begin.isPending || verify.isPending || closing) return;
+ setClosing(true);
+ setCloseError(false);
+ try {
+ await qc.cancelQueries({ queryKey: key });
+ if (loginId) await api.cancelWeixinLogin(wsId, loginId);
+ await qc.invalidateQueries({ queryKey: weixinKeys.installations(wsId) });
+ qc.removeQueries({ queryKey: key });
+ setOpen(false);
+ onBusyChange?.(false);
+ setLoginId("");
+ setCode("");
+ } catch {
+ setCloseError(true);
+ } finally {
+ setClosing(false);
+ }
+ }
+
+ function start() {
+ onBusyChange?.(true);
+ setOpen(true);
+ setLoginId("");
+ begin.mutate();
+ }
+
+ const pending = isWeixinLoginPending(login?.status);
+ const status = login?.status;
+ const statusText =
+ status === "confirmed"
+ ? t(($) => $.weixin.success)
+ : status === "scaned" || status === "scaned_but_redirect"
+ ? t(($) => $.weixin.scanned)
+ : isWeixinVerificationRequired(status)
+ ? t(($) => $.weixin.verify_hint)
+ : status === "expired"
+ ? t(($) => $.weixin.expired)
+ : status === "verify_code_blocked"
+ ? t(($) => $.weixin.blocked)
+ : status === "binded_redirect"
+ ? t(($) => $.weixin.already_bound)
+ : status === "error" || status === "cancelled"
+ ? t(($) => $.weixin.action_failed)
+ : t(($) => $.weixin.scan_hint);
+ const failed = begin.isError || poll.isError || verify.isError || closeError;
+ const error = begin.error ?? poll.error ?? verify.error;
+ const conflict = weixinConflict(error);
+ const errorText = conflict
+ ? conflict.agent_name
+ ? t(($) => $.weixin.already_connected, { agent: conflict.agent_name })
+ : t(($) => $.weixin.connected_elsewhere)
+ : clientErrorMessage(error) ?? t(($) => $.weixin.action_failed);
+ return (
+ <>
+ <Button variant="outline" size="sm" onClick={start}>
+ <WeChat className="size-4" aria-hidden="true" />
+ {t(($) => $.weixin.connect)}
+ </Button>
+ <Dialog
+ open={open}
+ onOpenChange={(value) => {
+ if (!value) void close();
+ }}
+ >
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>
+ {t(($) => $.weixin.connect_title, { agent: agentName })}
+ </DialogTitle>
+ <DialogDescription>
+ {t(($) => $.weixin.privacy_hint)}
+ </DialogDescription>
+ </DialogHeader>
+ {begin.isPending ? (
+ <p role="status">{t(($) => $.weixin.loading)}</p>
+ ) : (
+ <>
+ {pending && !conflict && login?.qr_code_url && (
+ <div className="mx-auto rounded-lg bg-white p-4">
+ <QRCode
+ value={login.qr_code_url}
+ size={200}
+ title={t(($) => $.weixin.qr_label)}
+ />
+ </div>
+ )}
+ {!conflict && (
+ <p role="status" className="text-body">
+ {statusText}
+ </p>
+ )}
+ {isWeixinVerificationRequired(status) && (
+ <form
+ className="space-y-3"
+ onSubmit={(event) => {
+ event.preventDefault();
+ verify.mutate();
+ }}
+ >
+ <Label htmlFor={`weixin-code-${agentId}`}>
+ {t(($) => $.weixin.verify_label)}
+ </Label>
+ <Input
+ id={`weixin-code-${agentId}`}
+ inputMode="numeric"
+ autoComplete="one-time-code"
+ pattern="[0-9]+"
+ maxLength={12}
+ value={code}
+ onChange={(event) => setCode(event.target.value)}
+ disabled={verify.isPending}
+ />
+ <Button
+ type="submit"
+ disabled={verify.isPending || !/^\d{1,12}$/.test(code)}
+ >
+ {t(($) => $.weixin.verify)}
+ </Button>
+ </form>
+ )}
+ </>
+ )}
+ {failed && (
+ <p role="alert" className="text-caption text-destructive">
+ {errorText}
+ </p>
+ )}
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={() => void close()}
+ disabled={begin.isPending || verify.isPending || closing}
+ >
+ {t(($) => $.weixin.close)}
+ </Button>
+ {!begin.isPending &&
+ status !== "confirmed" &&
+ (!pending || begin.isError) && (
+ <Button onClick={start}>{t(($) => $.weixin.refresh)}</Button>
+ )}
+ {poll.isError && pending && (
+ <Button onClick={() => void poll.refetch()}>
+ {t(($) => $.weixin.retry)}
+ </Button>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index b93a5a1ed8..2c36f48423 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -140,6 +140,9 @@ var pgBigmOperatorClass = extensionOperatorClass{
// they are still pending: a fresh self-hosted install, which is exactly where an
// interrupted build would otherwise leave a permanently unusable index.
var concurrentIndexCleanups = map[string]string{
+ "671_weixin_account_state_unique_index": "weixin_account_state_pkey",
+ "669_weixin_login_session_unique_index": "weixin_login_session_pkey",
+ "666_weixin_login_expiry_idx": "weixin_login_expiry_idx",
"662_chat_task_supplement_message": "uq_chat_task_supplement_message",
"663_chat_task_supplement_task": "idx_chat_task_supplement_task",
"664_chat_task_supplement_workspace": "idx_chat_task_supplement_workspace",
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 742ad7af2d..bc73e8369c 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -788,6 +788,12 @@ func main() {
if h.TelegramOutbound != nil {
h.TelegramOutbound.Start(sweepCtx)
}
+ if h.WeixinOutbound != nil {
+ h.WeixinOutbound.Start(sweepCtx)
+ }
+ if h.WeixinInstall != nil {
+ go h.WeixinInstall.RunCleanup(sweepCtx)
+ }
// GitHub PR-card API snapshot pipeline (MUL-5265): worker pool + TTL sweeper.
// No-op when unconfigured (no App private key).
h.PRRefresh.Start(sweepCtx)
@@ -948,6 +954,9 @@ func main() {
}
},
JoinTelegram: func() {
+ if h.WeixinOutbound != nil && !h.WeixinOutbound.WaitWithTimeout(5*time.Second) {
+ slog.Warn("weixin outbound workers did not exit within shutdown timeout")
+ }
if h.TelegramOutbound != nil && !h.TelegramOutbound.WaitWithTimeout(5*time.Second) {
slog.Warn("telegram outbound workers did not exit within shutdown timeout")
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index d7dcdb0324..09cc720a2c 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -39,6 +39,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/slack"
"github.com/multica-ai/multica/server/internal/integrations/telegram"
"github.com/multica-ai/multica/server/internal/integrations/wecom"
+ "github.com/multica-ai/multica/server/internal/integrations/weixin"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/realtime"
@@ -1245,6 +1246,31 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
slog.Info("wecom integration disabled (MULTICA_WECOM_SECRET_KEY not set)")
}
+ // WeChat iLink needs only an at-rest key; users authorize their bot by QR.
+ if key, err := secretbox.LoadKey("MULTICA_WEIXIN_SECRET_KEY"); err == nil {
+ box, boxErr := secretbox.New(key)
+ if boxErr != nil {
+ slog.Error("weixin: encryption setup failed", "error", boxErr)
+ } else if install, installErr := weixin.NewInstallService(queries, pool, box); installErr != nil {
+ slog.Error("weixin: install service setup failed", "error", installErr)
+ } else {
+ outbound := weixin.NewOutbound(queries, box, slog.Default())
+ media := weixin.NewMediaResolver(nil, nil)
+ if store != nil {
+ media = weixin.NewMediaResolver(store, engine.NewDBMediaIntentLedger(queries))
+ outbound.EnableFileDelivery(store)
+ h.DeclareChannelFileDelivery(string(weixin.TypeWeixin))
+ }
+ channelRouter.Register(weixin.TypeWeixin, weixin.NewWeixinResolverSet(queries, pool, outbound, outbound.Typing, media))
+ weixin.RegisterWeixin(channelRegistry, weixin.ChannelDeps{Queries: queries, Box: box, Logger: slog.Default(), Typing: outbound.Typing, Bus: bus})
+ outbound.Register(bus)
+ h.WeixinInstall, h.WeixinOutbound = install, outbound
+ slog.Info("weixin integration enabled (QR login and long polling)")
+ }
+ } else {
+ slog.Info("weixin integration disabled (MULTICA_WEIXIN_SECRET_KEY not set)")
+ }
+
// Telegram integration. Same shape as Slack: BYO bot token pasted at
// install, one getUpdates long-polling loop per active installation
// supervised by the shared engine.Supervisor, resolvers on the generic
@@ -1976,6 +2002,18 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/dingtalk/install/byo", h.RegisterDingTalkBYO)
})
+ r.Group(func(r chi.Router) {
+ r.Use(middleware.RequireWorkspaceMemberFromURL(queries, "id"))
+ r.Get("/weixin/installations", h.ListWeixinInstallations)
+ })
+ r.Group(func(r chi.Router) {
+ r.Use(middleware.RequireWorkspaceRoleFromURL(queries, "id", "owner", "admin"))
+ r.Post("/weixin/logins", h.BeginWeixinLogin)
+ r.Post("/weixin/logins/{loginId}/poll", h.PollWeixinLogin)
+ r.Delete("/weixin/logins/{loginId}", h.CancelWeixinLogin)
+ r.Delete("/weixin/installations/{installationId}", h.RevokeWeixinInstallation)
+ })
+
// Telegram integration. Same admin/member split as Slack:
// listing is member-visible; install + revoke are admin-only.
r.Group(func(r chi.Router) {
diff --git a/server/cmd/server/weixin_routes_test.go b/server/cmd/server/weixin_routes_test.go
new file mode 100644
index 0000000000..6c56a40d5a
--- /dev/null
+++ b/server/cmd/server/weixin_routes_test.go
@@ -0,0 +1,36 @@
+package main
+
+import (
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func TestWeixinRoutesRequireWorkspaceAdminForQRAndDisconnect(t *testing.T) {
+ f := testutil.New(testPool, testWorkspaceID, testUserID)
+ user := f.User(t, "WeChat route member", "weixin-route-"+time.Now().Format("150405.000000000")+"@example.test")
+ f.Member(t, testWorkspaceID, user, "member")
+ token, err := generateTestJWT(user, "[email protected]", "WeChat route member")
+ if err != nil {
+ t.Fatal(err)
+ }
+ base := "/api/workspaces/" + testWorkspaceID + "/weixin"
+ for _, tc := range []struct {
+ method, path string
+ want int
+ }{
+ {http.MethodGet, base + "/installations", http.StatusOK},
+ {http.MethodPost, base + "/logins?agent_id=11111111-1111-4111-8111-111111111111", http.StatusForbidden},
+ {http.MethodPost, base + "/logins/11111111-1111-4111-8111-111111111111/poll", http.StatusForbidden},
+ {http.MethodDelete, base + "/logins/11111111-1111-4111-8111-111111111111", http.StatusForbidden},
+ {http.MethodDelete, base + "/installations/11111111-1111-4111-8111-111111111111", http.StatusForbidden},
+ } {
+ t.Run(tc.method+tc.path, func(t *testing.T) {
+ req := testutil.JSONRequest(tc.method, tc.path, map[string]string{})
+ testutil.WithHeaders(req, "Authorization", "Bearer "+token, "X-Workspace-ID", testWorkspaceID)
+ testutil.Call(t, testServer.Config.Handler.ServeHTTP, req).Want(tc.want)
+ })
+ }
+}
diff --git a/server/internal/daemon/execenv/channel_type.go b/server/internal/daemon/execenv/channel_type.go
index fb2753e463..9d9fa7a880 100644
--- a/server/internal/daemon/execenv/channel_type.go
+++ b/server/internal/daemon/execenv/channel_type.go
@@ -18,6 +18,7 @@ const (
ChannelTypeWecom = "wecom"
ChannelTypeDingtalk = "dingtalk"
ChannelTypeTelegram = "telegram"
+ ChannelTypeWeixin = "weixin"
)
// SurfacePersistsTranscript reports whether a chat surface stores its
@@ -30,7 +31,7 @@ const (
// so a future non-persisting channel is never told "read it back".
func SurfacePersistsTranscript(channelType string) bool {
switch channelType {
- case "", ChannelTypeFeishu, ChannelTypeWecom, ChannelTypeDingtalk:
+ case "", ChannelTypeFeishu, ChannelTypeWecom, ChannelTypeDingtalk, ChannelTypeWeixin:
return true
default:
return false
@@ -129,6 +130,8 @@ func ChannelDisplayName(channelType string) string {
return "WeCom"
case ChannelTypeDingtalk:
return "DingTalk"
+ case ChannelTypeWeixin:
+ return "WeChat"
case ChannelTypeTelegram:
return "Telegram"
default:
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index b163ea0e66..98a1bf7297 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -34,6 +34,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/slack"
"github.com/multica-ai/multica/server/internal/integrations/telegram"
"github.com/multica-ai/multica/server/internal/integrations/wecom"
+ "github.com/multica-ai/multica/server/internal/integrations/weixin"
"github.com/multica-ai/multica/server/internal/issuestatus"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
@@ -403,6 +404,9 @@ type Handler struct {
// enqueues EventChatDone work.
TelegramOutbound *telegram.Outbound
+ WeixinInstall *weixin.InstallService
+ WeixinOutbound *weixin.Outbound
+
// channelFileDelivery names the channel types that can, IN THIS
// DEPLOYMENT, carry a file the agent produced the last hop into the
// conversation. It answers the claim response's
diff --git a/server/internal/handler/weixin.go b/server/internal/handler/weixin.go
new file mode 100644
index 0000000000..f820a21d4e
--- /dev/null
+++ b/server/internal/handler/weixin.go
@@ -0,0 +1,203 @@
+package handler
+
+import (
+ "encoding/json"
+ "errors"
+ "net/http"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/multica-ai/multica/server/internal/integrations/weixin"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+type WeixinInstallationResponse struct {
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ AgentID string `json:"agent_id"`
+ BotID string `json:"bot_id"`
+ UserID string `json:"user_id"`
+ InstallerUserID string `json:"installer_user_id"`
+ Status string `json:"status"`
+ InstalledAt string `json:"installed_at"`
+}
+
+func weixinInstallationResponse(row db.ChannelInstallation) WeixinInstallationResponse {
+ info := weixin.DecodePublicConfig(row.Config)
+ if row.Status == "revoked" && info.AuthorizationExpired {
+ row.Status = "expired"
+ }
+ return WeixinInstallationResponse{ID: uuidToString(row.ID), WorkspaceID: uuidToString(row.WorkspaceID), AgentID: uuidToString(row.AgentID), BotID: info.BotID, UserID: info.UserID, InstallerUserID: uuidToString(row.InstallerUserID), Status: row.Status, InstalledAt: row.InstalledAt.Time.UTC().Format(time.RFC3339)}
+}
+
+func (h *Handler) ListWeixinInstallations(w http.ResponseWriter, r *http.Request) {
+ workspace, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ out := []WeixinInstallationResponse{}
+ if h.WeixinInstall != nil {
+ rows, err := h.WeixinInstall.List(r.Context(), workspace)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list WeChat connections")
+ return
+ }
+ for _, row := range rows {
+ out = append(out, weixinInstallationResponse(row))
+ }
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"installations": out, "configured": h.WeixinInstall != nil, "install_supported": h.WeixinInstall != nil})
+}
+
+func (h *Handler) BeginWeixinLogin(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ if h.WeixinInstall == nil {
+ writeFeatureDisabled(w, "weixin_not_configured", "WeChat integration is not enabled")
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspace, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ initiator, ok := parseUUIDOrBadRequest(w, userID, "user id")
+ if !ok {
+ return
+ }
+ agent, ok := parseUUIDOrBadRequest(w, r.URL.Query().Get("agent_id"), "agent_id")
+ if !ok {
+ return
+ }
+ row, err := h.Queries.GetAgentInWorkspace(r.Context(), db.GetAgentInWorkspaceParams{ID: agent, WorkspaceID: workspace})
+ if err != nil || row.ArchivedAt.Valid {
+ writeError(w, http.StatusNotFound, "agent not found in this workspace")
+ return
+ }
+ view, err := h.WeixinInstall.Begin(r.Context(), workspace, agent, initiator)
+ if err != nil {
+ writeWeixinError(w, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, view)
+}
+
+// POST because a confirmed provider response commits the binding. Both the
+// session and its QR view are scoped to the initiating signed-in admin.
+func (h *Handler) PollWeixinLogin(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ if h.WeixinInstall == nil {
+ writeFeatureDisabled(w, "weixin_not_configured", "WeChat integration is not enabled")
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspace, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ initiator, ok := parseUUIDOrBadRequest(w, userID, "user id")
+ if !ok {
+ return
+ }
+ session, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "loginId"), "login id")
+ if !ok {
+ return
+ }
+ var body struct {
+ VerifyCode string `json:"verify_code"`
+ }
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024)).Decode(&body); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ view, err := h.WeixinInstall.Poll(r.Context(), session, workspace, initiator, body.VerifyCode)
+ if err != nil {
+ writeWeixinError(w, err)
+ return
+ }
+ if view.Status == "confirmed" {
+ h.publish(protocol.EventWeixinInstallationCreated, uuidToString(workspace), "user", userID, map[string]any{"id": view.InstallationID})
+ }
+ writeJSON(w, http.StatusOK, view)
+}
+
+func (h *Handler) CancelWeixinLogin(w http.ResponseWriter, r *http.Request) {
+ if h.WeixinInstall == nil {
+ writeFeatureDisabled(w, "weixin_not_configured", "WeChat integration is not enabled")
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspace, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ initiator, ok := parseUUIDOrBadRequest(w, userID, "user id")
+ if !ok {
+ return
+ }
+ session, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "loginId"), "login id")
+ if !ok {
+ return
+ }
+ if err := h.WeixinInstall.Cancel(r.Context(), session, workspace, initiator); err != nil {
+ writeWeixinError(w, err)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
+func (h *Handler) RevokeWeixinInstallation(w http.ResponseWriter, r *http.Request) {
+ if h.WeixinInstall == nil {
+ writeFeatureDisabled(w, "weixin_not_configured", "WeChat integration is not enabled")
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspace, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ installation, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "installationId"), "installation id")
+ if !ok {
+ return
+ }
+ if err := h.WeixinInstall.Revoke(r.Context(), installation, workspace); err != nil {
+ writeWeixinError(w, err)
+ return
+ }
+ h.publish(protocol.EventWeixinInstallationRevoked, uuidToString(workspace), "user", userID, map[string]any{"id": uuidToString(installation)})
+ w.WriteHeader(http.StatusNoContent)
+}
+
+func writeWeixinError(w http.ResponseWriter, err error) {
+ switch {
+ case errors.Is(err, weixin.ErrNotFound):
+ writeError(w, http.StatusNotFound, "WeChat login or connection not found")
+ case errors.Is(err, weixin.ErrInvalidCode):
+ writeError(w, http.StatusBadRequest, "enter the numeric verification code shown in WeChat")
+ case errors.Is(err, weixin.ErrConflict):
+ body := map[string]any{"code": "weixin_already_connected", "error": "this WeChat account is already connected; disconnect it before changing its agent"}
+ var conflict *weixin.ConflictError
+ if errors.As(err, &conflict) {
+ body["agent_id"], body["agent_name"] = conflict.AgentID, conflict.AgentName
+ }
+ writeJSON(w, http.StatusConflict, body)
+ case errors.Is(err, weixin.ErrBusy):
+ writeError(w, http.StatusConflict, "this login is being checked; try again shortly")
+ case errors.Is(err, weixin.ErrAccess):
+ writeError(w, http.StatusForbidden, "workspace or agent access changed")
+ default:
+ writeError(w, http.StatusServiceUnavailable, "could not complete WeChat login; check the server connection and try again")
+ }
+}
diff --git a/server/internal/handler/weixin_test.go b/server/internal/handler/weixin_test.go
new file mode 100644
index 0000000000..a267c1b647
--- /dev/null
+++ b/server/internal/handler/weixin_test.go
@@ -0,0 +1,85 @@
+package handler
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/weixin"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestWeixinPublicInstallationOmitsCredentials(t *testing.T) {
+ row := db.ChannelInstallation{Config: []byte(`{"app_id":"public-bot","user_id":"public-user","bot_token_encrypted":"private-ciphertext","base_url":"https://ilinkai.weixin.qq.com"}`)}
+ raw, err := json.Marshal(weixinInstallationResponse(row))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(raw), "public-bot") || !strings.Contains(string(raw), "public-user") {
+ t.Fatal("public identity missing")
+ }
+ for _, secret := range []string{"private-ciphertext", "bot_token", "base_url", "ws_lease"} {
+ if strings.Contains(string(raw), secret) {
+ t.Fatalf("public response exposes %s", secret)
+ }
+ }
+}
+
+func TestDeleteWorkspaceRemovesWeixinLoginAndReplyContext(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ws := dbfx.Workspace(t, "WeChat cleanup", "weixin-cleanup")
+ dbfx.Member(t, ws, testUserID, "owner")
+ agent := dbfx.Insert(t, "agent", testutil.Cols{
+ "workspace_id": ws, "name": "WeChat cleanup", "owner_id": testUserID, "runtime_mode": "cloud",
+ })
+ installation := dbfx.Insert(t, "channel_installation", testutil.Cols{
+ "workspace_id": ws, "agent_id": agent, "channel_type": "weixin", "installer_user_id": testUserID,
+ })
+ dbfx.Insert(t, "weixin_login_session", testutil.Cols{
+ "id": testutil.Raw("gen_random_uuid()"),
+ "workspace_id": ws, "agent_id": agent, "initiator_user_id": testUserID,
+ "state_encrypted": []byte("test-ciphertext"), "expires_at": testutil.Raw("now() + interval '5 minutes'"),
+ })
+ dbfx.InsertNoID(t, "weixin_account_state", testutil.Cols{
+ "installation_id": installation, "bot_id": "cleanup-bot", "user_id": "cleanup-scanner",
+ "context_token_encrypted": []byte("test-reply-ciphertext"),
+ }, "installation_id=$1", installation)
+ req := withURLParam(newRequest(http.MethodDelete, "/api/workspaces/"+ws, nil), "id", ws)
+ testutil.Call(t, testHandler.DeleteWorkspace, req).Want(http.StatusNoContent)
+ if dbfx.Count(t, "SELECT count(*) FROM weixin_login_session WHERE workspace_id=$1", ws) != 0 || dbfx.Count(t, "SELECT count(*) FROM weixin_account_state WHERE installation_id=$1", installation) != 0 {
+ t.Fatal("workspace deletion retained WeChat login or reply credentials")
+ }
+}
+
+func TestWeixinConflictResponseNamesScopedAgent(t *testing.T) {
+ w := httptest.NewRecorder()
+ writeWeixinError(w, &weixin.ConflictError{AgentID: "agent-id", AgentName: "Assistant"})
+ var body map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatal(err)
+ }
+ if w.Code != http.StatusConflict || body["code"] != "weixin_already_connected" || body["agent_name"] != "Assistant" {
+ t.Fatalf("conflict body: %s", w.Body.String())
+ }
+ w = httptest.NewRecorder()
+ writeWeixinError(w, weixin.ErrConflict)
+ if strings.Contains(w.Body.String(), "agent_id") || strings.Contains(w.Body.String(), "agent_name") {
+ t.Fatal("unscoped conflict exposed agent details")
+ }
+}
+
+func TestWeixinExpiredAuthorizationProjection(t *testing.T) {
+ row := db.ChannelInstallation{Status: "revoked", Config: []byte(`{"authorization_expired":true}`)}
+ if got := weixinInstallationResponse(row); got.Status != "expired" {
+ t.Fatalf("status=%s", got.Status)
+ }
+ row.Config = []byte(`{}`)
+ if got := weixinInstallationResponse(row); got.Status != "revoked" {
+ t.Fatal("manual disconnect shown as expired")
+ }
+}
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index e8add98f88..1d3cc5a0bc 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -154,6 +154,8 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"verification_code": workspaceDeleteKeep,
"webhook_delivery": workspaceDelete,
"wecom_install_session": workspaceDelete,
+ "weixin_login_session": workspaceDelete,
+ "weixin_account_state": workspaceDelete,
"workspace_composio_connection": workspaceDelete,
"agent_app": workspaceDelete,
"app_action_rule": workspaceDelete,
diff --git a/server/internal/integrations/weixin/api.go b/server/internal/integrations/weixin/api.go
new file mode 100644
index 0000000000..e276b4562f
--- /dev/null
+++ b/server/internal/integrations/weixin/api.go
@@ -0,0 +1,402 @@
+// Package weixin connects WeChat iLink Bot conversations to Multica channels.
+package weixin
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/binary"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+)
+
+const (
+ DefaultBaseURL = "https://ilinkai.weixin.qq.com"
+ protocolVersion = "2.4.10"
+ apiTimeout = 15 * time.Second
+ pollTimeout = 40 * time.Second
+ maxResponseBytes = 4 << 20
+)
+
+var (
+ ErrProtocol = errors.New("weixin: invalid provider response")
+ ErrTokenExpired = errors.New("weixin: authorization expired; reconnect WeChat")
+ ErrNoContext = errors.New("weixin: send a new WeChat message before replying")
+)
+
+// ProviderError contains only codes: provider bodies can contain credentials.
+type ProviderError struct {
+ Status int
+ Code int
+}
+
+func (e *ProviderError) Error() string {
+ return fmt.Sprintf("weixin: provider rejected request (HTTP %d, code %d)", e.Status, e.Code)
+}
+
+type apiResult struct {
+ Ret *int `json:"ret"`
+ ErrCode int `json:"errcode"`
+}
+
+func (r apiResult) check(required bool) error {
+ if r.ErrCode == -14 || r.Ret != nil && *r.Ret == -14 {
+ return ErrTokenExpired
+ }
+ code := r.ErrCode
+ if code == 0 && r.Ret != nil {
+ code = *r.Ret
+ }
+ if code != 0 {
+ return &ProviderError{Status: http.StatusOK, Code: code}
+ }
+ if required && r.Ret == nil {
+ return ErrProtocol
+ }
+ return nil
+}
+
+// id preserves 64-bit provider identifiers without passing through float64.
+type id string
+
+func (v *id) UnmarshalJSON(b []byte) error {
+ if len(b) == 0 || string(b) == "null" {
+ return nil
+ }
+ if b[0] == '"' {
+ return json.Unmarshal(b, (*string)(v))
+ }
+ var n json.Number
+ if err := json.Unmarshal(b, &n); err != nil {
+ return err
+ }
+ if _, err := strconv.ParseUint(n.String(), 10, 64); err != nil {
+ return err
+ }
+ *v = id(n.String())
+ return nil
+}
+
+type mediaRef struct {
+ Query string `json:"encrypt_query_param,omitempty"`
+ AESKey string `json:"aes_key,omitempty"`
+ EncryptType int `json:"encrypt_type,omitempty"`
+ FullURL string `json:"full_url,omitempty"`
+}
+
+type messageItem struct {
+ Type int `json:"type"`
+ Text *struct {
+ Text string `json:"text"`
+ } `json:"text_item,omitempty"`
+ Image *struct {
+ Media mediaRef `json:"media"`
+ AESKey string `json:"aeskey,omitempty"`
+ Size int64 `json:"mid_size,omitempty"`
+ } `json:"image_item,omitempty"`
+ Voice *struct {
+ Media mediaRef `json:"media"`
+ Text string `json:"text,omitempty"`
+ } `json:"voice_item,omitempty"`
+ File *struct {
+ Media mediaRef `json:"media"`
+ Name string `json:"file_name"`
+ Length string `json:"len,omitempty"`
+ } `json:"file_item,omitempty"`
+ Video *struct {
+ Media mediaRef `json:"media"`
+ Size int64 `json:"video_size,omitempty"`
+ } `json:"video_item,omitempty"`
+}
+
+type message struct {
+ ID id `json:"message_id,omitempty"`
+ From string `json:"from_user_id"`
+ To string `json:"to_user_id"`
+ ClientID string `json:"client_id,omitempty"`
+ Type int `json:"message_type"`
+ State *int `json:"message_state,omitempty"`
+ GroupID string `json:"group_id,omitempty"`
+ CreatedAt int64 `json:"create_time_ms,omitempty"`
+ ContextToken string `json:"context_token,omitempty"`
+ Items []messageItem `json:"item_list"`
+}
+
+type qrResult struct {
+ apiResult
+ QRCode string `json:"qrcode"`
+ Content string `json:"qrcode_img_content"`
+}
+
+type qrStatus struct {
+ apiResult
+ Status string `json:"status"`
+ Token string `json:"bot_token"`
+ BotID string `json:"ilink_bot_id"`
+ UserID string `json:"ilink_user_id"`
+ BaseURL string `json:"baseurl"`
+ RedirectHost string `json:"redirect_host"`
+}
+
+type updates struct {
+ apiResult
+ Messages []message `json:"msgs"`
+ Cursor string `json:"get_updates_buf"`
+ TimeoutMS int64 `json:"longpolling_timeout_ms"`
+}
+
+type apiClient struct {
+ baseURL string
+ token string
+ http *http.Client
+}
+
+func newAPI(baseURL, token string, client *http.Client) *apiClient {
+ if baseURL == "" {
+ baseURL = DefaultBaseURL
+ }
+ if client == nil {
+ client = &http.Client{Timeout: pollTimeout}
+ }
+ copy := *client
+ copy.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ return &apiClient{baseURL: strings.TrimRight(baseURL, "/"), token: token, http: &copy}
+}
+
+// The provider can move an account to another WeChat IDC during QR login.
+// Neither a browser-supplied URL nor an arbitrary redirect may receive tokens.
+func validateBaseURL(raw string) (string, error) {
+ u, err := url.Parse(raw)
+ if err != nil || u.Scheme != "https" || u.User != nil || u.Port() != "" || u.RawQuery != "" || u.Fragment != "" || u.Path != "" && u.Path != "/" {
+ return "", ErrProtocol
+ }
+ host := strings.ToLower(u.Hostname())
+ if !strings.HasSuffix(host, ".weixin.qq.com") {
+ return "", ErrProtocol
+ }
+ return "https://" + host, nil
+}
+
+func (c *apiClient) request(ctx context.Context, method, endpoint string, body any, authenticated bool, result any) error {
+ var reader io.Reader
+ if body != nil {
+ b, err := json.Marshal(body)
+ if err != nil {
+ return err
+ }
+ reader = bytes.NewReader(b)
+ }
+ req, err := http.NewRequestWithContext(ctx, method, c.baseURL+"/ilink/bot/"+endpoint, reader)
+ if err != nil {
+ return ErrProtocol
+ }
+ req.Header.Set("iLink-App-Id", "bot")
+ req.Header.Set("iLink-App-ClientVersion", strconv.Itoa(2<<16|4<<8|10))
+ if method == http.MethodPost {
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("AuthorizationType", "ilink_bot_token")
+ var random [4]byte
+ if _, err := rand.Read(random[:]); err != nil {
+ return err
+ }
+ req.Header.Set("X-WECHAT-UIN", base64.StdEncoding.EncodeToString([]byte(strconv.FormatUint(uint64(binary.BigEndian.Uint32(random[:])), 10))))
+ }
+ if authenticated {
+ if c.token == "" {
+ return ErrTokenExpired
+ }
+ req.Header.Set("Authorization", "Bearer "+c.token)
+ }
+ resp, err := c.http.Do(req)
+ if err != nil {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ // net/url errors can include the QR code or verification code in URLs.
+ return errors.New("weixin: provider request failed")
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return &ProviderError{Status: resp.StatusCode}
+ }
+ b, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes+1))
+ if err != nil || len(b) > maxResponseBytes {
+ return ErrProtocol
+ }
+ if result == nil {
+ return nil
+ }
+ if err := json.Unmarshal(b, result); err != nil {
+ return ErrProtocol
+ }
+ return nil
+}
+
+func baseInfo() map[string]string {
+ return map[string]string{"channel_version": protocolVersion, "bot_agent": "Multica"}
+}
+
+func (c *apiClient) QRCode(ctx context.Context, tokens ...string) (qrResult, error) {
+ ctx, cancel := context.WithTimeout(ctx, apiTimeout)
+ defer cancel()
+ var result qrResult
+ if tokens == nil {
+ tokens = []string{}
+ }
+ err := c.request(ctx, http.MethodPost, "get_bot_qrcode?bot_type=3", map[string]any{"local_token_list": tokens}, false, &result)
+ if err != nil {
+ return result, err
+ }
+ if err := result.check(false); err != nil {
+ return result, err
+ }
+ if result.QRCode == "" || result.Content == "" {
+ return result, ErrProtocol
+ }
+ return result, nil
+}
+
+func (c *apiClient) QRStatus(ctx context.Context, qr, verifyCode string) (qrStatus, error) {
+ ctx, cancel := context.WithTimeout(ctx, pollTimeout)
+ defer cancel()
+ q := url.Values{"qrcode": {qr}}
+ if verifyCode != "" {
+ q.Set("verify_code", verifyCode)
+ }
+ var result qrStatus
+ err := c.request(ctx, http.MethodGet, "get_qrcode_status?"+q.Encode(), nil, false, &result)
+ if err != nil {
+ return result, err
+ }
+ if err := result.check(false); err != nil {
+ return result, err
+ }
+ if strings.Contains(result.Status, "need_verifycode") {
+ return result, nil
+ }
+ switch result.Status {
+ case "wait", "scaned", "expired", "verify_code_blocked", "binded_redirect":
+ case "scaned_but_redirect":
+ if _, err := validateBaseURL("https://" + result.RedirectHost); err != nil {
+ return result, err
+ }
+ case "confirmed":
+ if result.Token == "" || result.BotID == "" || result.UserID == "" {
+ return result, ErrProtocol
+ }
+ if result.BaseURL == "" {
+ result.BaseURL = DefaultBaseURL
+ if base, err := validateBaseURL(c.baseURL); err == nil {
+ result.BaseURL = base
+ }
+ }
+ if _, err := validateBaseURL(result.BaseURL); err != nil {
+ return result, err
+ }
+ default:
+ return result, ErrProtocol
+ }
+ return result, nil
+}
+
+func (c *apiClient) Updates(ctx context.Context, cursor string) (updates, error) {
+ ctx, cancel := context.WithTimeout(ctx, pollTimeout)
+ defer cancel()
+ var result updates
+ err := c.request(ctx, http.MethodPost, "getupdates", map[string]any{"get_updates_buf": cursor, "base_info": baseInfo()}, true, &result)
+ if err != nil {
+ return result, err
+ }
+ if err := result.check(false); err != nil {
+ return result, err
+ }
+ // Successful polls may omit ret; still reject bodies with no update fields.
+ if result.Ret == nil && result.Messages == nil && result.Cursor == "" {
+ return result, ErrProtocol
+ }
+ return result, nil
+}
+
+func (c *apiClient) Send(ctx context.Context, msg message) (string, error) {
+ if msg.ContextToken == "" {
+ return "", ErrNoContext
+ }
+ ctx, cancel := context.WithTimeout(ctx, apiTimeout)
+ defer cancel()
+ var result struct {
+ apiResult
+ MessageID id `json:"message_id"`
+ }
+ err := c.request(ctx, http.MethodPost, "sendmessage", map[string]any{"msg": msg, "base_info": baseInfo()}, true, &result)
+ if err != nil {
+ return "", err
+ }
+ if err := result.check(false); err != nil {
+ return "", err
+ }
+ // Some successful responses omit a server ID. The stable client ID records
+ // acceptance, not proof that the recipient read or received the message.
+ if result.MessageID == "" {
+ return msg.ClientID, nil
+ }
+ return string(result.MessageID), nil
+}
+
+func textMessage(to, token, clientID, text string) message {
+ finished := 2
+ item := messageItem{Type: 1}
+ item.Text = &struct {
+ Text string `json:"text"`
+ }{Text: text}
+ return message{To: to, ClientID: clientID, Type: 2, State: &finished, ContextToken: token, Items: []messageItem{item}}
+}
+
+func (c *apiClient) notify(ctx context.Context, start bool) error {
+ ctx, cancel := context.WithTimeout(ctx, apiTimeout)
+ defer cancel()
+ endpoint := "msg/notifystop"
+ if start {
+ endpoint = "msg/notifystart"
+ }
+ var result apiResult
+ if err := c.request(ctx, http.MethodPost, endpoint, map[string]any{"base_info": baseInfo()}, true, &result); err != nil {
+ return err
+ }
+ return result.check(false)
+}
+
+func (c *apiClient) typingTicket(ctx context.Context, user, replyContext string) (string, error) {
+ ctx, cancel := context.WithTimeout(ctx, apiTimeout)
+ defer cancel()
+ var result struct {
+ apiResult
+ Ticket string `json:"typing_ticket"`
+ }
+ err := c.request(ctx, http.MethodPost, "getconfig", map[string]any{"ilink_user_id": user, "context_token": replyContext, "base_info": baseInfo()}, true, &result)
+ if err != nil {
+ return "", err
+ }
+ if err := result.check(true); err != nil {
+ return "", err
+ }
+ if result.Ticket == "" {
+ return "", ErrProtocol
+ }
+ return result.Ticket, nil
+}
+
+func (c *apiClient) sendTyping(ctx context.Context, user, ticket string, status int) error {
+ ctx, cancel := context.WithTimeout(ctx, apiTimeout)
+ defer cancel()
+ // The provider does not promise a JSON response for this cosmetic request.
+ reqBody := map[string]any{"ilink_user_id": user, "typing_ticket": ticket, "status": status, "base_info": baseInfo()}
+ return c.request(ctx, http.MethodPost, "sendtyping", reqBody, true, nil)
+}
diff --git a/server/internal/integrations/weixin/api_test.go b/server/internal/integrations/weixin/api_test.go
new file mode 100644
index 0000000000..6070f6e58d
--- /dev/null
+++ b/server/internal/integrations/weixin/api_test.go
@@ -0,0 +1,223 @@
+package weixin
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestQRLoginProtocol(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Authorization") != "" {
+ t.Error("QR login must not send a bot token")
+ }
+ if r.Header.Get("iLink-App-Id") != "bot" {
+ t.Error("missing app id")
+ }
+ switch r.URL.Path {
+ case "/ilink/bot/get_bot_qrcode":
+ if r.Method != http.MethodPost || r.URL.Query().Get("bot_type") != "3" {
+ t.Error("wrong QR request")
+ }
+ var body map[string]json.RawMessage
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatal(err)
+ }
+ if string(body["local_token_list"]) != "[]" {
+ t.Error("unexpected local credentials")
+ }
+ _, _ = w.Write([]byte(`{"qrcode":"opaque +/& QR","qrcode_img_content":"https://weixin.qq.com/qr/example"}`))
+ case "/ilink/bot/get_qrcode_status":
+ if r.Method != http.MethodGet || r.URL.Query().Get("qrcode") != "opaque +/& QR" || r.URL.Query().Get("verify_code") != "001234" {
+ t.Error("lost QR/verification code encoding")
+ }
+ _, _ = w.Write([]byte(`{"status":"confirmed","bot_token":"test-bot-token","ilink_bot_id":"[email protected]","ilink_user_id":"[email protected]","baseurl":"https://ilinkai.weixin.qq.com"}`))
+ default:
+ t.Errorf("unexpected endpoint %s", r.URL.Path)
+ }
+ }))
+ defer server.Close()
+ api := newAPI(server.URL, "must-not-be-sent", server.Client())
+ qr, err := api.QRCode(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ status, err := api.QRStatus(context.Background(), qr.QRCode, "001234")
+ if err != nil || status.UserID != "[email protected]" {
+ t.Fatalf("status = %#v, error = %v", status, err)
+ }
+}
+
+func TestQRVerificationStates(t *testing.T) {
+ for _, status := range []string{"need_verifycode", "confirmed_but_need_verifycode", "future_need_verifycode"} {
+ t.Run(status, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]string{"status": status})
+ }))
+ defer server.Close()
+ result, err := newAPI(server.URL, "", server.Client()).QRStatus(context.Background(), "qr", "")
+ if err != nil || result.Status != status {
+ t.Fatalf("verification status rejected: %q, %v", result.Status, err)
+ }
+ })
+ }
+}
+
+func TestUpdatesPreserveMessageIDAndReplyContext(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Authorization") != "Bearer test-token" || r.Header.Get("AuthorizationType") != "ilink_bot_token" {
+ t.Error("missing authentication")
+ }
+ var body map[string]json.RawMessage
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatal(err)
+ }
+ if len(body["base_info"]) == 0 {
+ t.Error("missing base_info")
+ }
+ if strings.HasSuffix(r.URL.Path, "getupdates") {
+ if string(body["get_updates_buf"]) != `"cursor-1"` {
+ t.Error("cursor not resumed")
+ }
+ _, _ = w.Write([]byte(`{"ret":0,"get_updates_buf":"cursor-2","msgs":[{"message_id":18446744073709551615,"from_user_id":"owner","message_type":1,"context_token":"context","item_list":[{"type":1,"text_item":{"text":"hello"}}]}]}`))
+ } else {
+ var msg message
+ if err := json.Unmarshal(body["msg"], &msg); err != nil {
+ t.Fatal(err)
+ }
+ if msg.ContextToken != "context" || msg.To != "owner" || msg.Type != 2 || msg.State == nil || *msg.State != 2 || msg.ClientID != "stable-send" {
+ t.Error("incorrect reply addressing")
+ }
+ _, _ = w.Write([]byte(`{"ret":0,"message_id":"18446744073709551614"}`))
+ }
+ }))
+ defer server.Close()
+ api := newAPI(server.URL, "test-token", server.Client())
+ result, err := api.Updates(context.Background(), "cursor-1")
+ if err != nil || len(result.Messages) != 1 || result.Messages[0].ID != "18446744073709551615" {
+ t.Fatalf("updates = %#v, %v", result, err)
+ }
+ msg := result.Messages[0]
+ got, err := api.Send(context.Background(), textMessage(msg.From, msg.ContextToken, "stable-send", "reply"))
+ if err != nil || got != "18446744073709551614" {
+ t.Fatalf("send = %q, %v", got, err)
+ }
+}
+
+func TestProviderFailuresAndMissingContext(t *testing.T) {
+ for _, tc := range []struct {
+ name, body string
+ want error
+ }{
+ {"expired", `{"ret":-14}`, ErrTokenExpired},
+ {"expired errcode", `{"errcode":-14}`, ErrTokenExpired},
+ {"missing status", `{}`, ErrProtocol},
+ {"invalid json", `{"bot_token":"secret"`, ErrProtocol},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(tc.body)) }))
+ defer server.Close()
+ _, err := newAPI(server.URL, "token", server.Client()).Updates(context.Background(), "")
+ if !errors.Is(err, tc.want) {
+ t.Fatalf("error = %v", err)
+ }
+ })
+ }
+ _, err := newAPI("", "", nil).Send(context.Background(), textMessage("owner", "", "id", "text"))
+ if !errors.Is(err, ErrNoContext) {
+ t.Fatalf("error = %v", err)
+ }
+}
+
+func TestUpdatesAcceptSuccessWithoutRet(t *testing.T) {
+ for _, body := range []string{
+ `{"msgs":[],"sync_buf":"sync","get_updates_buf":"next"}`,
+ `{"msgs":[{"message_id":123,"from_user_id":"owner","message_type":1,"item_list":[{"type":1,"text_item":{"text":"hello"}}]}],"get_updates_buf":"next"}`,
+ } {
+ t.Run(body, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(body))
+ }))
+ defer server.Close()
+ result, err := newAPI(server.URL, "token", server.Client()).Updates(context.Background(), "")
+ if err != nil || result.Cursor != "next" {
+ t.Fatalf("successful update rejected: cursor=%q error=%v", result.Cursor, err)
+ }
+ })
+ }
+}
+
+func TestSendAcceptSuccessWithoutRet(t *testing.T) {
+ for _, tc := range []struct{ body, want string }{
+ {`{"message_id":"provider-id"}`, "provider-id"},
+ {`{}`, "client-id"},
+ } {
+ t.Run(tc.body, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(tc.body))
+ }))
+ defer server.Close()
+ got, err := newAPI(server.URL, "token", server.Client()).Send(context.Background(), textMessage("owner", "context", "client-id", "reply"))
+ if err != nil || got != tc.want {
+ t.Fatalf("successful send rejected: id=%q error=%v", got, err)
+ }
+ })
+ }
+}
+
+func TestSendRejectsProviderErrors(t *testing.T) {
+ for _, body := range []string{`{"ret":-14}`, `{"errcode":-14}`, `{"ret":123}`, `{"errcode":456}`} {
+ t.Run(body, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(body))
+ }))
+ defer server.Close()
+ got, err := newAPI(server.URL, "token", server.Client()).Send(context.Background(), textMessage("owner", "context", "client-id", "reply"))
+ if err == nil || got != "" {
+ t.Fatalf("provider failure accepted: id=%q error=%v", got, err)
+ }
+ })
+ }
+}
+
+func TestNotifyOptionalReturnCode(t *testing.T) {
+ for _, start := range []bool{true, false} {
+ for _, body := range []string{`{}`, `{"ret":0}`, `{"errcode":0}`, `{"ret":123}`, `{"errcode":456}`} {
+ t.Run(body, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(body)) }))
+ defer server.Close()
+ err := newAPI(server.URL, "token", server.Client()).notify(context.Background(), start)
+ wantError := strings.Contains(body, "123") || strings.Contains(body, "456")
+ if (err != nil) != wantError {
+ t.Fatalf("notify error=%v, wantError=%v", err, wantError)
+ }
+ })
+ }
+ }
+}
+
+func TestProviderURLsAndRedirects(t *testing.T) {
+ for _, raw := range []string{"http://ilinkai.weixin.qq.com", "https://weixin.qq.com.evil.test", "https://evil.test/", "https://user:[email protected]", "https://ilinkai.weixin.qq.com:8443", "https://ilinkai.weixin.qq.com/path"} {
+ if _, err := validateBaseURL(raw); err == nil {
+ t.Errorf("accepted %s", raw)
+ }
+ }
+ if _, err := validateBaseURL("https://ilinkai.weixin.qq.com/"); err != nil {
+ t.Fatal(err)
+ }
+ visited := false
+ destination := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { visited = true }))
+ defer destination.Close()
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, destination.URL, http.StatusTemporaryRedirect)
+ }))
+ defer server.Close()
+ _, err := newAPI(server.URL, "secret", server.Client()).Updates(context.Background(), "")
+ if err == nil || visited {
+ t.Fatal("followed redirect with a credential")
+ }
+}
diff --git a/server/internal/integrations/weixin/channel.go b/server/internal/integrations/weixin/channel.go
new file mode 100644
index 0000000000..45827034f4
--- /dev/null
+++ b/server/internal/integrations/weixin/channel.go
@@ -0,0 +1,237 @@
+package weixin
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/util"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+type accountStore interface {
+ GetWeixinAccountState(context.Context, db.GetWeixinAccountStateParams) (db.WeixinAccountState, error)
+ SaveWeixinContext(context.Context, db.SaveWeixinContextParams) (int64, error)
+ SaveWeixinCursor(context.Context, db.SaveWeixinCursorParams) (int64, error)
+ ExpireWeixinInstallation(context.Context, db.ExpireWeixinInstallationParams) (int64, error)
+}
+
+type ChannelDeps struct {
+ Queries *db.Queries
+ Box *secretbox.Box
+ Logger *slog.Logger
+ Client *http.Client
+ Typing *TypingNotifier
+ Bus *events.Bus
+}
+
+type weixinChannel struct {
+ id pgtype.UUID
+ creds credentials
+ api *apiClient
+ q accountStore
+ box *secretbox.Box
+ handler channel.InboundHandler
+ logger *slog.Logger
+ config []byte
+ typing *TypingNotifier
+ onExpired func(context.Context)
+}
+
+func RegisterWeixin(reg *channel.Registry, deps ChannelDeps) {
+ reg.Register(TypeWeixin, func(cfg channel.Config) (channel.Channel, error) {
+ creds, err := decodeCredentials(cfg.Raw, deps.Box)
+ if err != nil {
+ return nil, err
+ }
+ if deps.Queries == nil {
+ return nil, errors.New("weixin: account store is required")
+ }
+ logger := deps.Logger
+ if logger == nil {
+ logger = slog.Default()
+ }
+ c := &weixinChannel{id: cfg.ID, config: cfg.Raw, creds: creds, api: newAPI(creds.BaseURL, creds.Token, deps.Client), q: deps.Queries, box: deps.Box, handler: cfg.Handler, logger: logger, typing: deps.Typing}
+ if deps.Bus != nil {
+ c.onExpired = func(ctx context.Context) {
+ inst, err := deps.Queries.GetChannelInstallation(ctx, db.GetChannelInstallationParams{ID: cfg.ID, ChannelType: string(TypeWeixin)})
+ if err == nil {
+ deps.Bus.Publish(events.Event{Type: protocol.EventWeixinInstallationRevoked, WorkspaceID: util.UUIDToString(inst.WorkspaceID), ActorType: "system", Payload: map[string]any{"id": util.UUIDToString(inst.ID)}})
+ }
+ }
+ }
+ return c, nil
+ })
+}
+
+func (c *weixinChannel) Type() channel.Type { return TypeWeixin }
+func (c *weixinChannel) Capabilities() channel.Capability {
+ return channel.CapText | channel.CapAttachment | channel.CapTypingIndicator
+}
+func (c *weixinChannel) Disconnect(context.Context) error { return nil }
+
+func (c *weixinChannel) Connect(ctx context.Context) error {
+ if c.handler == nil {
+ return errors.New("weixin: inbound handler is required")
+ }
+ state, err := c.q.GetWeixinAccountState(ctx, db.GetWeixinAccountStateParams{InstallationID: c.id, BotID: c.creds.AppID})
+ if err != nil {
+ return err
+ }
+ if err := c.api.notify(ctx, true); err != nil && ctx.Err() == nil {
+ c.logger.WarnContext(ctx, "weixin: start notification failed", "error", err)
+ }
+ tokenExpired := false
+ defer func() {
+ if ctx.Err() == nil && !tokenExpired {
+ return
+ }
+ if c.typing != nil {
+ clear, cancel := context.WithTimeout(context.WithoutCancel(ctx), typingCallTimeout)
+ c.typing.StopInstallation(clear, c.id)
+ cancel()
+ }
+ stop, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second)
+ defer cancel()
+ if err := c.api.notify(stop, false); err != nil {
+ c.logger.WarnContext(stop, "weixin: stop notification failed", "error", err)
+ }
+ }()
+ cursor := state.GetUpdatesBuf
+ for ctx.Err() == nil {
+ result, err := c.api.Updates(ctx, cursor)
+ if ctx.Err() != nil {
+ return nil
+ }
+ if errors.Is(err, context.DeadlineExceeded) {
+ continue
+ }
+ if err != nil {
+ if errors.Is(err, ErrTokenExpired) {
+ tokenExpired = true
+ // Fence against a newer QR login rotating this installation while
+ // its predecessor's long poll was still in flight.
+ if rows, err := c.q.ExpireWeixinInstallation(ctx, db.ExpireWeixinInstallationParams{ID: c.id, Config: c.config}); err == nil && rows == 1 && c.onExpired != nil {
+ c.onExpired(ctx)
+ }
+ }
+ return err
+ }
+ for _, msg := range result.Messages {
+ in, ok := normalizeMessage(c.creds, msg)
+ if !ok {
+ continue
+ }
+ if msg.ContextToken != "" {
+ sealed, err := c.box.Seal([]byte(msg.ContextToken))
+ if err != nil {
+ return err
+ }
+ if _, err := c.q.SaveWeixinContext(ctx, db.SaveWeixinContextParams{InstallationID: c.id, BotID: c.creds.AppID, UserID: c.creds.UserID, ContextTokenEncrypted: sealed, ContextTimeMs: msg.CreatedAt}); err != nil {
+ return err
+ }
+ }
+ // The shared engine commits dedup and inbound persistence before
+ // returning; advance the provider cursor only after the entire batch.
+ if err := c.handler(ctx, in); err != nil {
+ return err
+ }
+ }
+ if result.Cursor != "" && result.Cursor != cursor {
+ rows, err := c.q.SaveWeixinCursor(ctx, db.SaveWeixinCursorParams{InstallationID: c.id, BotID: c.creds.AppID, GetUpdatesBuf: result.Cursor})
+ if err != nil {
+ return err
+ }
+ if rows != 1 {
+ return ErrNotFound
+ }
+ cursor = result.Cursor
+ }
+ // Some transports return immediately without events; avoid a hot loop.
+ if len(result.Messages) == 0 {
+ select {
+ case <-ctx.Done():
+ return nil
+ case <-time.After(time.Second):
+ }
+ }
+ }
+ return nil
+}
+
+func (c *weixinChannel) Send(ctx context.Context, out channel.OutboundMessage) (channel.SendResult, error) {
+ if out.ChatID != c.creds.UserID {
+ return channel.SendResult{}, ErrAccess
+ }
+ state, err := c.q.GetWeixinAccountState(ctx, db.GetWeixinAccountStateParams{InstallationID: c.id, BotID: c.creds.AppID})
+ if err != nil {
+ return channel.SendResult{}, err
+ }
+ token, err := c.box.Open(state.ContextTokenEncrypted)
+ if err != nil {
+ return channel.SendResult{}, ErrNoContext
+ }
+ id, err := c.api.Send(ctx, textMessage(out.ChatID, string(token), util.UUIDToString(dbid.NewV7()), out.Text))
+ return channel.SendResult{MessageID: id}, err
+}
+
+type weixinRawEvent struct {
+ BotID string `json:"bot_id"`
+ EventType string `json:"event_type"`
+ Message message `json:"message"`
+}
+
+func normalizeMessage(creds credentials, msg message) (channel.InboundMessage, bool) {
+ // A partial update can share its message ID with the final update. Claiming
+ // it would make the deduper discard the completed message later.
+ if msg.State != nil && *msg.State != 2 {
+ return channel.InboundMessage{}, false
+ }
+ if msg.Type != 1 || msg.ID == "" || msg.GroupID != "" || msg.From != creds.UserID || msg.From == "" || msg.To != "" && msg.To != creds.AppID {
+ return channel.InboundMessage{}, false
+ }
+ var text []string
+ kind := channel.MsgTypeText
+ for _, item := range msg.Items {
+ switch {
+ case item.Type == 1 && item.Text != nil:
+ text = append(text, item.Text.Text)
+ case item.Type == 2 && item.Image != nil:
+ text = append(text, "[Image]")
+ kind = channel.MsgTypeImage
+ case item.Type == 3 && item.Voice != nil:
+ if item.Voice.Text != "" {
+ text = append(text, item.Voice.Text)
+ } else {
+ text = append(text, "[Audio]")
+ kind = channel.MsgTypeAudio
+ }
+ case item.Type == 4 && item.File != nil:
+ text = append(text, "[File]")
+ kind = channel.MsgTypeFile
+ case item.Type == 5 && item.Video != nil:
+ text = append(text, "[Video]")
+ kind = channel.MsgTypeVideo
+ }
+ }
+ if len(text) == 0 {
+ return channel.InboundMessage{}, false
+ }
+ msg.ContextToken = ""
+ raw, _ := json.Marshal(weixinRawEvent{BotID: creds.AppID, EventType: "message", Message: msg})
+ return channel.InboundMessage{
+ Source: channel.Source{ChannelType: TypeWeixin, ChatID: msg.From, ChatType: channel.ChatTypeP2P, SenderID: msg.From},
+ MessageID: string(msg.ID), EventID: string(msg.ID), Type: kind,
+ Text: strings.Join(text, "\n"), Raw: raw,
+ }, true
+}
diff --git a/server/internal/integrations/weixin/channel_test.go b/server/internal/integrations/weixin/channel_test.go
new file mode 100644
index 0000000000..2646820efd
--- /dev/null
+++ b/server/internal/integrations/weixin/channel_test.go
@@ -0,0 +1,181 @@
+package weixin
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type memoryAccount struct {
+ state db.WeixinAccountState
+ cursorSaved bool
+ expired bool
+ cancel context.CancelFunc
+}
+
+func (m *memoryAccount) GetWeixinAccountState(context.Context, db.GetWeixinAccountStateParams) (db.WeixinAccountState, error) {
+ return m.state, nil
+}
+func (m *memoryAccount) SaveWeixinContext(_ context.Context, p db.SaveWeixinContextParams) (int64, error) {
+ m.state.ContextTokenEncrypted = p.ContextTokenEncrypted
+ return 1, nil
+}
+func (m *memoryAccount) SaveWeixinCursor(_ context.Context, p db.SaveWeixinCursorParams) (int64, error) {
+ m.cursorSaved = true
+ m.state.GetUpdatesBuf = p.GetUpdatesBuf
+ m.cancel()
+ return 1, nil
+}
+func (m *memoryAccount) ExpireWeixinInstallation(context.Context, db.ExpireWeixinInstallationParams) (int64, error) {
+ m.expired = true
+ return 1, nil
+}
+
+func TestInboundCursorCommitsAfterAcceptedBatch(t *testing.T) {
+ for _, fail := range []bool{false, true} {
+ t.Run(map[bool]string{false: "accepted", true: "persistence-failed"}[fail], func(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ store := &memoryAccount{cancel: cancel, state: db.WeixinAccountState{GetUpdatesBuf: "previous"}}
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.Path, "getupdates") {
+ var body map[string]any
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ if body["get_updates_buf"] != "previous" {
+ t.Error("lost saved cursor")
+ }
+ _, _ = w.Write([]byte(`{"ret":0,"get_updates_buf":"next","msgs":[{"message_id":123,"from_user_id":"owner","message_type":1,"context_token":"reply-token","item_list":[{"type":1,"text_item":{"text":"hello"}}]}]}`))
+ } else {
+ _, _ = w.Write([]byte(`{"ret":0}`))
+ }
+ }))
+ defer server.Close()
+ box := testBox(t)
+ calls := 0
+ c := &weixinChannel{creds: credentials{installConfig: installConfig{AppID: "bot", UserID: "owner"}}, api: newAPI(server.URL, "token", server.Client()), q: store, box: box, logger: slog.Default(), handler: func(_ context.Context, msg channel.InboundMessage) error {
+ calls++
+ if store.cursorSaved {
+ t.Error("cursor moved before engine acceptance")
+ }
+ if strings.Contains(string(msg.Raw), "reply-token") {
+ t.Error("reply credential leaked into raw message")
+ }
+ token, err := box.Open(store.state.ContextTokenEncrypted)
+ if err != nil || string(token) != "reply-token" {
+ t.Error("context not durable before dispatch")
+ }
+ if fail {
+ return errors.New("database unavailable")
+ }
+ return nil
+ }}
+ err := c.Connect(ctx)
+ if fail && err == nil || !fail && err != nil {
+ t.Fatalf("connect: %v", err)
+ }
+ if calls != 1 || store.cursorSaved == fail {
+ t.Fatalf("calls=%d cursorSaved=%v", calls, store.cursorSaved)
+ }
+ })
+ }
+}
+
+func TestInboundRejectsOtherUsersGroupsAndBotEchoes(t *testing.T) {
+ creds := credentials{installConfig: installConfig{AppID: "bot", UserID: "owner"}}
+ msg := textMessage("bot", "context", "", "hello")
+ msg.ID, msg.From, msg.Type = "id", "owner", 1
+ if in, ok := normalizeMessage(creds, msg); !ok || in.Text != "hello" {
+ t.Fatal("owner message rejected")
+ }
+ for _, state := range []int{0, 1, 99} {
+ partial := msg
+ partial.State = &state
+ if _, ok := normalizeMessage(creds, partial); ok {
+ t.Fatal("accepted an incomplete message before its final update")
+ }
+ }
+ for _, mutate := range []func(*message){func(m *message) { m.From = "stranger" }, func(m *message) { m.Type = 2 }, func(m *message) { m.GroupID = "group" }, func(m *message) { m.To = "other-bot" }, func(m *message) { m.ID = "" }} {
+ copy := msg
+ mutate(&copy)
+ if _, ok := normalizeMessage(creds, copy); ok {
+ t.Fatal("accepted foreign or unsupported source")
+ }
+ }
+}
+
+func TestStopNotificationOnlyForShutdownOrExpiredToken(t *testing.T) {
+ for _, kind := range []string{"transient", "cancelled", "expired"} {
+ t.Run(kind, func(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ var stops atomic.Int32
+ store := &memoryAccount{}
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case strings.HasSuffix(r.URL.Path, "notifystop"):
+ if r.Context().Err() != nil {
+ t.Error("stop inherited cancelled context")
+ }
+ stops.Add(1)
+ case strings.HasSuffix(r.URL.Path, "getupdates"):
+ switch kind {
+ case "transient":
+ w.WriteHeader(http.StatusBadGateway)
+ return
+ case "cancelled":
+ cancel()
+ case "expired":
+ _, _ = w.Write([]byte(`{"errcode":-14}`))
+ return
+ }
+ }
+ _, _ = w.Write([]byte(`{}`))
+ }))
+ defer server.Close()
+ c := &weixinChannel{api: newAPI(server.URL, "token", server.Client()), q: store, logger: slog.Default(), handler: func(context.Context, channel.InboundMessage) error { return nil }}
+ err := c.Connect(ctx)
+ if kind == "transient" && err == nil {
+ t.Fatal("transient error was swallowed")
+ }
+ wantStops := int32(1)
+ if kind == "transient" {
+ wantStops = 0
+ }
+ if stops.Load() != wantStops || store.expired != (kind == "expired") {
+ t.Fatalf("stops=%d expired=%v", stops.Load(), store.expired)
+ }
+ })
+ }
+}
+
+func TestUnchangedCursorDoesNotWriteOrSkipMessages(t *testing.T) {
+ var polls atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.Path, "getupdates") {
+ if polls.Add(1) > 1 {
+ w.WriteHeader(http.StatusBadGateway)
+ return
+ }
+ _, _ = w.Write([]byte(`{"get_updates_buf":"same","msgs":[{"message_id":1,"from_user_id":"owner","message_type":1,"item_list":[{"type":1,"text_item":{"text":"hello"}}]}]}`))
+ return
+ }
+ _, _ = w.Write([]byte(`{}`))
+ }))
+ defer server.Close()
+ store := &memoryAccount{state: db.WeixinAccountState{GetUpdatesBuf: "same"}}
+ calls := 0
+ c := &weixinChannel{creds: credentials{installConfig: installConfig{AppID: "bot", UserID: "owner"}}, api: newAPI(server.URL, "token", server.Client()), q: store, box: testBox(t), logger: slog.Default(), handler: func(context.Context, channel.InboundMessage) error { calls++; return nil }}
+ _ = c.Connect(context.Background())
+ if store.cursorSaved || calls != 1 {
+ t.Fatalf("cursorSaved=%v messages=%d", store.cursorSaved, calls)
+ }
+}
diff --git a/server/internal/integrations/weixin/config.go b/server/internal/integrations/weixin/config.go
new file mode 100644
index 0000000000..f9201d706e
--- /dev/null
+++ b/server/internal/integrations/weixin/config.go
@@ -0,0 +1,59 @@
+package weixin
+
+import (
+ "encoding/base64"
+ "encoding/json"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+)
+
+const TypeWeixin channel.Type = "weixin"
+
+type installConfig struct {
+ AppID string `json:"app_id"`
+ UserID string `json:"user_id"`
+ BaseURL string `json:"base_url"`
+ TokenEncrypted string `json:"bot_token_encrypted"`
+ AuthorizationExpired bool `json:"authorization_expired,omitempty"`
+}
+
+type credentials struct {
+ installConfig
+ Token string
+}
+
+type PublicConfig struct {
+ BotID, UserID string
+ AuthorizationExpired bool
+}
+
+func DecodePublicConfig(raw json.RawMessage) PublicConfig {
+ var cfg installConfig
+ _ = json.Unmarshal(raw, &cfg)
+ return PublicConfig{BotID: cfg.AppID, UserID: cfg.UserID, AuthorizationExpired: cfg.AuthorizationExpired}
+}
+
+func decodeCredentials(raw json.RawMessage, box *secretbox.Box) (credentials, error) {
+ var cfg installConfig
+ if box == nil || json.Unmarshal(raw, &cfg) != nil || cfg.AppID == "" || cfg.UserID == "" {
+ return credentials{}, ErrProtocol
+ }
+ base, err := validateBaseURL(cfg.BaseURL)
+ if err != nil {
+ return credentials{}, err
+ }
+ sealed, err := base64.StdEncoding.DecodeString(cfg.TokenEncrypted)
+ if err != nil {
+ return credentials{}, ErrProtocol
+ }
+ plain, err := box.Open(sealed)
+ if err != nil {
+ return credentials{}, err
+ }
+ if len(plain) == 0 {
+ return credentials{}, ErrTokenExpired
+ }
+ cfg.BaseURL = base
+ return credentials{installConfig: cfg, Token: string(plain)}, nil
+}
diff --git a/server/internal/integrations/weixin/database_test.go b/server/internal/integrations/weixin/database_test.go
new file mode 100644
index 0000000000..53f0e3d3b6
--- /dev/null
+++ b/server/internal/integrations/weixin/database_test.go
@@ -0,0 +1,521 @@
+package weixin
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/events"
+ dbfx "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/internal/util"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+var testPool *pgxpool.Pool
+
+func TestMain(m *testing.M) {
+ if dsn := os.Getenv("DATABASE_URL"); dsn != "" {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ pool, err := pgxpool.New(ctx, dsn)
+ if err == nil {
+ if pool.Ping(ctx) == nil {
+ testPool = pool
+ } else {
+ pool.Close()
+ }
+ }
+ cancel()
+ }
+ code := m.Run()
+ if testPool != nil {
+ testPool.Close()
+ }
+ os.Exit(code)
+}
+
+func testBox(t *testing.T) *secretbox.Box {
+ t.Helper()
+ box, err := secretbox.New(bytes.Repeat([]byte{7}, 32))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return box
+}
+
+func testUUID(t *testing.T, value string) pgtype.UUID {
+ t.Helper()
+ id, err := util.ParseUUID(value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return id
+}
+
+type databaseFixture struct {
+ f *dbfx.Fixture
+ q *db.Queries
+ svc *InstallService
+ agent pgtype.UUID
+ workspace pgtype.UUID
+ user pgtype.UUID
+ status atomic.Value
+ tokens atomic.Value
+ provider *httptest.Server
+ block func()
+}
+
+func newDatabaseFixture(t *testing.T) *databaseFixture {
+ t.Helper()
+ if testPool == nil {
+ t.Skip("DATABASE_URL pointing to a migrated test database is required")
+ }
+ f := dbfx.New(testPool, "", "")
+ suffix := util.UUIDToString(dbid.NewV7())
+ f.UserID = f.User(t, "WeChat test", suffix+"@example.test")
+ f.WorkspaceID = f.Workspace(t, "WeChat test", "wx-"+suffix)
+ f.Member(t, f.WorkspaceID, f.UserID, "admin")
+ agent := f.Agent(t, "WeChat test agent", "")
+ x := &databaseFixture{f: f, q: db.New(testPool), agent: testUUID(t, agent), workspace: testUUID(t, f.WorkspaceID), user: testUUID(t, f.UserID)}
+ x.status.Store(qrStatus{Status: "confirmed", BotID: "bot-" + suffix, UserID: "scanner-" + suffix, Token: "test-token", BaseURL: DefaultBaseURL})
+ x.provider = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/ilink/bot/get_bot_qrcode":
+ var body struct {
+ Tokens []string `json:"local_token_list"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Error(err)
+ }
+ x.tokens.Store(body.Tokens)
+ _ = json.NewEncoder(w).Encode(map[string]string{"qrcode": "private-qr", "qrcode_img_content": "https://weixin.qq.com/test-qr"})
+ case "/ilink/bot/get_qrcode_status":
+ if x.block != nil {
+ x.block()
+ }
+ _ = json.NewEncoder(w).Encode(x.status.Load().(qrStatus))
+ default:
+ t.Errorf("unexpected provider path %s", r.URL.Path)
+ }
+ }))
+ t.Cleanup(x.provider.Close)
+ svc, err := NewInstallService(x.q, testPool, testBox(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ svc.apiBase = x.provider.URL
+ x.svc = svc
+ f.Cleanup(t, `DELETE FROM channel_installation WHERE workspace_id = $1`, f.WorkspaceID)
+ f.Cleanup(t, `DELETE FROM channel_user_binding WHERE workspace_id = $1`, f.WorkspaceID)
+ f.Cleanup(t, `DELETE FROM weixin_login_session WHERE workspace_id = $1`, f.WorkspaceID)
+ f.Cleanup(t, `DELETE FROM weixin_account_state WHERE installation_id IN (SELECT id FROM channel_installation WHERE workspace_id = $1)`, f.WorkspaceID)
+ return x
+}
+
+func (x *databaseFixture) begin(t *testing.T) pgtype.UUID {
+ t.Helper()
+ login, err := x.svc.Begin(context.Background(), x.workspace, x.agent, x.user)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return testUUID(t, login.ID)
+}
+
+func (x *databaseFixture) connect(t *testing.T) db.ChannelInstallation {
+ t.Helper()
+ login, err := x.svc.Poll(context.Background(), x.begin(t), x.workspace, x.user, "")
+ if err != nil || login.Status != "confirmed" {
+ t.Fatalf("login: %v, %v", login.Status, err)
+ }
+ inst, err := x.q.GetChannelInstallation(context.Background(), db.GetChannelInstallationParams{ID: testUUID(t, login.InstallationID), ChannelType: string(TypeWeixin)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return inst
+}
+
+func TestLoginPersistsEncryptedCredentialsAndIdentity(t *testing.T) {
+ x := newDatabaseFixture(t)
+ id := x.begin(t)
+ row, err := x.q.GetWeixinLoginSession(context.Background(), db.GetWeixinLoginSessionParams{ID: id, WorkspaceID: x.workspace, InitiatorUserID: x.user})
+ if err != nil || bytes.Contains(row.StateEncrypted, []byte("private-qr")) {
+ t.Fatalf("QR state not encrypted: %v", err)
+ }
+ if _, err := x.svc.Get(context.Background(), id, x.workspace, dbid.NewV7()); !errors.Is(err, ErrNotFound) {
+ t.Fatalf("another user could read QR: %v", err)
+ }
+ login, err := x.svc.Poll(context.Background(), id, x.workspace, x.user, "")
+ if err != nil || login.Status != "confirmed" || login.QRCodeURL != "" {
+ t.Fatalf("confirmation: %v, %v", login.Status, err)
+ }
+ instID := testUUID(t, login.InstallationID)
+ inst, err := x.q.GetChannelInstallation(context.Background(), db.GetChannelInstallationParams{ID: instID, ChannelType: string(TypeWeixin)})
+ if err != nil || bytes.Contains(inst.Config, []byte("test-token")) {
+ t.Fatalf("token not encrypted: %v", err)
+ }
+ creds, err := decodeCredentials(inst.Config, x.svc.box)
+ if err != nil || creds.Token != "test-token" {
+ t.Fatalf("credentials cannot be read: %v", err)
+ }
+ binding, err := x.q.GetChannelUserBindingByUserID(context.Background(), db.GetChannelUserBindingByUserIDParams{InstallationID: inst.ID, ChannelUserID: creds.UserID})
+ if err != nil || binding.MulticaUserID != x.user {
+ t.Fatalf("scanner not bound to initiator: %v", err)
+ }
+ row, err = x.q.GetWeixinLoginSession(context.Background(), db.GetWeixinLoginSessionParams{ID: id, WorkspaceID: x.workspace, InitiatorUserID: x.user})
+ if err != nil || len(row.StateEncrypted) != 0 {
+ t.Fatalf("confirmed QR retained: %v", err)
+ }
+}
+
+func TestLoginCancelFencesLateConfirmation(t *testing.T) {
+ x := newDatabaseFixture(t)
+ id := x.begin(t)
+ entered, release := make(chan struct{}), make(chan struct{})
+ defer func() {
+ select {
+ case <-release:
+ default:
+ close(release)
+ }
+ }()
+ x.block = func() { close(entered); <-release }
+ result := make(chan error, 1)
+ go func() { _, err := x.svc.Poll(context.Background(), id, x.workspace, x.user, ""); result <- err }()
+ select {
+ case <-entered:
+ case <-time.After(3 * time.Second):
+ t.Fatal("poll never reached provider")
+ }
+ if _, err := x.svc.Poll(context.Background(), id, x.workspace, x.user, ""); !errors.Is(err, ErrBusy) {
+ t.Fatalf("concurrent poll not fenced: %v", err)
+ }
+ if err := x.svc.Cancel(context.Background(), id, x.workspace, x.user); err != nil {
+ t.Fatal(err)
+ }
+ close(release)
+ if err := <-result; !errors.Is(err, ErrNotFound) {
+ t.Fatalf("late confirmation: %v", err)
+ }
+ if count := x.f.Count(t, "SELECT count(*) FROM channel_installation WHERE workspace_id=$1", x.f.WorkspaceID); count != 0 {
+ t.Fatal("cancelled login installed bot")
+ }
+}
+
+func TestLoginExpiryReplacementAndRevokedMembership(t *testing.T) {
+ x := newDatabaseFixture(t)
+ old, next := x.begin(t), x.begin(t)
+ view, err := x.svc.Get(context.Background(), old, x.workspace, x.user)
+ if err != nil || view.Status != "cancelled" {
+ t.Fatalf("old QR remains live: %v", err)
+ }
+ x.f.Exec(t, `UPDATE weixin_login_session SET expires_at=now()-interval '1 second' WHERE id=$1`, next)
+ view, err = x.svc.Poll(context.Background(), next, x.workspace, x.user, "")
+ if err != nil || view.Status != "expired" || view.QRCodeURL != "" {
+ t.Fatalf("expired QR: %v", err)
+ }
+ next = x.begin(t)
+ x.f.Exec(t, `UPDATE member SET role='member' WHERE workspace_id=$1 AND user_id=$2`, x.workspace, x.user)
+ if _, err := x.svc.Poll(context.Background(), next, x.workspace, x.user, ""); !errors.Is(err, ErrAccess) {
+ t.Fatalf("demoted admin installed: %v", err)
+ }
+}
+
+func TestLoginBotOwnershipAndRevoke(t *testing.T) {
+ x := newDatabaseFixture(t)
+ inst := x.connect(t)
+ y := newDatabaseFixture(t)
+ y.status.Store(x.status.Load().(qrStatus))
+ if _, err := y.svc.Poll(context.Background(), y.begin(t), y.workspace, y.user, ""); !errors.Is(err, ErrConflict) {
+ t.Fatalf("bot taken by another workspace: %v", err)
+ }
+ if err := x.svc.Revoke(context.Background(), inst.ID, y.workspace); !errors.Is(err, ErrNotFound) {
+ t.Fatalf("cross-workspace revoke: %v", err)
+ }
+ if err := x.svc.Revoke(context.Background(), inst.ID, x.workspace); err != nil {
+ t.Fatal(err)
+ }
+ y.connect(t)
+ if count := x.f.Count(t, "SELECT count(*) FROM weixin_account_state WHERE installation_id=$1", inst.ID); count != 0 {
+ t.Fatal("revoked context retained")
+ }
+}
+
+func TestLoginTokensAreScopedAndBoundRedirectPreservesInstallation(t *testing.T) {
+ x := newDatabaseFixture(t)
+ inst := x.connect(t)
+ if _, err := x.q.SaveWeixinCursor(context.Background(), db.SaveWeixinCursorParams{InstallationID: inst.ID, BotID: DecodePublicConfig(inst.Config).BotID, GetUpdatesBuf: "saved-cursor"}); err != nil {
+ t.Fatal(err)
+ }
+ y := newDatabaseFixture(t)
+ y.connect(t)
+ id := x.begin(t)
+ tokens := x.tokens.Load().([]string)
+ if len(tokens) != 1 || tokens[0] != "test-token" {
+ t.Fatalf("wrong current-agent tokens: count=%d", len(tokens))
+ }
+ x.status.Store(qrStatus{Status: "binded_redirect"})
+ view, err := x.svc.Poll(context.Background(), id, x.workspace, x.user, "")
+ if err != nil || view.Status != "confirmed" || view.InstallationID != util.UUIDToString(inst.ID) {
+ t.Fatalf("repeat binding: %+v %v", view, err)
+ }
+ state, err := x.q.GetWeixinAccountState(context.Background(), db.GetWeixinAccountStateParams{InstallationID: inst.ID, BotID: DecodePublicConfig(inst.Config).BotID})
+ if err != nil || state.GetUpdatesBuf != "saved-cursor" {
+ t.Fatalf("repeat binding reset state: %v", err)
+ }
+ other := testUUID(t, x.f.Agent(t, "Another agent", ""))
+ if _, err := x.svc.Begin(context.Background(), x.workspace, other, x.user); err != nil {
+ t.Fatal(err)
+ }
+ if tokens := x.tokens.Load().([]string); len(tokens) != 0 {
+ t.Fatalf("another agent received %d tokens", len(tokens))
+ }
+}
+
+func TestBoundRedirectRejectsMissingRevokedOrChangedInstallation(t *testing.T) {
+ for _, kind := range []string{"missing", "revoked", "changed", "demoted"} {
+ t.Run(kind, func(t *testing.T) {
+ x := newDatabaseFixture(t)
+ var inst db.ChannelInstallation
+ if kind != "missing" {
+ inst = x.connect(t)
+ }
+ id := x.begin(t)
+ switch kind {
+ case "revoked":
+ if err := x.svc.Revoke(context.Background(), inst.ID, x.workspace); err != nil {
+ t.Fatal(err)
+ }
+ case "changed":
+ x.f.Exec(t, `UPDATE channel_installation SET config=config || '{"changed":true}'::jsonb WHERE id=$1`, inst.ID)
+ case "demoted":
+ x.f.Exec(t, `UPDATE member SET role='member' WHERE workspace_id=$1 AND user_id=$2`, x.workspace, x.user)
+ }
+ x.status.Store(qrStatus{Status: "binded_redirect"})
+ if _, err := x.svc.Poll(context.Background(), id, x.workspace, x.user, ""); err == nil {
+ t.Fatal("stale or absent binding treated as connected")
+ }
+ })
+ }
+}
+
+func TestLoginConflictNamesOnlyCurrentWorkspaceAgent(t *testing.T) {
+ x := newDatabaseFixture(t)
+ x.connect(t)
+ other := testUUID(t, x.f.Agent(t, "Another agent", ""))
+ view, err := x.svc.Begin(context.Background(), x.workspace, other, x.user)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = x.svc.Poll(context.Background(), testUUID(t, view.ID), x.workspace, x.user, "")
+ var conflict *ConflictError
+ if !errors.As(err, &conflict) || conflict.AgentID != util.UUIDToString(x.agent) || conflict.AgentName != "WeChat test agent" {
+ t.Fatalf("missing conflict owner: %v", err)
+ }
+ y := newDatabaseFixture(t)
+ y.status.Store(x.status.Load().(qrStatus))
+ _, err = y.svc.Poll(context.Background(), y.begin(t), y.workspace, y.user, "")
+ if !errors.Is(err, ErrConflict) || errors.As(err, &conflict) {
+ t.Fatal("cross-workspace conflict leaked agent identity")
+ }
+}
+
+func TestExpiredTokenIsMarkedWithoutRevokingRotatedCredentials(t *testing.T) {
+ x := newDatabaseFixture(t)
+ inst := x.connect(t)
+ rows, err := x.q.ExpireWeixinInstallation(context.Background(), db.ExpireWeixinInstallationParams{ID: inst.ID, Config: inst.Config})
+ if err != nil || rows != 1 {
+ t.Fatalf("expire: %d %v", rows, err)
+ }
+ expired, err := x.q.GetChannelInstallation(context.Background(), db.GetChannelInstallationParams{ID: inst.ID, ChannelType: string(TypeWeixin)})
+ if err != nil || expired.Status != "revoked" || !DecodePublicConfig(expired.Config).AuthorizationExpired {
+ t.Fatalf("expiration missing: %v", err)
+ }
+ x.connect(t)
+ rows, err = x.q.ExpireWeixinInstallation(context.Background(), db.ExpireWeixinInstallationParams{ID: inst.ID, Config: inst.Config})
+ if err != nil || rows != 0 {
+ t.Fatalf("stale credential expired new binding: %d %v", rows, err)
+ }
+}
+
+func TestTypingTracksDurableInputsAndRetryAcrossReplicas(t *testing.T) {
+ x := newDatabaseFixture(t)
+ ctx := context.Background()
+ inst := x.connect(t)
+ session := x.f.Insert(t, "chat_session", dbfx.Cols{"workspace_id": x.workspace, "agent_id": x.agent, "creator_id": x.user})
+ sessionID := testUUID(t, session)
+ _, err := x.q.CreateChannelChatSessionBinding(ctx, db.CreateChannelChatSessionBindingParams{ChatSessionID: sessionID, InstallationID: inst.ID, ChannelType: string(TypeWeixin), ChannelChatID: "owner", ChatType: "p2p", Config: []byte(`{}`)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ input := x.f.Insert(t, "chat_message", dbfx.Cols{"chat_session_id": session, "role": "user", "content": "hello", "channel_ingested": true})
+ params := db.IsWeixinTypingActiveParams{InstallationID: inst.ID, ChatSessionID: sessionID, Config: inst.Config}
+ assertActive := func(want bool) {
+ t.Helper()
+ got, err := x.q.IsWeixinTypingActive(ctx, params)
+ if err != nil || got != want {
+ t.Fatalf("typing active=%v want=%v error=%v", got, want, err)
+ }
+ }
+ assertActive(true)
+ if err := x.q.SettleWeixinTypingInputs(ctx, db.SettleWeixinTypingInputsParams{InstallationID: inst.ID, ChatSessionID: sessionID, WorkspaceID: x.workspace, ThroughMessageID: testUUID(t, input), ContextRevision: pgtype.Int8{Int64: 1, Valid: true}}); err != nil {
+ t.Fatal(err)
+ }
+ assertActive(false)
+ x.f.Exec(t, `UPDATE chat_message SET channel_typing_settled=false WHERE id=$1`, input)
+ runtime := x.f.Runtime(t, "typing test runtime")
+ task := x.f.Task(t, util.UUIDToString(x.agent), dbfx.Cols{"runtime_id": runtime, "chat_session_id": session, "status": "running"})
+ x.f.Exec(t, `UPDATE chat_message SET task_id=$2 WHERE id=$1`, input, task)
+ assertActive(true)
+ x.f.Exec(t, `UPDATE agent_task_queue SET status='completed' WHERE id=$1`, task)
+ assertActive(false)
+ retry := x.f.Task(t, util.UUIDToString(x.agent), dbfx.Cols{"runtime_id": runtime, "chat_session_id": session, "status": "deferred", "chat_input_task_id": task})
+ assertActive(true)
+ x.f.Exec(t, `UPDATE agent_task_queue SET status='cancelled' WHERE id=$1`, retry)
+ assertActive(false)
+ x.f.Exec(t, `UPDATE agent_task_queue SET status='running' WHERE id=$1`, retry)
+ if err := x.svc.Revoke(ctx, inst.ID, x.workspace); err != nil {
+ t.Fatal(err)
+ }
+ assertActive(false)
+}
+
+type roundTripper func(*http.Request) (*http.Response, error)
+
+func (f roundTripper) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+func providerClient(server *httptest.Server) *http.Client {
+ target, _ := url.Parse(server.URL)
+ return &http.Client{Transport: roundTripper(func(req *http.Request) (*http.Response, error) {
+ copy := req.Clone(req.Context())
+ copy.URL.Scheme, copy.URL.Host = target.Scheme, target.Host
+ return server.Client().Transport.RoundTrip(copy)
+ })}
+}
+
+func TestLoginVerificationStatesRetainSession(t *testing.T) {
+ for _, status := range []string{"need_verifycode", "confirmed_but_need_verifycode", "future_need_verifycode"} {
+ t.Run(status, func(t *testing.T) {
+ x := newDatabaseFixture(t)
+ confirmed := x.status.Load().(qrStatus)
+ x.status.Store(qrStatus{Status: status})
+ id := x.begin(t)
+ view, err := x.svc.Poll(context.Background(), id, x.workspace, x.user, "")
+ if err != nil || view.Status != status || view.QRCodeURL == "" || view.InstallationID != "" {
+ t.Fatalf("verification did not remain pending: %#v, %v", view, err)
+ }
+ x.status.Store(confirmed)
+ view, err = x.svc.Poll(context.Background(), id, x.workspace, x.user, "001234")
+ if err != nil || view.Status != "confirmed" || view.InstallationID == "" {
+ t.Fatalf("verification could not finish: %#v, %v", view, err)
+ }
+ })
+ }
+}
+
+func TestVerificationLoginCanBeCancelledOrReplaced(t *testing.T) {
+ for _, action := range []string{"cancel", "replace"} {
+ t.Run(action, func(t *testing.T) {
+ x := newDatabaseFixture(t)
+ x.status.Store(qrStatus{Status: "confirmed_but_need_verifycode"})
+ ctx := context.Background()
+ id := x.begin(t)
+ if _, err := x.svc.Poll(ctx, id, x.workspace, x.user, ""); err != nil {
+ t.Fatal(err)
+ }
+ if action == "cancel" {
+ if err := x.svc.Cancel(ctx, id, x.workspace, x.user); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ x.begin(t)
+ }
+ view, err := x.svc.Get(ctx, id, x.workspace, x.user)
+ if err != nil || view.Status != "cancelled" || view.QRCodeURL != "" {
+ t.Fatalf("verification login was not cancelled: %#v, %v", view, err)
+ }
+ })
+ }
+}
+
+func TestOutboundDedupUnknownAndRouting(t *testing.T) {
+ for _, scenario := range []string{"accepted", "response-lost", "web-origin", "revoked", "rebound", "retry-pending"} {
+ t.Run(scenario, func(t *testing.T) {
+ x := newDatabaseFixture(t)
+ inst := x.connect(t)
+ info := DecodePublicConfig(inst.Config)
+ ctx := context.Background()
+ sealed, _ := x.svc.box.Seal([]byte("reply-context"))
+ if _, err := x.q.SaveWeixinContext(ctx, db.SaveWeixinContextParams{InstallationID: inst.ID, BotID: info.BotID, UserID: info.UserID, ContextTokenEncrypted: sealed, ContextTimeMs: 123}); err != nil {
+ t.Fatal(err)
+ }
+ session := x.f.ChatSession(t, util.UUIDToString(x.agent))
+ taskID := x.f.Task(t, util.UUIDToString(x.agent), dbfx.Cols{"chat_session_id": session, "status": "completed", "runtime_id": x.f.Runtime(t, "test runtime")})
+ x.f.Exec(t, `UPDATE agent_task_queue SET chat_input_task_id=id WHERE id=$1`, taskID)
+ x.f.Insert(t, "chat_message", dbfx.Cols{"chat_session_id": session, "role": "user", "content": "hello", "task_id": taskID, "channel_ingested": scenario != "web-origin"})
+ bindingID := x.f.Insert(t, "channel_chat_session_binding", dbfx.Cols{"chat_session_id": session, "installation_id": inst.ID, "channel_type": "weixin", "channel_chat_id": info.UserID, "chat_type": "p2p"})
+ route, _ := json.Marshal(weixinBindingConfig{BotID: info.BotID, UserID: info.UserID})
+ x.f.InsertNoID(t, "channel_task_delivery", dbfx.Cols{"task_id": taskID, "binding_id": bindingID, "installation_id": inst.ID, "channel_type": "weixin", "channel_chat_id": info.UserID, "chat_type": "p2p", "route_revision": 1, "config": route}, "task_id=$1", taskID)
+ x.f.Cleanup(t, `DELETE FROM channel_reply_delivery WHERE turn_id=$1`, taskID)
+ x.f.Cleanup(t, `DELETE FROM channel_outbound_message WHERE installation_id=$1`, inst.ID)
+ if scenario == "revoked" {
+ if err := x.svc.Revoke(ctx, inst.ID, x.workspace); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if scenario == "rebound" {
+ x.f.Exec(t, `UPDATE channel_task_delivery SET config=jsonb_set(config, '{bot_id}', '"previous-bot"') WHERE task_id=$1`, taskID)
+ }
+ var sends atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ sends.Add(1)
+ var body struct {
+ Msg message `json:"msg"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Error(err)
+ }
+ if body.Msg.To != info.UserID || body.Msg.ContextToken != "reply-context" {
+ t.Error("wrong reply context")
+ }
+ if scenario == "response-lost" {
+ _, _ = w.Write([]byte("truncated"))
+ return
+ }
+ _, _ = w.Write([]byte(`{"ret":0}`))
+ }))
+ defer server.Close()
+ o := NewOutbound(x.q, x.svc.box, nil)
+ o.client = providerClient(server)
+ event := events.Event{Type: protocol.EventChatDone, WorkspaceID: x.f.WorkspaceID, ChatSessionID: session, TaskID: taskID, Payload: map[string]any{"content": strings.Repeat("好", 4001), "retry_pending": scenario == "retry-pending"}}
+ for i := 0; i < 2; i++ {
+ err := o.processEvent(ctx, event)
+ if scenario == "accepted" && err != nil {
+ t.Fatal(err)
+ }
+ }
+ want := int32(0)
+ if scenario == "accepted" {
+ want = 2
+ }
+ if scenario == "response-lost" {
+ want = 1
+ }
+ if sends.Load() != want {
+ t.Fatalf("sends=%d, want %d", sends.Load(), want)
+ }
+ })
+ }
+}
diff --git a/server/internal/integrations/weixin/install.go b/server/internal/integrations/weixin/install.go
new file mode 100644
index 0000000000..3b9f82f8bd
--- /dev/null
+++ b/server/internal/integrations/weixin/install.go
@@ -0,0 +1,401 @@
+package weixin
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+)
+
+var (
+ ErrNotFound = errors.New("weixin: connection or login session not found")
+ ErrBusy = errors.New("weixin: login is already being checked")
+ ErrConflict = errors.New("weixin: this bot is already connected; disconnect it before changing its agent")
+ ErrInvalidCode = errors.New("weixin: enter the numeric code shown on your phone")
+ ErrAccess = errors.New("weixin: workspace or agent access changed")
+)
+
+type loginState struct {
+ QRCode string `json:"qrcode"`
+ Content string `json:"content"`
+ BaseURL string `json:"base_url"`
+ InstallationID string `json:"installation_id,omitempty"`
+ InstallationConfig []byte `json:"installation_config,omitempty"`
+}
+
+// Agent identity is exposed only for conflicts within the requested workspace.
+type ConflictError struct {
+ AgentID string
+ AgentName string
+}
+
+func (e *ConflictError) Error() string { return ErrConflict.Error() }
+func (e *ConflictError) Unwrap() error { return ErrConflict }
+
+// LoginView never contains bot credentials, the polling QR value, or a code.
+// Only the initiating Multica user can retrieve this short-lived view.
+type LoginView struct {
+ ID string `json:"id"`
+ Status string `json:"status"`
+ QRCodeURL string `json:"qr_code_url,omitempty"`
+ InstallationID string `json:"installation_id,omitempty"`
+ ExpiresAt string `json:"expires_at"`
+}
+
+type InstallService struct {
+ q *db.Queries
+ tx engine.TxStarter
+ box *secretbox.Box
+ client *http.Client
+ apiBase string // test-only transport override
+}
+
+func NewInstallService(q *db.Queries, tx engine.TxStarter, box *secretbox.Box) (*InstallService, error) {
+ if q == nil || tx == nil || box == nil {
+ return nil, errors.New("weixin: queries, transactions and encryption are required")
+ }
+ return &InstallService{q: q, tx: tx, box: box}, nil
+}
+
+func (s *InstallService) api(base, token string) *apiClient {
+ if s.apiBase != "" {
+ base = s.apiBase
+ }
+ return newAPI(base, token, s.client)
+}
+
+func (s *InstallService) Begin(ctx context.Context, workspace, agent, initiator pgtype.UUID) (LoginView, error) {
+ state := loginState{BaseURL: DefaultBaseURL}
+ var tokens []string
+ inst, err := s.q.GetWeixinInstallationForAgent(ctx, db.GetWeixinInstallationForAgentParams{WorkspaceID: workspace, AgentID: agent})
+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ return LoginView{}, err
+ }
+ if err == nil && inst.Status == "active" && inst.InstallerUserID == initiator {
+ creds, err := decodeCredentials(inst.Config, s.box)
+ if err != nil {
+ return LoginView{}, err
+ }
+ tokens = append(tokens, creds.Token)
+ state.InstallationID = util.UUIDToString(inst.ID)
+ state.InstallationConfig = inst.Config
+ }
+ qr, err := s.api(DefaultBaseURL, "").QRCode(ctx, tokens...)
+ if err != nil {
+ return LoginView{}, err
+ }
+ state.QRCode, state.Content = qr.QRCode, qr.Content
+ raw, _ := json.Marshal(state)
+ sealed, err := s.box.Seal(raw)
+ if err != nil {
+ return LoginView{}, err
+ }
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return LoginView{}, err
+ }
+ defer func() { _ = tx.Rollback(ctx) }()
+ q := s.q.WithTx(tx)
+ // Serialize a user's repeated Connect clicks; the newest QR cancels the old
+ // one even when the two requests land on different replicas.
+ if err := q.LockChannelInstallationAppIDSlot(ctx, db.LockChannelInstallationAppIDSlotParams{ChannelType: "weixin-login", AppID: util.UUIDToString(agent) + ":" + util.UUIDToString(initiator)}); err != nil {
+ return LoginView{}, err
+ }
+ if err := q.CancelPreviousWeixinLogins(ctx, db.CancelPreviousWeixinLoginsParams{WorkspaceID: workspace, AgentID: agent, InitiatorUserID: initiator}); err != nil {
+ return LoginView{}, err
+ }
+ row, err := q.CreateWeixinLoginSession(ctx, db.CreateWeixinLoginSessionParams{ID: dbid.NewV7(), WorkspaceID: workspace, AgentID: agent, InitiatorUserID: initiator, StateEncrypted: sealed})
+ if err != nil {
+ return LoginView{}, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return LoginView{}, err
+ }
+ return s.view(row)
+}
+
+func (s *InstallService) view(row db.WeixinLoginSession) (LoginView, error) {
+ v := LoginView{ID: util.UUIDToString(row.ID), Status: row.Status, ExpiresAt: row.ExpiresAt.Time.UTC().Format(time.RFC3339)}
+ if row.InstallationID.Valid {
+ v.InstallationID = util.UUIDToString(row.InstallationID)
+ }
+ if pendingLogin(row.Status) && !row.ExpiresAt.Time.After(time.Now()) {
+ v.Status = "expired"
+ }
+ if pendingLogin(v.Status) {
+ state, err := s.openState(row.StateEncrypted)
+ if err != nil {
+ return LoginView{}, err
+ }
+ v.QRCodeURL = state.Content
+ }
+ return v, nil
+}
+
+func pendingLogin(status string) bool {
+ return status == "wait" || status == "scaned" || strings.Contains(status, "need_verifycode") || status == "scaned_but_redirect"
+}
+
+func (s *InstallService) openState(sealed []byte) (loginState, error) {
+ var state loginState
+ raw, err := s.box.Open(sealed)
+ if err != nil {
+ return state, err
+ }
+ if err := json.Unmarshal(raw, &state); err != nil {
+ return state, ErrProtocol
+ }
+ if state.QRCode == "" {
+ return state, ErrProtocol
+ }
+ if _, err := validateBaseURL(state.BaseURL); err != nil {
+ return state, err
+ }
+ return state, nil
+}
+
+func (s *InstallService) Get(ctx context.Context, session, workspace, initiator pgtype.UUID) (LoginView, error) {
+ row, err := s.q.GetWeixinLoginSession(ctx, db.GetWeixinLoginSessionParams{ID: session, WorkspaceID: workspace, InitiatorUserID: initiator})
+ if errors.Is(err, pgx.ErrNoRows) {
+ return LoginView{}, ErrNotFound
+ }
+ if err != nil {
+ return LoginView{}, err
+ }
+ return s.view(row)
+}
+
+func (s *InstallService) Poll(ctx context.Context, session, workspace, initiator pgtype.UUID, code string) (LoginView, error) {
+ code = strings.TrimSpace(code)
+ if len(code) > 12 {
+ return LoginView{}, ErrInvalidCode
+ }
+ for _, r := range code {
+ if r < '0' || r > '9' {
+ return LoginView{}, ErrInvalidCode
+ }
+ }
+ lease := dbid.NewV7()
+ row, err := s.q.ClaimWeixinLoginSession(ctx, db.ClaimWeixinLoginSessionParams{ID: session, WorkspaceID: workspace, InitiatorUserID: initiator, LeaseToken: lease})
+ if errors.Is(err, pgx.ErrNoRows) {
+ view, err := s.Get(ctx, session, workspace, initiator)
+ if err == nil && pendingLogin(view.Status) {
+ err = ErrBusy
+ }
+ return view, err
+ }
+ if err != nil {
+ return LoginView{}, err
+ }
+ defer func() {
+ cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ defer cancel()
+ _ = s.q.ReleaseWeixinLoginSession(cleanup, db.ReleaseWeixinLoginSessionParams{ID: session, LeaseToken: lease})
+ }()
+ state, err := s.openState(row.StateEncrypted)
+ if err != nil {
+ return LoginView{}, err
+ }
+ status, err := s.api(state.BaseURL, "").QRStatus(ctx, state.QRCode, code)
+ if err != nil {
+ return LoginView{}, err
+ }
+ if status.Status == "scaned_but_redirect" {
+ state.BaseURL, err = validateBaseURL("https://" + status.RedirectHost)
+ if err != nil {
+ return LoginView{}, err
+ }
+ }
+ if status.Status == "binded_redirect" {
+ if err := s.confirmExisting(ctx, row, state); err != nil {
+ return LoginView{}, err
+ }
+ } else if status.Status == "confirmed" {
+ if err := s.complete(ctx, row, status); err != nil {
+ return LoginView{}, err
+ }
+ } else {
+ var sealed []byte
+ if pendingLogin(status.Status) {
+ raw, _ := json.Marshal(state)
+ sealed, err = s.box.Seal(raw)
+ if err != nil {
+ return LoginView{}, err
+ }
+ } else {
+ sealed = []byte{}
+ }
+ if _, err := s.q.UpdateWeixinLoginSession(ctx, db.UpdateWeixinLoginSessionParams{ID: session, LeaseToken: lease, Status: status.Status, StateEncrypted: sealed}); err != nil {
+ return LoginView{}, err
+ }
+ }
+ return s.Get(ctx, session, workspace, initiator)
+}
+
+func (s *InstallService) complete(ctx context.Context, session db.WeixinLoginSession, result qrStatus) error {
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = tx.Rollback(ctx) }()
+ q := s.q.WithTx(tx)
+ if _, err := q.LockWeixinLoginSession(ctx, db.LockWeixinLoginSessionParams{ID: session.ID, LeaseToken: session.LeaseToken}); err != nil {
+ return ErrNotFound
+ }
+ member, err := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: session.InitiatorUserID, WorkspaceID: session.WorkspaceID})
+ if err != nil || member.Role != "owner" && member.Role != "admin" {
+ return ErrAccess
+ }
+ agent, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: session.AgentID, WorkspaceID: session.WorkspaceID})
+ if err != nil || agent.ArchivedAt.Valid {
+ return ErrAccess
+ }
+ if err := q.LockChannelInstallationAppIDSlot(ctx, db.LockChannelInstallationAppIDSlotParams{ChannelType: string(TypeWeixin), AppID: result.BotID}); err != nil {
+ return err
+ }
+ owner, err := q.GetChannelInstallationSlotOwnerByAppID(ctx, db.GetChannelInstallationSlotOwnerByAppIDParams{ChannelType: string(TypeWeixin), AppID: result.BotID})
+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ return err
+ }
+ if err == nil && owner.Status == "active" && owner.WorkspaceExists && owner.AgentExists && (owner.WorkspaceID != session.WorkspaceID || owner.AgentID != session.AgentID) {
+ return s.conflict(ctx, q, session.WorkspaceID, owner.WorkspaceID, owner.AgentID)
+ }
+ if _, err := q.ReclaimDeadChannelInstallationByAppID(ctx, db.ReclaimDeadChannelInstallationByAppIDParams{ChannelType: string(TypeWeixin), AppID: result.BotID, WorkspaceID: session.WorkspaceID, AgentID: session.AgentID}); err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ return err
+ }
+ old, err := q.GetWeixinInstallationForAgent(ctx, db.GetWeixinInstallationForAgentParams{WorkspaceID: session.WorkspaceID, AgentID: session.AgentID})
+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ return err
+ }
+ if err == nil {
+ previous := DecodePublicConfig(old.Config)
+ if old.Status == "active" && (previous.BotID != result.BotID || previous.UserID != result.UserID || old.InstallerUserID != session.InitiatorUserID) {
+ return s.conflict(ctx, q, session.WorkspaceID, old.WorkspaceID, old.AgentID)
+ }
+ if previous.BotID != result.BotID || previous.UserID != result.UserID || old.InstallerUserID != session.InitiatorUserID {
+ if _, err := q.ClearChannelInstallationBotScopedRows(ctx, old.ID); err != nil {
+ return err
+ }
+ }
+ }
+ sealed, err := s.box.Seal([]byte(result.Token))
+ if err != nil {
+ return err
+ }
+ config, _ := json.Marshal(installConfig{AppID: result.BotID, UserID: result.UserID, BaseURL: result.BaseURL, TokenEncrypted: base64.StdEncoding.EncodeToString(sealed)})
+ inst, err := q.UpsertChannelInstallation(ctx, db.UpsertChannelInstallationParams{WorkspaceID: session.WorkspaceID, AgentID: session.AgentID, ChannelType: string(TypeWeixin), Config: config, InstallerUserID: session.InitiatorUserID})
+ if err != nil {
+ return err
+ }
+ if _, err := q.CreateChannelUserBinding(ctx, db.CreateChannelUserBindingParams{WorkspaceID: session.WorkspaceID, MulticaUserID: session.InitiatorUserID, InstallationID: inst.ID, ChannelType: string(TypeWeixin), ChannelUserID: result.UserID, Config: []byte(`{}`)}); err != nil {
+ return err
+ }
+ if err := q.ResetWeixinAccountState(ctx, db.ResetWeixinAccountStateParams{InstallationID: inst.ID, BotID: result.BotID, UserID: result.UserID}); err != nil {
+ return err
+ }
+ if _, err := q.UpdateWeixinLoginSession(ctx, db.UpdateWeixinLoginSessionParams{ID: session.ID, LeaseToken: session.LeaseToken, Status: "confirmed", StateEncrypted: []byte{}, InstallationID: inst.ID}); err != nil {
+ return err
+ }
+ return tx.Commit(ctx)
+}
+
+func (s *InstallService) conflict(ctx context.Context, q *db.Queries, requestedWorkspace, ownerWorkspace, agentID pgtype.UUID) error {
+ if requestedWorkspace != ownerWorkspace {
+ return ErrConflict
+ }
+ agent, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: agentID, WorkspaceID: requestedWorkspace})
+ if err != nil {
+ return ErrConflict
+ }
+ return &ConflictError{AgentID: util.UUIDToString(agent.ID), AgentName: agent.Name}
+}
+
+func (s *InstallService) confirmExisting(ctx context.Context, session db.WeixinLoginSession, state loginState) error {
+ id, err := util.ParseUUID(state.InstallationID)
+ if err != nil || !id.Valid || len(state.InstallationConfig) == 0 {
+ return ErrProtocol
+ }
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = tx.Rollback(ctx) }()
+ q := s.q.WithTx(tx)
+ if _, err := q.LockWeixinLoginSession(ctx, db.LockWeixinLoginSessionParams{ID: session.ID, LeaseToken: session.LeaseToken}); err != nil {
+ return ErrNotFound
+ }
+ member, err := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: session.InitiatorUserID, WorkspaceID: session.WorkspaceID})
+ if err != nil || member.Role != "owner" && member.Role != "admin" {
+ return ErrAccess
+ }
+ agent, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: session.AgentID, WorkspaceID: session.WorkspaceID})
+ if err != nil || agent.ArchivedAt.Valid {
+ return ErrAccess
+ }
+ inst, err := q.GetWeixinInstallationForAgent(ctx, db.GetWeixinInstallationForAgentParams{WorkspaceID: session.WorkspaceID, AgentID: session.AgentID})
+ if err != nil || inst.ID != id || inst.Status != "active" || inst.InstallerUserID != session.InitiatorUserID || !bytes.Equal(inst.Config, state.InstallationConfig) {
+ return ErrAccess
+ }
+ if _, err := q.UpdateWeixinLoginSession(ctx, db.UpdateWeixinLoginSessionParams{ID: session.ID, LeaseToken: session.LeaseToken, Status: "confirmed", StateEncrypted: []byte{}, InstallationID: inst.ID}); err != nil {
+ return err
+ }
+ return tx.Commit(ctx)
+}
+
+func (s *InstallService) Cancel(ctx context.Context, session, workspace, initiator pgtype.UUID) error {
+ _, err := s.q.CancelWeixinLoginSession(ctx, db.CancelWeixinLoginSessionParams{ID: session, WorkspaceID: workspace, InitiatorUserID: initiator})
+ return err
+}
+
+func (s *InstallService) List(ctx context.Context, workspace pgtype.UUID) ([]db.ChannelInstallation, error) {
+ return s.q.ListChannelInstallationsByWorkspace(ctx, db.ListChannelInstallationsByWorkspaceParams{WorkspaceID: workspace, ChannelType: string(TypeWeixin)})
+}
+
+func (s *InstallService) Revoke(ctx context.Context, installation, workspace pgtype.UUID) error {
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = tx.Rollback(ctx) }()
+ q := s.q.WithTx(tx)
+ row, err := q.GetChannelInstallationInWorkspace(ctx, db.GetChannelInstallationInWorkspaceParams{ID: installation, WorkspaceID: workspace, ChannelType: string(TypeWeixin)})
+ if errors.Is(err, pgx.ErrNoRows) {
+ return ErrNotFound
+ }
+ if err != nil {
+ return err
+ }
+ if err := q.SetChannelInstallationStatus(ctx, db.SetChannelInstallationStatusParams{ID: row.ID, Status: "revoked"}); err != nil {
+ return err
+ }
+ if err := q.DeleteWeixinAccountState(ctx, row.ID); err != nil {
+ return err
+ }
+ return tx.Commit(ctx)
+}
+
+func (s *InstallService) RunCleanup(ctx context.Context) {
+ ticker := time.NewTicker(15 * time.Minute)
+ defer ticker.Stop()
+ for {
+ _ = s.q.PurgeWeixinState(ctx)
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ }
+ }
+}
diff --git a/server/internal/integrations/weixin/media.go b/server/internal/integrations/weixin/media.go
new file mode 100644
index 0000000000..c4452c01d2
--- /dev/null
+++ b/server/internal/integrations/weixin/media.go
@@ -0,0 +1,220 @@
+package weixin
+
+import (
+ "context"
+ "crypto/aes"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "mime"
+ "net/http"
+ "net/url"
+ "path"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// Bound memory use independently of provider-declared lengths. This is a
+// Multica transfer limit, not a claim about WeChat's account-specific quota.
+const maxMediaBytes = 20 << 20
+const defaultCDN = "https://novac2c.cdn.weixin.qq.com/c2c"
+
+type objectStore interface {
+ Upload(context.Context, string, []byte, string, string) (string, error)
+ ObjectURL(string) string
+ KeyFromURL(string) string
+ GetReader(context.Context, string) (io.ReadCloser, error)
+}
+
+type inboundMedia struct {
+ ref mediaRef
+ key, name, placeholder string
+ kind channel.MsgType
+ index int
+}
+
+func messageMedia(msg message) []inboundMedia {
+ var out []inboundMedia
+ counts := map[string]int{}
+ for _, item := range msg.Items {
+ var m inboundMedia
+ switch {
+ case item.Type == 2 && item.Image != nil:
+ m = inboundMedia{ref: item.Image.Media, key: item.Image.AESKey, kind: channel.MsgTypeImage, placeholder: "[Image]"}
+ case item.Type == 3 && item.Voice != nil && item.Voice.Text == "":
+ m = inboundMedia{ref: item.Voice.Media, kind: channel.MsgTypeAudio, placeholder: "[Audio]", name: "voice.silk"}
+ case item.Type == 4 && item.File != nil:
+ m = inboundMedia{ref: item.File.Media, name: item.File.Name, kind: channel.MsgTypeFile, placeholder: "[File]"}
+ case item.Type == 5 && item.Video != nil:
+ m = inboundMedia{ref: item.Video.Media, kind: channel.MsgTypeVideo, placeholder: "[Video]", name: "video.mp4"}
+ default:
+ continue
+ }
+ m.index = counts[m.placeholder]
+ counts[m.placeholder]++
+ out = append(out, m)
+ }
+ return out
+}
+
+func mediaKey(ref mediaRef, imageKey string) ([]byte, error) {
+ if imageKey != "" {
+ key, err := hex.DecodeString(imageKey)
+ if err == nil && len(key) == aes.BlockSize {
+ return key, nil
+ }
+ return nil, ErrProtocol
+ }
+ key, err := base64.StdEncoding.DecodeString(ref.AESKey)
+ if err != nil {
+ return nil, ErrProtocol
+ }
+ if len(key) == 32 {
+ key, err = hex.DecodeString(string(key))
+ }
+ if err != nil || len(key) != aes.BlockSize {
+ return nil, ErrProtocol
+ }
+ return key, nil
+}
+
+// iLink media uses AES-128-ECB with PKCS#7 padding. Authenticate neither
+// arbitrary hosts nor redirected requests with the bot credential.
+func decryptMedia(data, key []byte) ([]byte, error) {
+ block, err := aes.NewCipher(key)
+ if err != nil || len(key) != aes.BlockSize || len(data) == 0 || len(data)%aes.BlockSize != 0 {
+ return nil, ErrProtocol
+ }
+ out := make([]byte, len(data))
+ for i := 0; i < len(data); i += aes.BlockSize {
+ block.Decrypt(out[i:i+aes.BlockSize], data[i:i+aes.BlockSize])
+ }
+ n := int(out[len(out)-1])
+ if n < 1 || n > aes.BlockSize {
+ return nil, ErrProtocol
+ }
+ for _, b := range out[len(out)-n:] {
+ if int(b) != n {
+ return nil, ErrProtocol
+ }
+ }
+ return out[:len(out)-n], nil
+}
+
+func trustedMediaURL(raw string) bool {
+ u, err := url.Parse(raw)
+ return err == nil && u.Scheme == "https" && u.User == nil && u.Port() == "" && u.Fragment == "" && strings.HasSuffix(strings.ToLower(u.Hostname()), ".weixin.qq.com")
+}
+
+func downloadMedia(ctx context.Context, client *http.Client, m inboundMedia) ([]byte, error) {
+ key, err := mediaKey(m.ref, m.key)
+ if err != nil {
+ return nil, err
+ }
+ target := m.ref.FullURL
+ if target == "" && m.ref.Query != "" {
+ target = defaultCDN + "/download?encrypted_query_param=" + url.QueryEscape(m.ref.Query)
+ }
+ if !trustedMediaURL(target) {
+ return nil, ErrProtocol
+ }
+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
+ if err != nil {
+ return nil, ErrProtocol
+ }
+ if client == nil {
+ client = http.DefaultClient
+ }
+ copy := *client
+ copy.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ resp, err := copy.Do(req)
+ if err != nil {
+ return nil, errors.New("weixin: media download failed")
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return nil, &ProviderError{Status: resp.StatusCode}
+ }
+ data, err := io.ReadAll(io.LimitReader(resp.Body, maxMediaBytes+aes.BlockSize+1))
+ if err != nil || len(data) > maxMediaBytes+aes.BlockSize {
+ return nil, errors.New("weixin: media transfer exceeds limit or failed")
+ }
+ plain, err := decryptMedia(data, key)
+ if err != nil || len(plain) > maxMediaBytes {
+ return nil, ErrProtocol
+ }
+ return plain, nil
+}
+
+type mediaResolver struct {
+ store objectStore
+ ledger engine.MediaIntentLedger
+ client *http.Client
+}
+
+func NewMediaResolver(store objectStore, ledger engine.MediaIntentLedger) engine.MediaResolver {
+ return &mediaResolver{store: store, ledger: ledger}
+}
+
+func (r *mediaResolver) HasMedia(msg channel.InboundMessage) bool {
+ raw, err := decodeWeixinRaw(msg)
+ return err == nil && len(messageMedia(raw.Message)) > 0
+}
+
+func (r *mediaResolver) ResolveMedia(ctx context.Context, inst engine.ResolvedInstallation, _ engine.ResolvedIdentity, _ pgtype.UUID, chatMessageID pgtype.UUID, msg channel.InboundMessage) channel.InboundMessage {
+ raw, err := decodeWeixinRaw(msg)
+ if err != nil {
+ return msg
+ }
+ for i, m := range messageMedia(raw.Message) {
+ ref, err := r.ingest(ctx, inst, chatMessageID, i, m)
+ if err != nil {
+ // Be explicit in the persisted prompt: a placeholder is not a file
+ // the model received. The original message stays in WeChat.
+ msg.Text += "\n[WeChat attachment unavailable: file " + strconv.Itoa(i+1) + "; send it again or upload it in Multica.]"
+ continue
+ }
+ msg.MediaRefs = append(msg.MediaRefs, ref)
+ }
+ return msg
+}
+
+func (r *mediaResolver) ingest(ctx context.Context, inst engine.ResolvedInstallation, messageID pgtype.UUID, index int, m inboundMedia) (channel.MediaRef, error) {
+ if r.store == nil || r.ledger == nil {
+ return channel.MediaRef{}, errors.New("weixin: media storage is not configured")
+ }
+ data, err := downloadMedia(ctx, r.client, m)
+ if err != nil {
+ return channel.MediaRef{}, err
+ }
+ contentType := http.DetectContentType(data)
+ name := path.Base(strings.ReplaceAll(m.name, "\\", "/"))
+ if name == "." || name == "/" || name == "" {
+ name = "wechat-" + string(m.kind)
+ if extensions, _ := mime.ExtensionsByType(contentType); len(extensions) > 0 {
+ name += extensions[0]
+ }
+ }
+ sum := sha256.Sum256([]byte(util.UUIDToString(messageID) + ":" + strconv.Itoa(index)))
+ key := path.Join("workspaces", util.UUIDToString(inst.WorkspaceID), "weixin", util.UUIDToString(inst.ID), hex.EncodeToString(sum[:]))
+ link := r.store.ObjectURL(key)
+ owned, err := r.ledger.RecordPendingMediaObject(ctx, engine.RecordPendingMediaObjectParams{StorageKey: key, WorkspaceID: inst.WorkspaceID, ChatMessageID: messageID, StorageURL: link, InstallationID: inst.ID})
+ if err != nil || !owned {
+ return channel.MediaRef{}, fmt.Errorf("weixin: media intent unavailable: %v", err)
+ }
+ if _, err := r.store.Upload(ctx, key, data, contentType, name); err != nil {
+ return channel.MediaRef{}, errors.New("weixin: media storage failed")
+ }
+ return channel.MediaRef{Type: m.kind, StorageKey: key, StorageURL: link, Filename: name, MimeType: contentType, SizeBytes: int64(len(data)), InlinePlaceholder: m.placeholder, InlineIndex: m.index}, nil
+}
diff --git a/server/internal/integrations/weixin/media_test.go b/server/internal/integrations/weixin/media_test.go
new file mode 100644
index 0000000000..9f03b0be6f
--- /dev/null
+++ b/server/internal/integrations/weixin/media_test.go
@@ -0,0 +1,138 @@
+package weixin
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+func TestInboundMediaWithoutStorageIsExplicitlyUnavailable(t *testing.T) {
+ var msg message
+ if err := json.Unmarshal([]byte(`{"message_id":1,"from_user_id":"owner","message_type":1,"item_list":[{"type":2,"image_item":{}}]}`), &msg); err != nil {
+ t.Fatal(err)
+ }
+ in, ok := normalizeMessage(credentials{installConfig: installConfig{AppID: "bot", UserID: "owner"}}, msg)
+ if !ok {
+ t.Fatal("image message was rejected")
+ }
+ resolver := NewMediaResolver(nil, nil)
+ got := resolver.ResolveMedia(context.Background(), engine.ResolvedInstallation{}, engine.ResolvedIdentity{}, pgtype.UUID{}, pgtype.UUID{}, in)
+ if len(got.MediaRefs) != 0 || !strings.Contains(got.Text, "WeChat attachment unavailable") {
+ t.Fatal("missing storage must not look like a delivered attachment")
+ }
+}
+
+func TestMediaCryptoInteroperability(t *testing.T) {
+ key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f")
+ plain, _ := hex.DecodeString("00112233445566778899aabbccddeeff")
+ encrypted, err := encryptMedia(plain, key)
+ // AES-128 ECB known-answer vector, independent of our decryptor.
+ if err != nil || hex.EncodeToString(encrypted[:16]) != "69c4e0d86a7b0430d8cdb78070b4c55a" || len(encrypted) != 32 {
+ t.Fatalf("wrong AES vector or padding: %v", err)
+ }
+ got, err := decryptMedia(encrypted, key)
+ if err != nil || !bytes.Equal(got, plain) {
+ t.Fatalf("decrypt: %v", err)
+ }
+ for _, encoded := range []string{base64.StdEncoding.EncodeToString(key), base64.StdEncoding.EncodeToString([]byte(hex.EncodeToString(key)))} {
+ got, err := mediaKey(mediaRef{AESKey: encoded}, "")
+ if err != nil || !bytes.Equal(got, key) {
+ t.Fatalf("key encoding: %v", err)
+ }
+ }
+ if _, err := decryptMedia(encrypted[:17], key); err == nil {
+ t.Fatal("accepted unaligned ciphertext")
+ }
+ if _, err := decryptMedia(encrypted[:16], key); err == nil {
+ t.Fatal("accepted invalid padding")
+ }
+ if _, err := mediaKey(mediaRef{AESKey: "bad"}, ""); err == nil {
+ t.Fatal("accepted invalid key")
+ }
+}
+
+func TestMediaUploadAndDownloadProtocol(t *testing.T) {
+ plain := []byte("attachment content")
+ var uploadKey, encrypted []byte
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/ilink/bot/getuploadurl":
+ if r.Header.Get("Authorization") != "Bearer token" {
+ t.Error("missing upload authorization")
+ }
+ var body struct {
+ Key string `json:"aeskey"`
+ Size int `json:"rawsize"`
+ MediaType int `json:"media_type"`
+ UserID string `json:"to_user_id"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Error(err)
+ }
+ uploadKey, _ = hex.DecodeString(body.Key)
+ if body.Size != len(plain) || body.MediaType != 3 || body.UserID != "owner" {
+ t.Error("wrong upload metadata")
+ }
+ _, _ = w.Write([]byte(`{"ret":0,"upload_full_url":"https://novac2c.cdn.weixin.qq.com/c2c/upload"}`))
+ case "/c2c/upload":
+ if r.Header.Get("Authorization") != "" || r.Header.Get("AuthorizationType") != "" {
+ t.Error("bot credential leaked to CDN")
+ }
+ encrypted, _ = io.ReadAll(r.Body)
+ got, err := decryptMedia(encrypted, uploadKey)
+ if err != nil || !bytes.Equal(got, plain) {
+ t.Error("uploaded body is not encrypted media")
+ }
+ w.Header().Set("x-encrypted-param", "opaque +/= download")
+ case "/c2c/download":
+ if r.URL.Query().Get("encrypted_query_param") != "opaque +/= download" || r.Header.Get("Authorization") != "" {
+ t.Error("wrong download request")
+ }
+ _, _ = w.Write(encrypted)
+ default:
+ t.Errorf("unexpected path %s", r.URL.Path)
+ }
+ }))
+ defer server.Close()
+ client := providerClient(server)
+ item, err := newAPI(DefaultBaseURL, "token", client).Upload(context.Background(), "owner", plain, "../report.txt", "text/plain")
+ if err != nil || item.File == nil || item.File.Name != "report.txt" {
+ t.Fatalf("upload: %v", err)
+ }
+ decodedKey, _ := base64.StdEncoding.DecodeString(item.File.Media.AESKey)
+ if len(decodedKey) != 32 {
+ t.Fatal("outbound AES key must be base64 of hex text")
+ }
+ got, err := downloadMedia(context.Background(), client, inboundMedia{ref: item.File.Media})
+ if err != nil || !bytes.Equal(got, plain) {
+ t.Fatalf("download: %v", err)
+ }
+}
+
+func TestMediaRejectsUntrustedURLsAndOversize(t *testing.T) {
+ for _, target := range []string{"http://novac2c.cdn.weixin.qq.com/c2c/download", "https://weixin.qq.com.evil.test/file", "https://127.0.0.1/file", "https://user:[email protected]/file"} {
+ if trustedMediaURL(target) {
+ t.Fatalf("accepted %s", target)
+ }
+ }
+ called := false
+ client := &http.Client{Transport: roundTripper(func(*http.Request) (*http.Response, error) { called = true; return nil, ErrProtocol })}
+ _, err := newAPI(DefaultBaseURL, "token", client).Upload(context.Background(), "owner", make([]byte, maxMediaBytes+1), "file", "application/octet-stream")
+ if err == nil || called {
+ t.Fatal("oversize file reached provider")
+ }
+ _, err = downloadMedia(context.Background(), client, inboundMedia{ref: mediaRef{FullURL: "https://evil.test/", AESKey: base64.StdEncoding.EncodeToString([]byte(strings.Repeat("a", 16)))}})
+ if err == nil || called {
+ t.Fatal("untrusted media URL reached transport")
+ }
+}
diff --git a/server/internal/integrations/weixin/media_upload.go b/server/internal/integrations/weixin/media_upload.go
new file mode 100644
index 0000000000..3886749c30
--- /dev/null
+++ b/server/internal/integrations/weixin/media_upload.go
@@ -0,0 +1,158 @@
+package weixin
+
+import (
+ "bytes"
+ "context"
+ "crypto/aes"
+ "crypto/md5" // iLink's upload contract requires the raw file's MD5.
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "io"
+ "net/http"
+ "net/url"
+ "path"
+ "strconv"
+ "strings"
+ "time"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func encryptMedia(data, key []byte) ([]byte, error) {
+ block, err := aes.NewCipher(key)
+ if err != nil || len(key) != aes.BlockSize {
+ return nil, ErrProtocol
+ }
+ padding := aes.BlockSize - len(data)%aes.BlockSize
+ padded := make([]byte, len(data)+padding)
+ copy(padded, data)
+ for i := len(data); i < len(padded); i++ {
+ padded[i] = byte(padding)
+ }
+ for i := 0; i < len(padded); i += aes.BlockSize {
+ block.Encrypt(padded[i:i+aes.BlockSize], padded[i:i+aes.BlockSize])
+ }
+ return padded, nil
+}
+
+func (c *apiClient) Upload(ctx context.Context, userID string, data []byte, filename, contentType string) (messageItem, error) {
+ if len(data) > maxMediaBytes {
+ return messageItem{}, errors.New("weixin: file exceeds the 20 MiB transfer limit")
+ }
+ ctx, cancel := context.WithTimeout(ctx, 45*time.Second)
+ defer cancel()
+ key := make([]byte, aes.BlockSize)
+ fileKey := make([]byte, 16)
+ if _, err := rand.Read(key); err != nil {
+ return messageItem{}, err
+ }
+ if _, err := rand.Read(fileKey); err != nil {
+ return messageItem{}, err
+ }
+ encrypted, err := encryptMedia(data, key)
+ if err != nil {
+ return messageItem{}, err
+ }
+ mediaType := 3 // unknown formats and audio are delivered as ordinary files
+ if contentType == "image/jpeg" || contentType == "image/png" || contentType == "image/gif" || contentType == "image/webp" {
+ mediaType = 1
+ }
+ if contentType == "video/mp4" {
+ mediaType = 2
+ }
+ var result struct {
+ apiResult
+ URL string `json:"upload_full_url"`
+ Param string `json:"upload_param"`
+ }
+ checksum := md5.Sum(data)
+ if err := c.request(ctx, http.MethodPost, "getuploadurl", map[string]any{
+ "filekey": hex.EncodeToString(fileKey), "media_type": mediaType, "to_user_id": userID,
+ "rawsize": len(data), "rawfilemd5": hex.EncodeToString(checksum[:]), "filesize": len(encrypted),
+ "no_need_thumb": true, "aeskey": hex.EncodeToString(key), "base_info": baseInfo(),
+ }, true, &result); err != nil {
+ return messageItem{}, err
+ }
+ if err := result.check(false); err != nil {
+ return messageItem{}, err
+ }
+ target := result.URL
+ if target == "" && result.Param != "" {
+ target = defaultCDN + "/upload?" + url.Values{"encrypted_query_param": {result.Param}, "filekey": {hex.EncodeToString(fileKey)}}.Encode()
+ }
+ if !trustedMediaURL(target) {
+ return messageItem{}, ErrProtocol
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, target, bytes.NewReader(encrypted))
+ if err != nil {
+ return messageItem{}, ErrProtocol
+ }
+ req.Header.Set("Content-Type", "application/octet-stream")
+ resp, err := c.http.Do(req) // no Authorization on the CDN request
+ if err != nil {
+ return messageItem{}, errors.New("weixin: media upload failed")
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return messageItem{}, &ProviderError{Status: resp.StatusCode}
+ }
+ query := resp.Header.Get("x-encrypted-param")
+ if query == "" {
+ return messageItem{}, ErrProtocol
+ }
+ ref := mediaRef{Query: query, AESKey: base64.StdEncoding.EncodeToString([]byte(hex.EncodeToString(key))), EncryptType: 1}
+ filename = path.Base(strings.ReplaceAll(filename, "\\", "/"))
+ if filename == "" || filename == "." || filename == "/" {
+ filename = "attachment"
+ }
+ item := messageItem{}
+ switch mediaType {
+ case 1:
+ item.Type = 2
+ item.Image = &struct {
+ Media mediaRef `json:"media"`
+ AESKey string `json:"aeskey,omitempty"`
+ Size int64 `json:"mid_size,omitempty"`
+ }{Media: ref, Size: int64(len(encrypted))}
+ case 2:
+ item.Type = 5
+ item.Video = &struct {
+ Media mediaRef `json:"media"`
+ Size int64 `json:"video_size,omitempty"`
+ }{Media: ref, Size: int64(len(encrypted))}
+ default:
+ item.Type = 4
+ item.File = &struct {
+ Media mediaRef `json:"media"`
+ Name string `json:"file_name"`
+ Length string `json:"len,omitempty"`
+ }{Media: ref, Name: filename, Length: strconv.Itoa(len(data))}
+ }
+ return item, nil
+}
+
+func (o *Outbound) EnableFileDelivery(store objectStore) { o.objects = store }
+
+func (o *Outbound) attachment(ctx context.Context, api *apiClient, userID string, row db.Attachment) (messageItem, error) {
+ if row.SizeBytes > maxMediaBytes {
+ return messageItem{}, errors.New("weixin: file exceeds the 20 MiB transfer limit")
+ }
+ ctx, cancel := context.WithTimeout(ctx, 45*time.Second)
+ defer cancel()
+ key := o.objects.KeyFromURL(row.Url)
+ if key == "" {
+ return messageItem{}, errors.New("weixin: attachment is not in Multica object storage")
+ }
+ reader, err := o.objects.GetReader(ctx, key)
+ if err != nil {
+ return messageItem{}, errors.New("weixin: cannot read attachment")
+ }
+ defer reader.Close()
+ data, err := io.ReadAll(io.LimitReader(reader, maxMediaBytes+1))
+ if err != nil || len(data) > maxMediaBytes {
+ return messageItem{}, errors.New("weixin: attachment transfer failed or exceeds limit")
+ }
+ return api.Upload(ctx, userID, data, row.Filename, row.ContentType)
+}
diff --git a/server/internal/integrations/weixin/outbound.go b/server/internal/integrations/weixin/outbound.go
new file mode 100644
index 0000000000..1442291eaf
--- /dev/null
+++ b/server/internal/integrations/weixin/outbound.go
@@ -0,0 +1,379 @@
+package weixin
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "hash/fnv"
+ "log/slog"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+const outboundEventQueueDepth = 256
+const outboundSessionQueueDepth = 32
+const outboundSessionLimit = 64
+
+type outboundReply struct {
+ event events.Event
+ payload completion
+ taskID pgtype.UUID
+ delivery db.ChannelTaskDelivery
+}
+
+type outboundSession struct {
+ queue []outboundReply
+}
+
+// Final replies only: iLink has no message-edit contract. The shared delivery
+// lease fences replicas and retry attempts; an ambiguous send is never replayed.
+type Outbound struct {
+ Typing *TypingNotifier
+ q *db.Queries
+ box *secretbox.Box
+ client *http.Client
+ logger *slog.Logger
+ queues [4]chan events.Event
+ mu sync.Mutex
+ sessions map[string]*outboundSession
+ done chan struct{}
+ once sync.Once
+ wg sync.WaitGroup
+ objects objectStore
+}
+
+func NewOutbound(q *db.Queries, box *secretbox.Box, logger *slog.Logger) *Outbound {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ o := &Outbound{q: q, box: box, logger: logger, done: make(chan struct{}), Typing: NewTypingNotifier(q, box, logger), sessions: make(map[string]*outboundSession)}
+ for i := range o.queues {
+ o.queues[i] = make(chan events.Event, outboundEventQueueDepth)
+ }
+ return o
+}
+
+func (o *Outbound) Register(bus *events.Bus) {
+ for _, typ := range []string{protocol.EventChatDone, protocol.EventTaskFailed, protocol.EventTaskCancelled} {
+ bus.Subscribe(typ, o.enqueue)
+ }
+}
+
+func (o *Outbound) Start(ctx context.Context) {
+ o.once.Do(func() {
+ o.Typing.Start(ctx)
+ for _, queue := range o.queues {
+ o.wg.Add(1)
+ go func() {
+ defer o.wg.Done()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case event := <-queue:
+ call, cancel := context.WithTimeout(ctx, 5*time.Second)
+ reply, err := o.prepareEvent(call, event)
+ cancel()
+ if err != nil {
+ o.logger.WarnContext(ctx, "weixin: reply routing failed", "task_id", event.TaskID, "error", err)
+ } else if reply != nil {
+ o.enqueueReply(ctx, *reply)
+ }
+ }
+ }
+ }()
+ }
+ go func() { <-ctx.Done(); close(o.done) }()
+ })
+}
+
+func (o *Outbound) WaitWithTimeout(timeout time.Duration) bool {
+ done := make(chan struct{})
+ go func() { o.wg.Wait(); o.Typing.wait(); close(done) }()
+ select {
+ case <-done:
+ return true
+ case <-time.After(timeout):
+ return false
+ }
+}
+
+func (o *Outbound) enqueue(e events.Event) {
+ if e.ChatSessionID == "" {
+ return
+ }
+ hash := fnv.New32a()
+ _, _ = hash.Write([]byte(e.ChatSessionID))
+ // The event bus is synchronous. Saturation must never hold up task
+ // completion or realtime fanout; the answer remains in the Multica chat.
+ select {
+ case o.queues[hash.Sum32()%uint32(len(o.queues))] <- e:
+ case <-o.done:
+ default:
+ o.logger.Error("weixin: outbound event queue capacity exceeded", "task_id", e.TaskID, "chat_session_id", e.ChatSessionID)
+ }
+}
+
+// Only routed WeChat replies enter these bounded per-session queues. A slow
+// provider call cannot occupy a routing worker or another conversation's sender.
+func (o *Outbound) enqueueReply(ctx context.Context, reply outboundReply) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ if ctx.Err() != nil {
+ return
+ }
+ key := reply.event.ChatSessionID
+ session := o.sessions[key]
+ if session == nil {
+ if len(o.sessions) >= outboundSessionLimit {
+ o.logger.Error("weixin: outbound session capacity exceeded", "task_id", reply.event.TaskID, "chat_session_id", key)
+ return
+ }
+ session = &outboundSession{}
+ o.sessions[key] = session
+ o.wg.Add(1)
+ go o.sendSession(ctx, key, session)
+ }
+ if len(session.queue) >= outboundSessionQueueDepth {
+ o.logger.Error("weixin: outbound session queue capacity exceeded", "task_id", reply.event.TaskID, "chat_session_id", key)
+ return
+ }
+ session.queue = append(session.queue, reply)
+}
+
+func (o *Outbound) sendSession(ctx context.Context, key string, session *outboundSession) {
+ defer o.wg.Done()
+ for {
+ o.mu.Lock()
+ if ctx.Err() != nil || len(session.queue) == 0 {
+ delete(o.sessions, key)
+ o.mu.Unlock()
+ return
+ }
+ reply := session.queue[0]
+ session.queue[0] = outboundReply{}
+ session.queue = session.queue[1:]
+ o.mu.Unlock()
+ call, cancel := context.WithTimeout(ctx, 5*time.Minute)
+ if err := o.deliverReply(call, reply); err != nil {
+ o.logger.WarnContext(ctx, "weixin: reply delivery failed", "task_id", reply.event.TaskID, "error", err)
+ }
+ cancel()
+ }
+}
+
+type completion struct {
+ TaskID string `json:"task_id"`
+ MessageID string `json:"message_id"`
+ Content string `json:"content"`
+ RetryPending bool `json:"retry_pending"`
+}
+
+func (o *Outbound) prepareEvent(ctx context.Context, event events.Event) (*outboundReply, error) {
+ var payload completion
+ raw, _ := json.Marshal(event.Payload)
+ if err := json.Unmarshal(raw, &payload); err != nil {
+ return nil, nil
+ }
+ if payload.RetryPending {
+ return nil, nil
+ }
+ if event.TaskID != "" {
+ payload.TaskID = event.TaskID
+ }
+ taskID, err := util.ParseUUID(payload.TaskID)
+ if err != nil || !taskID.Valid {
+ return nil, nil
+ }
+ delivery, err := o.q.GetChannelTaskDelivery(ctx, taskID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ if delivery.ChannelType != string(TypeWeixin) {
+ return nil, nil
+ }
+ return &outboundReply{event: event, payload: payload, taskID: taskID, delivery: delivery}, nil
+}
+
+func (o *Outbound) deliverReply(ctx context.Context, reply outboundReply) error {
+ event, payload, taskID, delivery := reply.event, reply.payload, reply.taskID, reply.delivery
+ task, err := o.q.GetAgentTask(ctx, taskID)
+ if err != nil {
+ return err
+ }
+ defer o.Typing.Wake(task.ChatSessionID)
+ fromChannel, err := engine.TaskInputIsChannelIngested(ctx, o.q, task)
+ if err != nil || !fromChannel {
+ return err
+ }
+ inst, err := o.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{ID: delivery.InstallationID, ChannelType: string(TypeWeixin)})
+ if err != nil {
+ return err
+ }
+ if inst.Status != "active" {
+ return nil
+ }
+ creds, err := decodeCredentials(inst.Config, o.box)
+ if err != nil {
+ return err
+ }
+ var route weixinBindingConfig
+ if json.Unmarshal(delivery.Config, &route) != nil || route.BotID != creds.AppID || route.UserID != creds.UserID || delivery.ChannelChatID != creds.UserID {
+ return ErrAccess // a disconnected/rebound bot cannot receive old tasks
+ }
+ turn, err := o.q.GetChannelReplyTurn(ctx, taskID)
+ if err != nil {
+ return err
+ }
+ if !turn.TurnID.Valid {
+ return ErrProtocol
+ }
+ owner := dbid.NewV7()
+ lease, err := o.q.AcquireChannelReplyDelivery(ctx, db.AcquireChannelReplyDeliveryParams{TurnID: turn.TurnID, TaskID: taskID, AttemptDepth: int32(turn.AttemptDepth), BindingID: delivery.BindingID, InstallationID: inst.ID, ChannelType: string(TypeWeixin), ChatID: creds.UserID, Phase: "terminal", OwnerToken: owner, LeaseSeconds: 60})
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ defer func() {
+ record, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ defer cancel()
+ _, _ = o.q.ReleaseChannelReplyDelivery(record, db.ReleaseChannelReplyDeliveryParams{TurnID: turn.TurnID, OwnerToken: owner})
+ }()
+ settle := func(reason string) error {
+ record, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ defer cancel()
+ _, err := o.q.SettleChannelReplyDelivery(record, db.SettleChannelReplyDeliveryParams{TurnID: turn.TurnID, OwnerToken: owner, SettledReason: reason})
+ return err
+ }
+ if lease.SendState == "in_flight" || lease.SendState == "unknown" {
+ return settle("send_result_unknown")
+ }
+ if event.Type == protocol.EventTaskFailed {
+ payload.Content = "This run failed. Open Multica to review the error and try again."
+ }
+ if event.Type == protocol.EventTaskCancelled {
+ return settle("cancelled")
+ }
+ chunks := splitText(payload.Content, 4000)
+ var attachments []db.Attachment
+ if o.objects != nil && event.Type == protocol.EventChatDone && payload.MessageID != "" {
+ messageID, parseErr := util.ParseUUID(payload.MessageID)
+ if parseErr != nil {
+ return parseErr
+ }
+ attachments, err = o.q.ListAttachmentsByChatMessage(ctx, db.ListAttachmentsByChatMessageParams{ChatMessageID: messageID, WorkspaceID: inst.WorkspaceID})
+ if err != nil {
+ return err
+ }
+ }
+ for i := int(lease.ChunksSent); i < len(chunks)+len(attachments); i++ {
+ // Revalidate revocation and the current context before every provider
+ // call. The 15s send budget fits inside the renewed 60s owner lease.
+ api, token, err := o.sender(ctx, inst.ID, creds.AppID, creds.UserID)
+ if err != nil {
+ return err
+ }
+ msg := textMessage(creds.UserID, token, util.UUIDToString(dbid.NewV7()), "")
+ if i < len(chunks) {
+ msg = textMessage(creds.UserID, token, msg.ClientID, chunks[i])
+ } else {
+ item, prepErr := o.attachment(ctx, api, creds.UserID, attachments[i-len(chunks)])
+ if prepErr != nil {
+ msg = textMessage(creds.UserID, token, msg.ClientID, "This file could not be sent to WeChat. It is still attached to the reply in Multica.")
+ o.logger.WarnContext(ctx, "weixin: attachment unavailable", "error", prepErr)
+ } else {
+ msg.Items = []messageItem{item}
+ }
+ }
+ // Upload preparation may take longer than a lease. Recheck installation
+ // and ownership after it, before posting anything into the conversation.
+ api, token, err = o.sender(ctx, inst.ID, creds.AppID, creds.UserID)
+ if err != nil {
+ return err
+ }
+ msg.ContextToken = token
+ rows, err := o.q.RenewChannelReplyDelivery(ctx, db.RenewChannelReplyDeliveryParams{TurnID: turn.TurnID, OwnerToken: owner, LeaseSeconds: 60})
+ if err != nil || rows != 1 {
+ return err
+ }
+ rows, err = o.q.MarkChannelReplyDeliverySending(ctx, db.MarkChannelReplyDeliverySendingParams{TurnID: turn.TurnID, OwnerToken: owner})
+ if err != nil || rows != 1 {
+ return err
+ }
+ messageID, sendErr := api.Send(ctx, msg)
+ record, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ if sendErr != nil {
+ // Do not infer non-delivery from a timeout, malformed response, or
+ // HTTP error. Keeping unknown also covers a process dying mid-send.
+ _, _ = o.q.MarkChannelReplyDeliverySendUnknown(record, turn.TurnID)
+ cancel()
+ _ = settle("send_result_unknown")
+ return sendErr
+ }
+ rows, err = o.q.RecordChannelReplyDeliveryChunk(record, db.RecordChannelReplyDeliveryChunkParams{TurnID: turn.TurnID, OwnerToken: owner, MessageID: messageID, ChunksSent: int32(i + 1)})
+ if err == nil && rows == 1 {
+ err = o.q.RecordChannelOutboundMessage(record, db.RecordChannelOutboundMessageParams{OutboundInstallationID: inst.ID, OutboundChannelType: string(TypeWeixin), OutboundMessageID: messageID, OutboundBindingID: delivery.BindingID, OutboundRouteRevision: delivery.RouteRevision, OutboundTaskID: taskID, OutboundKind: "task_reply"})
+ }
+ cancel()
+ if err != nil {
+ return err
+ }
+ if rows != 1 {
+ return ErrBusy
+ }
+ }
+ return settle("delivered")
+}
+
+func (o *Outbound) sender(ctx context.Context, installationID pgtype.UUID, botID, userID string) (*apiClient, string, error) {
+ inst, err := o.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{ID: installationID, ChannelType: string(TypeWeixin)})
+ if err != nil {
+ return nil, "", err
+ }
+ if inst.Status != "active" {
+ return nil, "", ErrNotFound
+ }
+ creds, err := decodeCredentials(inst.Config, o.box)
+ if err != nil {
+ return nil, "", err
+ }
+ if creds.AppID != botID || creds.UserID != userID {
+ return nil, "", ErrAccess
+ }
+ state, err := o.q.GetWeixinAccountState(ctx, db.GetWeixinAccountStateParams{InstallationID: inst.ID, BotID: botID})
+ if err != nil {
+ return nil, "", err
+ }
+ token, err := o.box.Open(state.ContextTokenEncrypted)
+ if err != nil || len(token) == 0 {
+ return nil, "", ErrNoContext
+ }
+ return newAPI(creds.BaseURL, creds.Token, o.client), string(token), nil
+}
+
+func splitText(text string, limit int) []string {
+ var chunks []string
+ runes := []rune(text)
+ for len(runes) > 0 {
+ n := min(limit, len(runes))
+ chunks = append(chunks, string(runes[:n]))
+ runes = runes[n:]
+ }
+ return chunks
+}
diff --git a/server/internal/integrations/weixin/outbound_test.go b/server/internal/integrations/weixin/outbound_test.go
new file mode 100644
index 0000000000..9d2c0d2471
--- /dev/null
+++ b/server/internal/integrations/weixin/outbound_test.go
@@ -0,0 +1,177 @@
+package weixin
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "hash/fnv"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ dbfx "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func (o *Outbound) processEvent(ctx context.Context, event events.Event) error {
+ reply, err := o.prepareEvent(ctx, event)
+ if err != nil || reply == nil {
+ return err
+ }
+ return o.deliverReply(ctx, *reply)
+}
+
+func TestOutboundFullQueueDoesNotBlockEventBus(t *testing.T) {
+ var logs bytes.Buffer
+ o := NewOutbound(nil, nil, slog.New(slog.NewTextHandler(&logs, nil)))
+ defer close(o.done)
+ for _, queue := range o.queues {
+ for i := 0; i < cap(queue); i++ {
+ queue <- events.Event{}
+ }
+ }
+ bus := events.New()
+ o.Register(bus)
+ fannedOut := make(chan struct{})
+ bus.SubscribeAll(func(events.Event) { close(fannedOut) })
+ go bus.Publish(events.Event{Type: protocol.EventChatDone, ChatSessionID: "session", TaskID: "task"})
+ select {
+ case <-fannedOut:
+ case <-time.After(time.Second):
+ t.Fatal("full WeChat queue blocked realtime fanout")
+ }
+ if !strings.Contains(logs.String(), "capacity exceeded") || !strings.Contains(logs.String(), "level=ERROR") {
+ t.Fatal("dropped reply was not logged as an error")
+ }
+}
+
+func TestOutboundDeliveryQueueLimits(t *testing.T) {
+ var logs bytes.Buffer
+ o := NewOutbound(nil, nil, slog.New(slog.NewTextHandler(&logs, nil)))
+ session := &outboundSession{queue: make([]outboundReply, outboundSessionQueueDepth)}
+ o.sessions["session"] = session
+ o.enqueueReply(context.Background(), outboundReply{event: events.Event{ChatSessionID: "session"}})
+ if len(session.queue) != outboundSessionQueueDepth {
+ t.Fatal("full session queue grew")
+ }
+ for i := 1; i < outboundSessionLimit; i++ {
+ o.sessions[util.UUIDToString(dbid.NewV7())] = &outboundSession{}
+ }
+ o.enqueueReply(context.Background(), outboundReply{event: events.Event{ChatSessionID: "new-session"}})
+ if len(o.sessions) != outboundSessionLimit || o.sessions["new-session"] != nil {
+ t.Fatal("sender concurrency limit was exceeded")
+ }
+ if strings.Count(logs.String(), "capacity exceeded") != 2 {
+ t.Fatal("queue overflow did not report both dropped replies")
+ }
+}
+
+func outboundTestEvent(t *testing.T, x *databaseFixture, inst db.ChannelInstallation, session, binding, content string) events.Event {
+ t.Helper()
+ taskID := x.f.Task(t, util.UUIDToString(x.agent), dbfx.Cols{"chat_session_id": session, "status": "completed", "runtime_id": x.f.Runtime(t, "test runtime")})
+ x.f.Exec(t, `UPDATE agent_task_queue SET chat_input_task_id=id WHERE id=$1`, taskID)
+ x.f.Insert(t, "chat_message", dbfx.Cols{"chat_session_id": session, "role": "user", "content": "hello", "task_id": taskID, "channel_ingested": true})
+ info := DecodePublicConfig(inst.Config)
+ route, _ := json.Marshal(weixinBindingConfig{BotID: info.BotID, UserID: info.UserID})
+ x.f.InsertNoID(t, "channel_task_delivery", dbfx.Cols{"task_id": taskID, "binding_id": binding, "installation_id": inst.ID, "channel_type": "weixin", "channel_chat_id": info.UserID, "chat_type": "p2p", "route_revision": 1, "config": route}, "task_id=$1", taskID)
+ x.f.Cleanup(t, `DELETE FROM channel_reply_delivery WHERE turn_id=$1`, taskID)
+ x.f.Cleanup(t, `DELETE FROM channel_outbound_message WHERE installation_id=$1`, inst.ID)
+ return events.Event{Type: protocol.EventChatDone, WorkspaceID: x.f.WorkspaceID, ChatSessionID: session, TaskID: taskID, Payload: map[string]any{"content": content}}
+}
+
+func TestOutboundSlowSendDoesNotBlockRoutingOrOtherSessions(t *testing.T) {
+ slow, fast := newDatabaseFixture(t), newDatabaseFixture(t)
+ slowInst, fastInst := slow.connect(t), fast.connect(t)
+ slowSession := slow.f.ChatSession(t, util.UUIDToString(slow.agent))
+ queueIndex := func(s string) uint32 { h := fnv.New32a(); _, _ = h.Write([]byte(s)); return h.Sum32() % 4 }
+ fastSession := util.UUIDToString(dbid.NewV7())
+ for queueIndex(fastSession) != queueIndex(slowSession) {
+ fastSession = util.UUIDToString(dbid.NewV7())
+ }
+ fast.f.ChatSession(t, util.UUIDToString(fast.agent), dbfx.Cols{"id": fastSession})
+ makeBinding := func(x *databaseFixture, inst db.ChannelInstallation, session string) string {
+ info := DecodePublicConfig(inst.Config)
+ sealed, _ := x.svc.box.Seal([]byte("reply-context"))
+ if _, err := x.q.SaveWeixinContext(context.Background(), db.SaveWeixinContextParams{InstallationID: inst.ID, BotID: info.BotID, UserID: info.UserID, ContextTokenEncrypted: sealed, ContextTimeMs: 123}); err != nil {
+ t.Fatal(err)
+ }
+ return x.f.Insert(t, "channel_chat_session_binding", dbfx.Cols{"chat_session_id": session, "installation_id": inst.ID, "channel_type": "weixin", "channel_chat_id": info.UserID, "chat_type": "p2p"})
+ }
+ slowBinding, fastBinding := makeBinding(slow, slowInst, slowSession), makeBinding(fast, fastInst, fastSession)
+ first := outboundTestEvent(t, slow, slowInst, slowSession, slowBinding, "slow-first")
+ second := outboundTestEvent(t, slow, slowInst, slowSession, slowBinding, "slow-second")
+ other := outboundTestEvent(t, fast, fastInst, fastSession, fastBinding, "fast")
+ started, release := make(chan struct{}), make(chan struct{})
+ var releaseOnce sync.Once
+ sent := make(chan string, 8)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body struct {
+ Msg message `json:"msg"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Error(err)
+ return
+ }
+ text := body.Msg.Items[0].Text.Text
+ if text == "slow-first" {
+ close(started)
+ select {
+ case <-release:
+ case <-r.Context().Done():
+ return
+ }
+ }
+ sent <- text
+ _, _ = w.Write([]byte(`{"ret":0}`))
+ }))
+ defer server.Close()
+ o := NewOutbound(slow.q, slow.svc.box, nil)
+ o.client = providerClient(server)
+ ctx, cancel := context.WithCancel(context.Background())
+ o.Start(ctx)
+ defer func() {
+ releaseOnce.Do(func() { close(release) })
+ cancel()
+ if !o.WaitWithTimeout(3 * time.Second) {
+ t.Error("outbound workers did not stop")
+ }
+ }()
+ bus := events.New()
+ o.Register(bus)
+ bus.Publish(first)
+ select {
+ case <-started:
+ case <-time.After(3 * time.Second):
+ t.Fatal("first send never started")
+ }
+ bus.Publish(second)
+ bus.Publish(events.Event{Type: protocol.EventChatDone, ChatSessionID: fastSession, TaskID: util.UUIDToString(dbid.NewV7())})
+ bus.Publish(other)
+ select {
+ case text := <-sent:
+ if text != "fast" {
+ t.Fatalf("same-session reply overtook blocked send: %s", text)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("slow WeChat send blocked routing or another conversation")
+ }
+ releaseOnce.Do(func() { close(release) })
+ for _, want := range []string{"slow-first", "slow-second"} {
+ select {
+ case text := <-sent:
+ if text != want {
+ t.Fatalf("out-of-order reply: got %s want %s", text, want)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatalf("missing reply: %s", want)
+ }
+ }
+}
diff --git a/server/internal/integrations/weixin/replier.go b/server/internal/integrations/weixin/replier.go
new file mode 100644
index 0000000000..1972570133
--- /dev/null
+++ b/server/internal/integrations/weixin/replier.go
@@ -0,0 +1,59 @@
+package weixin
+
+import (
+ "context"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+)
+
+// Reply implements the shared engine's command/status notices. The scanner
+// was already bound to the initiating Multica user during QR confirmation.
+func (o *Outbound) Reply(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, result engine.Result) {
+ var text string
+ switch result.Outcome {
+ case engine.OutcomeAgentOffline:
+ text = "This agent is offline. Start its runtime in Multica, then send your message again."
+ case engine.OutcomeAgentArchived:
+ text = "This agent is archived. Restore it in Multica before continuing."
+ case engine.OutcomeInvokeDenied:
+ text = "You no longer have permission to run this agent. Check your workspace access in Multica."
+ case engine.OutcomeNeedsBinding:
+ text = "Reconnect WeChat in Multica to link this account."
+ case engine.OutcomeFreshPending:
+ text = "Your next message will start with fresh context."
+ case engine.OutcomeChatStarted:
+ text = "Started a new Multica chat. Send your next message here."
+ case engine.OutcomeIssueUsage:
+ text = "Use /issue <title> followed by an optional description."
+ case engine.OutcomeIngested:
+ if result.IssueID.Valid {
+ text = "Created " + result.IssueIdentifier + ": " + result.IssueTitle
+ if result.IssueDuplicate {
+ text = "This issue already exists: " + result.IssueIdentifier
+ }
+ }
+ case engine.OutcomeDropped:
+ if result.DropReason == engine.DropReasonNonWorkspaceMember {
+ text = "You are no longer a member of this Multica workspace."
+ }
+ }
+ if text == "" {
+ return
+ }
+ row, ok := inst.Platform.(db.ChannelInstallation)
+ if !ok {
+ return
+ }
+ info := DecodePublicConfig(row.Config)
+ api, token, err := o.sender(ctx, inst.ID, info.BotID, msg.Source.SenderID)
+ if err == nil {
+ _, err = api.Send(ctx, textMessage(msg.Source.ChatID, token, util.UUIDToString(dbid.NewV7()), text))
+ }
+ if err != nil {
+ o.logger.WarnContext(ctx, "weixin: status reply failed", "error", err)
+ }
+}
diff --git a/server/internal/integrations/weixin/resolvers.go b/server/internal/integrations/weixin/resolvers.go
new file mode 100644
index 0000000000..7daff51d75
--- /dev/null
+++ b/server/internal/integrations/weixin/resolvers.go
@@ -0,0 +1,262 @@
+package weixin
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+)
+
+const originWeixinChat = "weixin_chat"
+
+func NewWeixinResolverSet(q *db.Queries, tx engine.TxStarter, replier engine.OutboundReplier, typing engine.TypingNotifier, media engine.MediaResolver) engine.ResolverSet {
+ return engine.ResolverSet{
+ Installation: &installationResolver{q: q},
+ Identity: &identityResolver{q: q},
+ Dedup: &deduper{q: q},
+ Session: &sessionBinder{session: engine.NewChatSession(q, tx, TypeWeixin, engine.SessionTitles{
+ Group: "WeChat group",
+ Direct: "WeChat direct message",
+ Fallback: "WeChat chat",
+ })},
+ Media: media,
+ Audit: &auditor{q: q},
+ Replier: replier,
+ Typing: typing,
+ OriginType: originWeixinChat,
+ }
+}
+
+var (
+ _ engine.InstallationResolver = (*installationResolver)(nil)
+ _ engine.IdentityResolver = (*identityResolver)(nil)
+ _ engine.Deduper = (*deduper)(nil)
+ _ engine.SessionBinder = (*sessionBinder)(nil)
+ _ engine.Auditor = (*auditor)(nil)
+)
+
+type weixinBindingConfig struct {
+ BotID string `json:"bot_id"`
+ UserID string `json:"user_id"`
+}
+
+func weixinSessionRouting(msg channel.InboundMessage) (string, []byte, string) {
+ raw, _ := decodeWeixinRaw(msg)
+ config, _ := json.Marshal(weixinBindingConfig{BotID: raw.BotID, UserID: msg.Source.SenderID})
+ return msg.Source.ChatID, config, ""
+}
+
+func decodeWeixinRaw(msg channel.InboundMessage) (weixinRawEvent, error) {
+ var raw weixinRawEvent
+ if len(msg.Raw) == 0 {
+ return weixinRawEvent{}, errors.New("weixin: inbound message Raw is empty")
+ }
+ if err := json.Unmarshal(msg.Raw, &raw); err != nil {
+ return weixinRawEvent{}, fmt.Errorf("decode weixin inbound raw: %w", err)
+ }
+ return raw, nil
+}
+
+func nullText(s string) pgtype.Text {
+ if s == "" {
+ return pgtype.Text{}
+ }
+ return pgtype.Text{String: s, Valid: true}
+}
+
+type installationResolver struct{ q *db.Queries }
+
+func (r *installationResolver) ResolveInstallation(ctx context.Context, msg channel.InboundMessage) (engine.ResolvedInstallation, error) {
+ raw, err := decodeWeixinRaw(msg)
+ if err != nil {
+ return engine.ResolvedInstallation{}, err
+ }
+ inst, err := r.q.GetChannelInstallationByAppID(ctx, db.GetChannelInstallationByAppIDParams{
+ ChannelType: string(TypeWeixin),
+ AppID: raw.BotID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ResolvedInstallation{}, engine.ErrInstallationNotFound
+ }
+ return engine.ResolvedInstallation{}, err
+ }
+ return engine.ResolvedInstallation{
+ ID: inst.ID,
+ WorkspaceID: inst.WorkspaceID,
+ AgentID: inst.AgentID,
+ InstallerUserID: inst.InstallerUserID,
+ Active: inst.Status == "active",
+ Platform: inst,
+ }, nil
+}
+
+type identityResolver struct{ q *db.Queries }
+
+func (r *identityResolver) ResolveSender(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage) (engine.ResolvedIdentity, error) {
+ binding, err := r.q.GetChannelUserBindingByUserID(ctx, db.GetChannelUserBindingByUserIDParams{
+ InstallationID: inst.ID,
+ ChannelUserID: msg.Source.SenderID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ResolvedIdentity{}, engine.ErrSenderUnbound
+ }
+ return engine.ResolvedIdentity{}, err
+ }
+ if _, err := r.q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: binding.MulticaUserID,
+ WorkspaceID: inst.WorkspaceID,
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ResolvedIdentity{}, engine.ErrSenderNotMember
+ }
+ return engine.ResolvedIdentity{}, err
+ }
+ return engine.ResolvedIdentity{UserID: binding.MulticaUserID}, nil
+}
+
+type deduper struct{ q *db.Queries }
+
+func (r *deduper) Claim(ctx context.Context, installationID pgtype.UUID, messageID string) (pgtype.UUID, error) {
+ claim, err := r.q.ClaimChannelInboundDedup(ctx, db.ClaimChannelInboundDedupParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return pgtype.UUID{}, engine.ErrDuplicate
+ }
+ return pgtype.UUID{}, err
+ }
+ return claim.ClaimToken, nil
+}
+
+func (r *deduper) Mark(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
+ _, err := r.q.MarkChannelInboundDedupProcessed(ctx, db.MarkChannelInboundDedupProcessedParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ ClaimToken: claimToken,
+ })
+ return err
+}
+
+func (r *deduper) Release(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
+ _, err := r.q.ReleaseChannelInboundDedup(ctx, db.ReleaseChannelInboundDedupParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ ClaimToken: claimToken,
+ })
+ return err
+}
+
+type chatSession interface {
+ EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
+ StartSession(ctx context.Context, in engine.StartSessionInput) (engine.StartSessionResult, error)
+ MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error
+ AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
+ BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error
+}
+
+type sessionBinder struct{ session chatSession }
+
+func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessionParams) (pgtype.UUID, error) {
+ bindingKey, config, _ := weixinSessionRouting(p.Message)
+ return r.session.EnsureSession(ctx, engine.EnsureSessionInput{
+ WorkspaceID: p.Installation.WorkspaceID,
+ AgentID: p.Installation.AgentID,
+ InstallationID: p.Installation.ID,
+ Sender: p.Sender,
+ BindingKey: bindingKey,
+ BindingConfig: config,
+ ChatType: p.Message.Source.ChatType,
+ })
+}
+
+func (r *sessionBinder) StartSession(ctx context.Context, p engine.StartSessionParams) (engine.StartSessionResult, error) {
+ bindingKey, config, replyThread := weixinSessionRouting(p.Message)
+ result, err := r.session.StartSession(ctx, engine.StartSessionInput{
+ EnsureSessionInput: engine.EnsureSessionInput{
+ WorkspaceID: p.Installation.WorkspaceID, AgentID: p.Installation.AgentID,
+ InstallationID: p.Installation.ID, Sender: p.Creator,
+ BindingKey: bindingKey, BindingConfig: config, ChatType: p.Message.Source.ChatType,
+ },
+ Initiator: p.Sender,
+ Body: p.Message.Text, CommandText: p.Message.CommandText, MessageID: p.Message.MessageID, ThreadID: replyThread,
+ ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,
+ PersistMessage: p.PersistMessage, HistoryBoundaryPending: p.HistoryBoundaryPending,
+ BeforeCommit: p.BeforeCommit,
+ })
+ return engine.StartSessionResult{
+ SessionID: result.SessionID, BindingID: result.BindingID,
+ RouteRevision: result.RouteRevision, Append: result.Append,
+ }, err
+}
+
+func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error {
+ return r.session.MarkPendingFresh(ctx, sessionID, messageID)
+}
+
+func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
+ _, _, replyThread := weixinSessionRouting(p.Message)
+ commandText := p.Message.CommandText
+ if commandText == "" {
+ commandText = p.Message.Text
+ }
+ return r.session.AppendUserMessage(ctx, engine.AppendInput{
+ SessionID: p.SessionID,
+ Sender: p.Sender,
+ InstallationID: p.InstallationID,
+ Body: p.Message.Text,
+ CommandText: commandText,
+ MessageID: p.Message.MessageID,
+ ThreadID: replyThread,
+ ClaimToken: p.ClaimToken,
+ MediaPendingSeconds: p.MediaPendingSeconds,
+ ForceFresh: p.Message.ForceFresh,
+ })
+}
+
+func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) (engine.BindMediaResult, error) {
+ in := engine.BindMediaInput{
+ MessageID: p.MessageID,
+ SessionID: p.SessionID,
+ WorkspaceID: p.WorkspaceID,
+ Sender: p.Sender,
+ IssueID: p.IssueID,
+ IssueDescriptionBase: p.IssueDescriptionBase,
+ IssueCommandText: p.IssueCommandText,
+ Body: p.Body,
+ MediaRefs: p.MediaRefs,
+ }
+ if richer, ok := r.session.(interface {
+ BindMediaRefsWithResult(context.Context, engine.BindMediaInput) (engine.BindMediaResult, error)
+ }); ok {
+ return richer.BindMediaRefsWithResult(ctx, in)
+ }
+ return engine.BindMediaResult{}, r.session.BindMediaRefs(ctx, in)
+}
+
+type auditor struct{ q *db.Queries }
+
+func (r *auditor) RecordDrop(ctx context.Context, instID pgtype.UUID, msg channel.InboundMessage, reason engine.DropReason) error {
+ raw, _ := decodeWeixinRaw(msg) // best-effort; a decode miss still audits
+ return r.q.RecordChannelInboundDrop(ctx, db.RecordChannelInboundDropParams{
+ ID: dbid.NewV7(),
+ ChannelType: string(TypeWeixin),
+ EventType: raw.EventType,
+ DropReason: string(reason),
+ InstallationID: instID,
+ ChannelChatID: nullText(msg.Source.ChatID),
+ ChannelEventID: nullText(msg.EventID),
+ ChannelMessageID: nullText(msg.MessageID),
+ })
+}
diff --git a/server/internal/integrations/weixin/resolvers_test.go b/server/internal/integrations/weixin/resolvers_test.go
new file mode 100644
index 0000000000..1b596ae1de
--- /dev/null
+++ b/server/internal/integrations/weixin/resolvers_test.go
@@ -0,0 +1,37 @@
+package weixin
+
+import (
+ "context"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+)
+
+type captureMediaSession struct {
+ chatSession
+ input engine.BindMediaInput
+}
+
+func (s *captureMediaSession) BindMediaRefs(_ context.Context, in engine.BindMediaInput) error {
+ s.input = in
+ return nil
+}
+
+func TestMediaBindingPreservesFailureNoticeAndIssueDestination(t *testing.T) {
+ session := &captureMediaSession{}
+ binder := &sessionBinder{session: session}
+ params := engine.BindMediaParams{
+ IssueID: dbid.NewV7(),
+ IssueDescriptionBase: pgtype.Text{String: "Original description", Valid: true},
+ IssueCommandText: "/issue Review image",
+ Body: "[Image]\n[WeChat attachment unavailable: file 1; send it again or upload it in Multica.]",
+ }
+ if _, err := binder.BindMedia(context.Background(), params); err != nil {
+ t.Fatal(err)
+ }
+ if session.input.Body != params.Body || session.input.IssueID != params.IssueID || session.input.IssueDescriptionBase != params.IssueDescriptionBase || session.input.IssueCommandText != params.IssueCommandText {
+ t.Fatal("media binding dropped the failure notice or /issue destination")
+ }
+}
diff --git a/server/internal/integrations/weixin/typing.go b/server/internal/integrations/weixin/typing.go
new file mode 100644
index 0000000000..6c2e40122b
--- /dev/null
+++ b/server/internal/integrations/weixin/typing.go
@@ -0,0 +1,225 @@
+package weixin
+
+import (
+ "context"
+ "log/slog"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+const typingKeepalive = 5 * time.Second
+const typingCallTimeout = 3 * time.Second
+const typingTicketTTL = 5 * time.Minute
+
+type typingStore interface {
+ IsWeixinTypingActive(context.Context, db.IsWeixinTypingActiveParams) (bool, error)
+ SettleWeixinTypingInputs(context.Context, db.SettleWeixinTypingInputsParams) error
+ GetWeixinAccountState(context.Context, db.GetWeixinAccountStateParams) (db.WeixinAccountState, error)
+}
+
+type typingRun struct {
+ installation pgtype.UUID
+ cancel context.CancelFunc
+ wake chan struct{}
+ done chan struct{}
+}
+
+type cachedTypingTicket struct {
+ user, token, ticket string
+ expires time.Time
+}
+
+// Only the ingesting connector starts keepalives. Durable task state also clears
+// them when a different API replica receives completion, cancellation or retry.
+type TypingNotifier struct {
+ q typingStore
+ box *secretbox.Box
+ client *http.Client
+ logger *slog.Logger
+ interval time.Duration
+ mu sync.Mutex
+ ctx context.Context
+ runs map[pgtype.UUID]*typingRun
+ tickets map[pgtype.UUID]cachedTypingTicket
+ wg sync.WaitGroup
+}
+
+func NewTypingNotifier(q typingStore, box *secretbox.Box, logger *slog.Logger) *TypingNotifier {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return &TypingNotifier{q: q, box: box, logger: logger, interval: typingKeepalive, runs: make(map[pgtype.UUID]*typingRun), tickets: make(map[pgtype.UUID]cachedTypingTicket)}
+}
+
+func (n *TypingNotifier) Start(ctx context.Context) {
+ n.mu.Lock()
+ n.ctx = ctx
+ n.mu.Unlock()
+}
+
+func (n *TypingNotifier) wait() {
+ // Shutdown cancels ctx first; synchronize with an ingest already adding work.
+ n.mu.Lock()
+ n.mu.Unlock()
+ n.wg.Wait()
+}
+
+func (n *TypingNotifier) OnIngested(_ context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID, _ pgtype.UUID) {
+ row, ok := inst.Platform.(db.ChannelInstallation)
+ if !ok || !sessionID.Valid {
+ return
+ }
+ creds, err := decodeCredentials(row.Config, n.box)
+ if err != nil || msg.Source.SenderID != creds.UserID {
+ return
+ }
+ n.mu.Lock()
+ defer n.mu.Unlock()
+ if n.ctx == nil || n.ctx.Err() != nil {
+ return
+ }
+ if run := n.runs[sessionID]; run != nil {
+ select {
+ case run.wake <- struct{}{}:
+ default:
+ }
+ return
+ }
+ ctx, cancel := context.WithCancel(n.ctx)
+ run := &typingRun{installation: inst.ID, cancel: cancel, wake: make(chan struct{}, 1), done: make(chan struct{})}
+ n.runs[sessionID] = run
+ n.wg.Add(1)
+ go n.keepalive(ctx, sessionID, row, creds, run)
+}
+
+func (n *TypingNotifier) OnSettled(ctx context.Context, sessionID pgtype.UUID, scope engine.TypingSettlement) {
+ if err := n.q.SettleWeixinTypingInputs(ctx, db.SettleWeixinTypingInputsParams{ThroughMessageID: scope.ThroughMessageID, ChatSessionID: sessionID, WorkspaceID: scope.WorkspaceID, InstallationID: scope.InstallationID, ContextRevision: pgtype.Int8{Int64: scope.ContextRevision, Valid: true}}); err != nil {
+ return
+ }
+ n.Wake(sessionID)
+}
+
+func (n *TypingNotifier) Wake(sessionID pgtype.UUID) {
+ n.mu.Lock()
+ defer n.mu.Unlock()
+ if run := n.runs[sessionID]; run != nil {
+ select {
+ case run.wake <- struct{}{}:
+ default:
+ }
+ }
+}
+
+func (n *TypingNotifier) StopInstallation(ctx context.Context, id pgtype.UUID) {
+ n.mu.Lock()
+ var done []<-chan struct{}
+ for _, run := range n.runs {
+ if run.installation == id {
+ run.cancel()
+ done = append(done, run.done)
+ }
+ }
+ delete(n.tickets, id)
+ n.mu.Unlock()
+ for _, ch := range done {
+ select {
+ case <-ch:
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+func (n *TypingNotifier) keepalive(ctx context.Context, sessionID pgtype.UUID, inst db.ChannelInstallation, creds credentials, run *typingRun) {
+ defer n.wg.Done()
+ defer close(run.done)
+ defer run.cancel()
+ defer func() {
+ n.mu.Lock()
+ if n.runs[sessionID] == run {
+ delete(n.runs, sessionID)
+ }
+ n.mu.Unlock()
+ }()
+ api := newAPI(creds.BaseURL, creds.Token, n.client)
+ ticket := ""
+ started := false
+ defer func() {
+ if ticket != "" {
+ clear, cancel := context.WithTimeout(context.WithoutCancel(ctx), typingCallTimeout)
+ defer cancel()
+ if err := api.sendTyping(clear, creds.UserID, ticket, 2); err == nil {
+ n.logger.Debug("weixin: typing stopped", "session_id", sessionID)
+ }
+ }
+ }()
+ ticker := time.NewTicker(n.interval)
+ defer ticker.Stop()
+ for {
+ call, cancel := context.WithTimeout(ctx, typingCallTimeout)
+ active, err := n.q.IsWeixinTypingActive(call, db.IsWeixinTypingActiveParams{InstallationID: inst.ID, ChatSessionID: sessionID, Config: inst.Config})
+ if err != nil || !active {
+ cancel()
+ return
+ }
+ if ticket == "" {
+ ticket = n.ticket(call, inst.ID, creds, api)
+ }
+ if ticket == "" {
+ cancel()
+ return
+ }
+ err = api.sendTyping(call, creds.UserID, ticket, 1)
+ cancel()
+ // Typing is cosmetic: a transient send failure must not end keepalives.
+ if err == nil && !started {
+ n.logger.DebugContext(ctx, "weixin: typing started", "session_id", sessionID)
+ started = true
+ }
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ case <-run.wake:
+ }
+ }
+}
+
+func (n *TypingNotifier) ticket(ctx context.Context, id pgtype.UUID, creds credentials, api *apiClient) string {
+ n.mu.Lock()
+ cached := n.tickets[id]
+ n.mu.Unlock()
+ if cached.user == creds.UserID && cached.token == creds.Token && time.Now().Before(cached.expires) {
+ return cached.ticket
+ }
+ state, err := n.q.GetWeixinAccountState(ctx, db.GetWeixinAccountStateParams{InstallationID: id, BotID: creds.AppID})
+ if err != nil {
+ return ""
+ }
+ contextToken, _ := n.box.Open(state.ContextTokenEncrypted)
+ ticket, err := api.typingTicket(ctx, creds.UserID, string(contextToken))
+ if err != nil {
+ return ""
+ }
+ n.mu.Lock()
+ // The ticket is cosmetic; a full cache simply leaves this result uncached.
+ if len(n.tickets) >= 1024 {
+ for key, entry := range n.tickets {
+ if time.Now().After(entry.expires) {
+ delete(n.tickets, key)
+ }
+ }
+ }
+ if len(n.tickets) < 1024 {
+ n.tickets[id] = cachedTypingTicket{user: creds.UserID, token: creds.Token, ticket: ticket, expires: time.Now().Add(typingTicketTTL)}
+ }
+ n.mu.Unlock()
+ return ticket
+}
diff --git a/server/internal/integrations/weixin/typing_test.go b/server/internal/integrations/weixin/typing_test.go
new file mode 100644
index 0000000000..849680615a
--- /dev/null
+++ b/server/internal/integrations/weixin/typing_test.go
@@ -0,0 +1,224 @@
+package weixin
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+)
+
+type memoryTypingStore struct {
+ active atomic.Bool
+ state db.WeixinAccountState
+}
+
+func (s *memoryTypingStore) IsWeixinTypingActive(context.Context, db.IsWeixinTypingActiveParams) (bool, error) {
+ return s.active.Load(), nil
+}
+func (s *memoryTypingStore) SettleWeixinTypingInputs(context.Context, db.SettleWeixinTypingInputsParams) error {
+ s.active.Store(false)
+ return nil
+}
+func (s *memoryTypingStore) GetWeixinAccountState(context.Context, db.GetWeixinAccountStateParams) (db.WeixinAccountState, error) {
+ return s.state, nil
+}
+
+func receiveTyping(t *testing.T, statuses <-chan int, want int) {
+ t.Helper()
+ select {
+ case got := <-statuses:
+ if got != want {
+ t.Fatalf("typing status=%d want=%d", got, want)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatalf("missing typing status %d", want)
+ }
+}
+
+func TestTypingKeepaliveCacheAndTerminalCleanup(t *testing.T) {
+ for _, end := range []string{"completed", "failed", "cancelled", "settled", "disconnect", "shutdown"} {
+ t.Run(end, func(t *testing.T) {
+ statuses := make(chan int, 32)
+ var configs atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body struct {
+ User string `json:"ilink_user_id"`
+ Ticket string `json:"typing_ticket"`
+ Status int `json:"status"`
+ Context string `json:"context_token"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Error(err)
+ }
+ if body.User != "owner" {
+ t.Error("typing sent to wrong user")
+ }
+ if strings.HasSuffix(r.URL.Path, "getconfig") {
+ configs.Add(1)
+ if body.Context != "reply-context" {
+ t.Error("missing reply context")
+ }
+ _, _ = w.Write([]byte(`{"ret":0,"typing_ticket":"ticket"}`))
+ } else {
+ if body.Ticket != "ticket" {
+ t.Error("missing typing ticket")
+ }
+ statuses <- body.Status
+ w.WriteHeader(http.StatusNoContent)
+ }
+ }))
+ defer server.Close()
+ box := testBox(t)
+ encrypted, _ := box.Seal([]byte("token"))
+ cfg, _ := json.Marshal(installConfig{AppID: "bot", UserID: "owner", BaseURL: DefaultBaseURL, TokenEncrypted: base64.StdEncoding.EncodeToString(encrypted)})
+ contextToken, _ := box.Seal([]byte("reply-context"))
+ store := &memoryTypingStore{state: db.WeixinAccountState{ContextTokenEncrypted: contextToken}}
+ store.active.Store(true)
+ n := NewTypingNotifier(store, box, nil)
+ n.client = providerClient(server)
+ n.interval = 10 * time.Millisecond
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ n.Start(ctx)
+ sessionID := dbid.NewV7()
+ inst := engine.ResolvedInstallation{ID: dbid.NewV7(), Platform: db.ChannelInstallation{Config: cfg}}
+ msg := channel.InboundMessage{Source: channel.Source{SenderID: "owner"}}
+ n.OnIngested(ctx, inst, msg, sessionID, dbid.NewV7())
+ receiveTyping(t, statuses, 1)
+ receiveTyping(t, statuses, 1)
+ switch end {
+ case "settled":
+ n.OnSettled(ctx, sessionID, engine.TypingSettlement{})
+ case "disconnect":
+ n.StopInstallation(ctx, inst.ID)
+ case "shutdown":
+ cancel()
+ default:
+ store.active.Store(false)
+ n.Wake(sessionID)
+ }
+ for {
+ select {
+ case status := <-statuses:
+ if status == 2 {
+ goto cleared
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("terminal outcome did not cancel typing")
+ }
+ }
+ cleared:
+ n.wg.Wait()
+ if end == "completed" {
+ store.active.Store(true)
+ n.OnIngested(ctx, inst, msg, sessionID, dbid.NewV7())
+ receiveTyping(t, statuses, 1)
+ store.active.Store(false)
+ n.Wake(sessionID)
+ n.wg.Wait()
+ if configs.Load() != 1 {
+ t.Fatalf("ticket not cached: requests=%d", configs.Load())
+ }
+ }
+ })
+ }
+}
+
+func TestTypingContinuesAfterTransientSendFailure(t *testing.T) {
+ for _, failAt := range []int32{1, 2} {
+ t.Run(fmt.Sprint(failAt), func(t *testing.T) {
+ statuses := make(chan int, 32)
+ var attempts atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.Path, "getconfig") {
+ _, _ = w.Write([]byte(`{"ret":0,"typing_ticket":"ticket"}`))
+ return
+ }
+ var body struct {
+ Status int `json:"status"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Error(err)
+ }
+ if body.Status == 1 && attempts.Add(1) == failAt {
+ statuses <- -1
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ statuses <- body.Status
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ defer server.Close()
+ box := testBox(t)
+ encrypted, _ := box.Seal([]byte("token"))
+ cfg, _ := json.Marshal(installConfig{AppID: "bot", UserID: "owner", BaseURL: DefaultBaseURL, TokenEncrypted: base64.StdEncoding.EncodeToString(encrypted)})
+ store := &memoryTypingStore{}
+ store.active.Store(true)
+ n := NewTypingNotifier(store, box, nil)
+ n.client = providerClient(server)
+ n.interval = 10 * time.Millisecond
+ ctx, cancel := context.WithCancel(context.Background())
+ defer func() { cancel(); n.wait() }()
+ n.Start(ctx)
+ n.OnIngested(ctx, engine.ResolvedInstallation{ID: dbid.NewV7(), Platform: db.ChannelInstallation{Config: cfg}}, channel.InboundMessage{Source: channel.Source{SenderID: "owner"}}, dbid.NewV7(), dbid.NewV7())
+ if failAt == 2 {
+ receiveTyping(t, statuses, 1)
+ }
+ receiveTyping(t, statuses, -1)
+ receiveTyping(t, statuses, 1)
+ cancel()
+ n.wait()
+ for {
+ select {
+ case status := <-statuses:
+ if status == 2 {
+ return
+ }
+ default:
+ t.Fatal("typing was not cleared after cancellation")
+ }
+ }
+ })
+ }
+}
+
+func TestTypingSkipsUnavailableTicketsAndAlreadySettledInput(t *testing.T) {
+ for _, body := range []string{`{"typing_ticket":"ticket"}`, `{"ret":1,"typing_ticket":"ticket"}`, `{"ret":0}`, `{"ret":0,"typing_ticket":"ticket"}`} {
+ t.Run(body, func(t *testing.T) {
+ var typingCalls atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.Path, "sendtyping") {
+ typingCalls.Add(1)
+ }
+ _, _ = w.Write([]byte(body))
+ }))
+ defer server.Close()
+ box := testBox(t)
+ encrypted, _ := box.Seal([]byte("token"))
+ cfg, _ := json.Marshal(installConfig{AppID: "bot", UserID: "owner", BaseURL: DefaultBaseURL, TokenEncrypted: base64.StdEncoding.EncodeToString(encrypted)})
+ store := &memoryTypingStore{}
+ store.active.Store(!strings.Contains(body, `"ret":0,"typing_ticket"`))
+ n := NewTypingNotifier(store, box, nil)
+ n.client = providerClient(server)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ n.Start(ctx)
+ n.OnIngested(ctx, engine.ResolvedInstallation{ID: dbid.NewV7(), Platform: db.ChannelInstallation{Config: cfg}}, channel.InboundMessage{Source: channel.Source{SenderID: "owner"}}, dbid.NewV7(), dbid.NewV7())
+ n.wg.Wait()
+ if typingCalls.Load() != 0 {
+ t.Fatal("unavailable ticket or settled input started typing")
+ }
+ })
+ }
+}
diff --git a/server/internal/migrations/weixin_origin_migration_test.go b/server/internal/migrations/weixin_origin_migration_test.go
new file mode 100644
index 0000000000..9d037bf743
--- /dev/null
+++ b/server/internal/migrations/weixin_origin_migration_test.go
@@ -0,0 +1,102 @@
+package migrations
+
+import (
+ "context"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+const weixinOriginMigrationTestSchema = "weixin_origin_migration_test"
+
+func TestWeixinOriginMigrationsUpDownAndCatalog(t *testing.T) {
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ t.Skip("integration test requires Postgres at DATABASE_URL")
+ }
+
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ t.Fatalf("connect to Postgres: %v", err)
+ }
+ defer pool.Close()
+
+ conn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire Postgres connection: %v", err)
+ }
+ defer conn.Release()
+
+ cleanup := func() {
+ _, _ = pool.Exec(context.Background(), "DROP SCHEMA IF EXISTS "+weixinOriginMigrationTestSchema+" CASCADE")
+ }
+ cleanup()
+ t.Cleanup(cleanup)
+ if _, err := conn.Exec(ctx, "CREATE SCHEMA "+weixinOriginMigrationTestSchema); err != nil {
+ t.Fatalf("create isolated migration schema: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `SELECT set_config('search_path', $1, false)`, weixinOriginMigrationTestSchema); err != nil {
+ t.Fatalf("set isolated migration search path: %v", err)
+ }
+
+ if _, err := conn.Exec(ctx, `
+ CREATE TABLE issue (
+ id UUID PRIMARY KEY,
+ origin_type TEXT NULL
+ );
+ ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check
+ CHECK (origin_type IN ('autopilot', 'quick_create', 'lark_chat', 'slack_chat', 'agent_create', 'dingtalk_chat', 'wecom_chat', 'telegram_chat'));
+ `); err != nil {
+ t.Fatalf("create pre-Weixin issue table: %v", err)
+ }
+
+ assertWeixinOriginRejected(t, ctx, conn.Conn(), "00000000-0000-4000-8000-000000000001")
+
+ applyMigrationFile(t, ctx, conn.Conn(), "667_issue_origin_weixin_chat.up.sql")
+ assertWeixinOriginConstraint(t, ctx, conn.Conn(), false, true)
+ if _, err := conn.Exec(ctx, `INSERT INTO issue (id, origin_type) VALUES ($1, 'weixin_chat')`, "00000000-0000-4000-8000-000000000002"); err != nil {
+ t.Fatalf("insert weixin_chat after widening constraint: %v", err)
+ }
+
+ applyMigrationFile(t, ctx, conn.Conn(), "668_issue_origin_weixin_chat_validate.up.sql")
+ assertWeixinOriginConstraint(t, ctx, conn.Conn(), true, true)
+
+ applyMigrationFile(t, ctx, conn.Conn(), "668_issue_origin_weixin_chat_validate.down.sql")
+ assertWeixinOriginConstraint(t, ctx, conn.Conn(), false, true)
+ if _, err := conn.Exec(ctx, `DELETE FROM issue WHERE origin_type = 'weixin_chat'`); err != nil {
+ t.Fatalf("remove Weixin row before narrowing rollback: %v", err)
+ }
+ applyMigrationFile(t, ctx, conn.Conn(), "667_issue_origin_weixin_chat.down.sql")
+ assertWeixinOriginConstraint(t, ctx, conn.Conn(), true, false)
+ assertWeixinOriginRejected(t, ctx, conn.Conn(), "00000000-0000-4000-8000-000000000003")
+}
+
+func assertWeixinOriginConstraint(t *testing.T, ctx context.Context, conn *pgx.Conn, wantValidated, wantWeixin bool) {
+ t.Helper()
+ var validated bool
+ var definition string
+ if err := conn.QueryRow(ctx, `
+ SELECT convalidated, pg_get_constraintdef(oid)
+ FROM pg_constraint
+ WHERE conrelid = 'issue'::regclass AND conname = 'issue_origin_type_check'
+ `).Scan(&validated, &definition); err != nil {
+ t.Fatalf("inspect issue origin constraint: %v", err)
+ }
+ if validated != wantValidated {
+ t.Fatalf("constraint validated = %t, want %t", validated, wantValidated)
+ }
+ if strings.Contains(definition, "weixin_chat") != wantWeixin {
+ t.Fatalf("constraint Weixin membership = %t, want %t: %s", strings.Contains(definition, "weixin_chat"), wantWeixin, definition)
+ }
+}
+
+func assertWeixinOriginRejected(t *testing.T, ctx context.Context, conn *pgx.Conn, id string) {
+ t.Helper()
+ if _, err := conn.Exec(ctx, `INSERT INTO issue (id, origin_type) VALUES ($1, 'weixin_chat')`, id); !isCheckViolation(err) {
+ t.Fatalf("insert weixin_chat under pre-Weixin constraint: got %v, want check violation", err)
+ }
+}
diff --git a/server/migrations/665_weixin_state.down.sql b/server/migrations/665_weixin_state.down.sql
new file mode 100644
index 0000000000..b466c20b67
--- /dev/null
+++ b/server/migrations/665_weixin_state.down.sql
@@ -0,0 +1,2 @@
+DROP TABLE IF EXISTS weixin_account_state;
+DROP TABLE IF EXISTS weixin_login_session;
diff --git a/server/migrations/665_weixin_state.up.sql b/server/migrations/665_weixin_state.up.sql
new file mode 100644
index 0000000000..c6653275c6
--- /dev/null
+++ b/server/migrations/665_weixin_state.up.sql
@@ -0,0 +1,23 @@
+CREATE TABLE weixin_login_session (
+ id uuid NOT NULL,
+ workspace_id uuid NOT NULL,
+ agent_id uuid NOT NULL,
+ initiator_user_id uuid NOT NULL,
+ state_encrypted bytea NOT NULL,
+ status text NOT NULL DEFAULT 'wait',
+ installation_id uuid,
+ lease_token uuid,
+ lease_expires_at timestamptz,
+ expires_at timestamptz NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE TABLE weixin_account_state (
+ installation_id uuid NOT NULL,
+ bot_id text NOT NULL,
+ user_id text NOT NULL,
+ get_updates_buf text NOT NULL DEFAULT '',
+ context_token_encrypted bytea NOT NULL DEFAULT '',
+ context_time_ms bigint NOT NULL DEFAULT 0,
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/666_weixin_login_expiry_idx.down.sql b/server/migrations/666_weixin_login_expiry_idx.down.sql
new file mode 100644
index 0000000000..7a72782828
--- /dev/null
+++ b/server/migrations/666_weixin_login_expiry_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS weixin_login_expiry_idx;
diff --git a/server/migrations/666_weixin_login_expiry_idx.up.sql b/server/migrations/666_weixin_login_expiry_idx.up.sql
new file mode 100644
index 0000000000..d9e137103f
--- /dev/null
+++ b/server/migrations/666_weixin_login_expiry_idx.up.sql
@@ -0,0 +1 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS weixin_login_expiry_idx ON weixin_login_session (expires_at);
diff --git a/server/migrations/667_issue_origin_weixin_chat.down.sql b/server/migrations/667_issue_origin_weixin_chat.down.sql
new file mode 100644
index 0000000000..239274f01d
--- /dev/null
+++ b/server/migrations/667_issue_origin_weixin_chat.down.sql
@@ -0,0 +1,8 @@
+-- Restore the validated pre-WeChat constraint. This intentionally fails
+-- closed while weixin_chat rows remain, because a rollback must not leave a
+-- trusted constraint that existing rows violate.
+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_origin_type_check;
+ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check
+ CHECK (origin_type IN ('autopilot', 'quick_create', 'lark_chat', 'slack_chat', 'agent_create', 'dingtalk_chat', 'wecom_chat', 'telegram_chat'))
+ NOT VALID;
+ALTER TABLE issue VALIDATE CONSTRAINT issue_origin_type_check;
diff --git a/server/migrations/667_issue_origin_weixin_chat.up.sql b/server/migrations/667_issue_origin_weixin_chat.up.sql
new file mode 100644
index 0000000000..48dc41aa40
--- /dev/null
+++ b/server/migrations/667_issue_origin_weixin_chat.up.sql
@@ -0,0 +1,11 @@
+-- Extend issue.origin_type for issues created by the WeChat `/issue`
+-- command. origin_id stores the chat_session id, matching the existing Lark,
+-- Slack, DingTalk, and WeCom channel origins.
+--
+-- This only widens the allowed set. Recreate the CHECK as NOT VALID so the
+-- ACCESS EXCLUSIVE lock is held briefly; migration 668 performs the table scan
+-- under SHARE UPDATE EXCLUSIVE without blocking normal reads and writes.
+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_origin_type_check;
+ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check
+ CHECK (origin_type IN ('autopilot', 'quick_create', 'lark_chat', 'slack_chat', 'agent_create', 'dingtalk_chat', 'wecom_chat', 'telegram_chat', 'weixin_chat'))
+ NOT VALID;
diff --git a/server/migrations/668_issue_origin_weixin_chat_validate.down.sql b/server/migrations/668_issue_origin_weixin_chat_validate.down.sql
new file mode 100644
index 0000000000..c10922fd02
--- /dev/null
+++ b/server/migrations/668_issue_origin_weixin_chat_validate.down.sql
@@ -0,0 +1,6 @@
+-- PostgreSQL cannot mark a validated constraint NOT VALID. Recreate the state
+-- immediately after migration 667: enforcing new writes but not yet validated.
+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_origin_type_check;
+ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check
+ CHECK (origin_type IN ('autopilot', 'quick_create', 'lark_chat', 'slack_chat', 'agent_create', 'dingtalk_chat', 'wecom_chat', 'telegram_chat', 'weixin_chat'))
+ NOT VALID;
diff --git a/server/migrations/668_issue_origin_weixin_chat_validate.up.sql b/server/migrations/668_issue_origin_weixin_chat_validate.up.sql
new file mode 100644
index 0000000000..b4a340a927
--- /dev/null
+++ b/server/migrations/668_issue_origin_weixin_chat_validate.up.sql
@@ -0,0 +1,3 @@
+-- Validate the widened CHECK separately from migration 667 so the validation
+-- scan does not inherit migration 667's ACCESS EXCLUSIVE lock.
+ALTER TABLE issue VALIDATE CONSTRAINT issue_origin_type_check;
diff --git a/server/migrations/669_weixin_login_session_unique_index.down.sql b/server/migrations/669_weixin_login_session_unique_index.down.sql
new file mode 100644
index 0000000000..dfaf97c448
--- /dev/null
+++ b/server/migrations/669_weixin_login_session_unique_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS weixin_login_session_pkey;
diff --git a/server/migrations/669_weixin_login_session_unique_index.up.sql b/server/migrations/669_weixin_login_session_unique_index.up.sql
new file mode 100644
index 0000000000..9407e9e2c6
--- /dev/null
+++ b/server/migrations/669_weixin_login_session_unique_index.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY weixin_login_session_pkey ON weixin_login_session (id);
diff --git a/server/migrations/670_weixin_login_session_primary_key.down.sql b/server/migrations/670_weixin_login_session_primary_key.down.sql
new file mode 100644
index 0000000000..b4657fe5e0
--- /dev/null
+++ b/server/migrations/670_weixin_login_session_primary_key.down.sql
@@ -0,0 +1 @@
+ALTER TABLE weixin_login_session DROP CONSTRAINT IF EXISTS weixin_login_session_pkey;
diff --git a/server/migrations/670_weixin_login_session_primary_key.up.sql b/server/migrations/670_weixin_login_session_primary_key.up.sql
new file mode 100644
index 0000000000..31d824524e
--- /dev/null
+++ b/server/migrations/670_weixin_login_session_primary_key.up.sql
@@ -0,0 +1 @@
+ALTER TABLE weixin_login_session ADD CONSTRAINT weixin_login_session_pkey PRIMARY KEY USING INDEX weixin_login_session_pkey;
diff --git a/server/migrations/671_weixin_account_state_unique_index.down.sql b/server/migrations/671_weixin_account_state_unique_index.down.sql
new file mode 100644
index 0000000000..175eb82cc5
--- /dev/null
+++ b/server/migrations/671_weixin_account_state_unique_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS weixin_account_state_pkey;
diff --git a/server/migrations/671_weixin_account_state_unique_index.up.sql b/server/migrations/671_weixin_account_state_unique_index.up.sql
new file mode 100644
index 0000000000..1a323c731f
--- /dev/null
+++ b/server/migrations/671_weixin_account_state_unique_index.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY weixin_account_state_pkey ON weixin_account_state (installation_id);
diff --git a/server/migrations/672_weixin_account_state_primary_key.down.sql b/server/migrations/672_weixin_account_state_primary_key.down.sql
new file mode 100644
index 0000000000..d73fcf6781
--- /dev/null
+++ b/server/migrations/672_weixin_account_state_primary_key.down.sql
@@ -0,0 +1 @@
+ALTER TABLE weixin_account_state DROP CONSTRAINT IF EXISTS weixin_account_state_pkey;
diff --git a/server/migrations/672_weixin_account_state_primary_key.up.sql b/server/migrations/672_weixin_account_state_primary_key.up.sql
new file mode 100644
index 0000000000..a918d3e00e
--- /dev/null
+++ b/server/migrations/672_weixin_account_state_primary_key.up.sql
@@ -0,0 +1 @@
+ALTER TABLE weixin_account_state ADD CONSTRAINT weixin_account_state_pkey PRIMARY KEY USING INDEX weixin_account_state_pkey;
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index b38c154f82..c5bab6d5ee 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -2017,6 +2017,30 @@ type WecomInstallSession struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
+type WeixinAccountState struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ BotID string `json:"bot_id"`
+ UserID string `json:"user_id"`
+ GetUpdatesBuf string `json:"get_updates_buf"`
+ ContextTokenEncrypted []byte `json:"context_token_encrypted"`
+ ContextTimeMs int64 `json:"context_time_ms"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
+type WeixinLoginSession struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ StateEncrypted []byte `json:"state_encrypted"`
+ Status string `json:"status"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ LeaseToken pgtype.UUID `json:"lease_token"`
+ LeaseExpiresAt pgtype.Timestamptz `json:"lease_expires_at"`
+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
type Workspace struct {
ID pgtype.UUID `json:"id"`
Name string `json:"name"`
diff --git a/server/pkg/db/generated/weixin.sql.go b/server/pkg/db/generated/weixin.sql.go
new file mode 100644
index 0000000000..d91a5e3785
--- /dev/null
+++ b/server/pkg/db/generated/weixin.sql.go
@@ -0,0 +1,457 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: weixin.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const cancelPreviousWeixinLogins = `-- name: CancelPreviousWeixinLogins :exec
+UPDATE weixin_login_session SET status = 'cancelled', state_encrypted = '', lease_token = NULL, lease_expires_at = NULL
+WHERE workspace_id = $1 AND agent_id = $2 AND initiator_user_id = $3
+ AND (status IN ('wait', 'scaned', 'scaned_but_redirect') OR strpos(status, 'need_verifycode') > 0)
+`
+
+type CancelPreviousWeixinLoginsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+}
+
+func (q *Queries) CancelPreviousWeixinLogins(ctx context.Context, arg CancelPreviousWeixinLoginsParams) error {
+ _, err := q.db.Exec(ctx, cancelPreviousWeixinLogins, arg.WorkspaceID, arg.AgentID, arg.InitiatorUserID)
+ return err
+}
+
+const cancelWeixinLoginSession = `-- name: CancelWeixinLoginSession :execrows
+UPDATE weixin_login_session SET status = 'cancelled', state_encrypted = '', lease_token = NULL, lease_expires_at = NULL
+WHERE id = $1 AND workspace_id = $2 AND initiator_user_id = $3
+ AND (status IN ('wait', 'scaned', 'scaned_but_redirect') OR strpos(status, 'need_verifycode') > 0)
+`
+
+type CancelWeixinLoginSessionParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+}
+
+func (q *Queries) CancelWeixinLoginSession(ctx context.Context, arg CancelWeixinLoginSessionParams) (int64, error) {
+ result, err := q.db.Exec(ctx, cancelWeixinLoginSession, arg.ID, arg.WorkspaceID, arg.InitiatorUserID)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const claimWeixinLoginSession = `-- name: ClaimWeixinLoginSession :one
+UPDATE weixin_login_session
+SET lease_token = $1, lease_expires_at = now() + interval '50 seconds'
+WHERE id = $2 AND workspace_id = $3
+ AND initiator_user_id = $4 AND expires_at > now()
+ AND (status IN ('wait', 'scaned', 'scaned_but_redirect') OR strpos(status, 'need_verifycode') > 0)
+ AND (lease_expires_at IS NULL OR lease_expires_at < now())
+RETURNING id, workspace_id, agent_id, initiator_user_id, state_encrypted, status, installation_id, lease_token, lease_expires_at, expires_at, created_at
+`
+
+type ClaimWeixinLoginSessionParams struct {
+ LeaseToken pgtype.UUID `json:"lease_token"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+}
+
+func (q *Queries) ClaimWeixinLoginSession(ctx context.Context, arg ClaimWeixinLoginSessionParams) (WeixinLoginSession, error) {
+ row := q.db.QueryRow(ctx, claimWeixinLoginSession,
+ arg.LeaseToken,
+ arg.ID,
+ arg.WorkspaceID,
+ arg.InitiatorUserID,
+ )
+ var i WeixinLoginSession
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.InitiatorUserID,
+ &i.StateEncrypted,
+ &i.Status,
+ &i.InstallationID,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.ExpiresAt,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
+const createWeixinLoginSession = `-- name: CreateWeixinLoginSession :one
+INSERT INTO weixin_login_session (id, workspace_id, agent_id, initiator_user_id, state_encrypted, expires_at)
+VALUES ($1, $2, $3, $4, $5, now() + interval '5 minutes') RETURNING id, workspace_id, agent_id, initiator_user_id, state_encrypted, status, installation_id, lease_token, lease_expires_at, expires_at, created_at
+`
+
+type CreateWeixinLoginSessionParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ StateEncrypted []byte `json:"state_encrypted"`
+}
+
+func (q *Queries) CreateWeixinLoginSession(ctx context.Context, arg CreateWeixinLoginSessionParams) (WeixinLoginSession, error) {
+ row := q.db.QueryRow(ctx, createWeixinLoginSession,
+ arg.ID,
+ arg.WorkspaceID,
+ arg.AgentID,
+ arg.InitiatorUserID,
+ arg.StateEncrypted,
+ )
+ var i WeixinLoginSession
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.InitiatorUserID,
+ &i.StateEncrypted,
+ &i.Status,
+ &i.InstallationID,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.ExpiresAt,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
+const deleteWeixinAccountState = `-- name: DeleteWeixinAccountState :exec
+DELETE FROM weixin_account_state WHERE installation_id = $1
+`
+
+func (q *Queries) DeleteWeixinAccountState(ctx context.Context, installationID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWeixinAccountState, installationID)
+ return err
+}
+
+const expireWeixinInstallation = `-- name: ExpireWeixinInstallation :execrows
+UPDATE channel_installation SET status = 'revoked',
+ config = jsonb_set(config, '{authorization_expired}', 'true'), updated_at = now()
+WHERE id = $1 AND channel_type = 'weixin' AND status = 'active' AND config = $2
+`
+
+type ExpireWeixinInstallationParams struct {
+ ID pgtype.UUID `json:"id"`
+ Config []byte `json:"config"`
+}
+
+func (q *Queries) ExpireWeixinInstallation(ctx context.Context, arg ExpireWeixinInstallationParams) (int64, error) {
+ result, err := q.db.Exec(ctx, expireWeixinInstallation, arg.ID, arg.Config)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const getWeixinAccountState = `-- name: GetWeixinAccountState :one
+SELECT installation_id, bot_id, user_id, get_updates_buf, context_token_encrypted, context_time_ms, updated_at FROM weixin_account_state WHERE installation_id = $1 AND bot_id = $2
+`
+
+type GetWeixinAccountStateParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ BotID string `json:"bot_id"`
+}
+
+func (q *Queries) GetWeixinAccountState(ctx context.Context, arg GetWeixinAccountStateParams) (WeixinAccountState, error) {
+ row := q.db.QueryRow(ctx, getWeixinAccountState, arg.InstallationID, arg.BotID)
+ var i WeixinAccountState
+ err := row.Scan(
+ &i.InstallationID,
+ &i.BotID,
+ &i.UserID,
+ &i.GetUpdatesBuf,
+ &i.ContextTokenEncrypted,
+ &i.ContextTimeMs,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const getWeixinInstallationForAgent = `-- name: GetWeixinInstallationForAgent :one
+SELECT id, workspace_id, agent_id, channel_type, config, status, ws_lease_token, ws_lease_expires_at, installer_user_id, installed_at, created_at, updated_at FROM channel_installation
+WHERE workspace_id = $1 AND agent_id = $2 AND channel_type = 'weixin' FOR UPDATE
+`
+
+type GetWeixinInstallationForAgentParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+}
+
+func (q *Queries) GetWeixinInstallationForAgent(ctx context.Context, arg GetWeixinInstallationForAgentParams) (ChannelInstallation, error) {
+ row := q.db.QueryRow(ctx, getWeixinInstallationForAgent, arg.WorkspaceID, arg.AgentID)
+ var i ChannelInstallation
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.ChannelType,
+ &i.Config,
+ &i.Status,
+ &i.WsLeaseToken,
+ &i.WsLeaseExpiresAt,
+ &i.InstallerUserID,
+ &i.InstalledAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const getWeixinLoginSession = `-- name: GetWeixinLoginSession :one
+SELECT id, workspace_id, agent_id, initiator_user_id, state_encrypted, status, installation_id, lease_token, lease_expires_at, expires_at, created_at FROM weixin_login_session
+WHERE id = $1 AND workspace_id = $2 AND initiator_user_id = $3
+`
+
+type GetWeixinLoginSessionParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+}
+
+func (q *Queries) GetWeixinLoginSession(ctx context.Context, arg GetWeixinLoginSessionParams) (WeixinLoginSession, error) {
+ row := q.db.QueryRow(ctx, getWeixinLoginSession, arg.ID, arg.WorkspaceID, arg.InitiatorUserID)
+ var i WeixinLoginSession
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.InitiatorUserID,
+ &i.StateEncrypted,
+ &i.Status,
+ &i.InstallationID,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.ExpiresAt,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
+const isWeixinTypingActive = `-- name: IsWeixinTypingActive :one
+SELECT EXISTS (
+ SELECT 1 FROM chat_session s
+ JOIN channel_installation i ON i.id = $1 AND i.workspace_id = s.workspace_id
+ JOIN channel_chat_session_binding b ON b.chat_session_id = s.id AND b.installation_id = i.id
+ JOIN chat_message m ON m.chat_session_id = s.id
+ WHERE s.id = $2 AND s.status = 'active'
+ AND i.channel_type = 'weixin' AND i.status = 'active' AND i.config = $3
+ AND b.channel_type = 'weixin' AND b.retired_at IS NULL
+ AND m.channel_ingested AND m.role = 'user' AND NOT m.channel_typing_settled
+ AND COALESCE(m.channel_context_revision, 1) = b.context_revision
+ AND ((m.task_id IS NULL AND m.created_at > now() - interval '2 minutes') OR EXISTS (
+ SELECT 1 FROM agent_task_queue t WHERE t.chat_session_id = s.id
+ AND (t.id = m.task_id OR t.chat_input_task_id = m.task_id)
+ AND t.status IN ('queued','dispatched','running','waiting_local_directory','deferred')
+ ))
+) AS active
+`
+
+type IsWeixinTypingActiveParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ Config []byte `json:"config"`
+}
+
+func (q *Queries) IsWeixinTypingActive(ctx context.Context, arg IsWeixinTypingActiveParams) (bool, error) {
+ row := q.db.QueryRow(ctx, isWeixinTypingActive, arg.InstallationID, arg.ChatSessionID, arg.Config)
+ var active bool
+ err := row.Scan(&active)
+ return active, err
+}
+
+const lockWeixinLoginSession = `-- name: LockWeixinLoginSession :one
+SELECT id, workspace_id, agent_id, initiator_user_id, state_encrypted, status, installation_id, lease_token, lease_expires_at, expires_at, created_at FROM weixin_login_session
+WHERE id = $1 AND lease_token = $2 AND expires_at > now()
+ AND (status IN ('wait', 'scaned', 'scaned_but_redirect') OR strpos(status, 'need_verifycode') > 0)
+FOR UPDATE
+`
+
+type LockWeixinLoginSessionParams struct {
+ ID pgtype.UUID `json:"id"`
+ LeaseToken pgtype.UUID `json:"lease_token"`
+}
+
+func (q *Queries) LockWeixinLoginSession(ctx context.Context, arg LockWeixinLoginSessionParams) (WeixinLoginSession, error) {
+ row := q.db.QueryRow(ctx, lockWeixinLoginSession, arg.ID, arg.LeaseToken)
+ var i WeixinLoginSession
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.InitiatorUserID,
+ &i.StateEncrypted,
+ &i.Status,
+ &i.InstallationID,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.ExpiresAt,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
+const purgeWeixinState = `-- name: PurgeWeixinState :exec
+WITH expired AS (
+ DELETE FROM weixin_login_session WHERE expires_at < now() - interval '1 hour'
+)
+DELETE FROM weixin_account_state state
+WHERE NOT EXISTS (SELECT 1 FROM channel_installation ci WHERE ci.id = state.installation_id AND ci.channel_type = 'weixin')
+`
+
+func (q *Queries) PurgeWeixinState(ctx context.Context) error {
+ _, err := q.db.Exec(ctx, purgeWeixinState)
+ return err
+}
+
+const releaseWeixinLoginSession = `-- name: ReleaseWeixinLoginSession :exec
+UPDATE weixin_login_session SET lease_token = NULL, lease_expires_at = NULL
+WHERE id = $1 AND lease_token = $2
+`
+
+type ReleaseWeixinLoginSessionParams struct {
+ ID pgtype.UUID `json:"id"`
+ LeaseToken pgtype.UUID `json:"lease_token"`
+}
+
+func (q *Queries) ReleaseWeixinLoginSession(ctx context.Context, arg ReleaseWeixinLoginSessionParams) error {
+ _, err := q.db.Exec(ctx, releaseWeixinLoginSession, arg.ID, arg.LeaseToken)
+ return err
+}
+
+const resetWeixinAccountState = `-- name: ResetWeixinAccountState :exec
+INSERT INTO weixin_account_state (installation_id, bot_id, user_id)
+VALUES ($1, $2, $3)
+ON CONFLICT (installation_id) DO UPDATE SET bot_id = EXCLUDED.bot_id, user_id = EXCLUDED.user_id,
+ get_updates_buf = '', context_token_encrypted = '', context_time_ms = 0, updated_at = now()
+`
+
+type ResetWeixinAccountStateParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ BotID string `json:"bot_id"`
+ UserID string `json:"user_id"`
+}
+
+func (q *Queries) ResetWeixinAccountState(ctx context.Context, arg ResetWeixinAccountStateParams) error {
+ _, err := q.db.Exec(ctx, resetWeixinAccountState, arg.InstallationID, arg.BotID, arg.UserID)
+ return err
+}
+
+const saveWeixinContext = `-- name: SaveWeixinContext :execrows
+UPDATE weixin_account_state SET context_token_encrypted = $4, context_time_ms = $5, updated_at = now()
+WHERE installation_id = $1 AND bot_id = $2 AND user_id = $3 AND context_time_ms <= $5
+`
+
+type SaveWeixinContextParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ BotID string `json:"bot_id"`
+ UserID string `json:"user_id"`
+ ContextTokenEncrypted []byte `json:"context_token_encrypted"`
+ ContextTimeMs int64 `json:"context_time_ms"`
+}
+
+func (q *Queries) SaveWeixinContext(ctx context.Context, arg SaveWeixinContextParams) (int64, error) {
+ result, err := q.db.Exec(ctx, saveWeixinContext,
+ arg.InstallationID,
+ arg.BotID,
+ arg.UserID,
+ arg.ContextTokenEncrypted,
+ arg.ContextTimeMs,
+ )
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const saveWeixinCursor = `-- name: SaveWeixinCursor :execrows
+UPDATE weixin_account_state SET get_updates_buf = $3, updated_at = now()
+WHERE installation_id = $1 AND bot_id = $2
+`
+
+type SaveWeixinCursorParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ BotID string `json:"bot_id"`
+ GetUpdatesBuf string `json:"get_updates_buf"`
+}
+
+func (q *Queries) SaveWeixinCursor(ctx context.Context, arg SaveWeixinCursorParams) (int64, error) {
+ result, err := q.db.Exec(ctx, saveWeixinCursor, arg.InstallationID, arg.BotID, arg.GetUpdatesBuf)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const settleWeixinTypingInputs = `-- name: SettleWeixinTypingInputs :exec
+UPDATE chat_message m SET channel_typing_settled = true
+FROM chat_message cutoff, chat_session s, channel_installation i
+WHERE cutoff.id = $1 AND cutoff.chat_session_id = s.id
+ AND s.id = $2 AND s.workspace_id = $3
+ AND i.id = $4 AND i.workspace_id = s.workspace_id AND i.channel_type = 'weixin'
+ AND EXISTS (SELECT 1 FROM channel_chat_session_binding b WHERE b.chat_session_id = s.id
+ AND b.installation_id = i.id AND b.channel_type = 'weixin')
+ AND m.chat_session_id = s.id AND m.channel_ingested AND m.role = 'user' AND m.task_id IS NULL
+ AND COALESCE(m.channel_context_revision, 1) = $5
+ AND (m.created_at, m.id) <= (cutoff.created_at, cutoff.id)
+`
+
+type SettleWeixinTypingInputsParams struct {
+ ThroughMessageID pgtype.UUID `json:"through_message_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ContextRevision pgtype.Int8 `json:"context_revision"`
+}
+
+func (q *Queries) SettleWeixinTypingInputs(ctx context.Context, arg SettleWeixinTypingInputsParams) error {
+ _, err := q.db.Exec(ctx, settleWeixinTypingInputs,
+ arg.ThroughMessageID,
+ arg.ChatSessionID,
+ arg.WorkspaceID,
+ arg.InstallationID,
+ arg.ContextRevision,
+ )
+ return err
+}
+
+const updateWeixinLoginSession = `-- name: UpdateWeixinLoginSession :execrows
+UPDATE weixin_login_session
+SET status = $1, state_encrypted = $2,
+ installation_id = $3, lease_token = NULL, lease_expires_at = NULL
+WHERE id = $4 AND lease_token = $5
+ AND (status IN ('wait', 'scaned', 'scaned_but_redirect') OR strpos(status, 'need_verifycode') > 0)
+`
+
+type UpdateWeixinLoginSessionParams struct {
+ Status string `json:"status"`
+ StateEncrypted []byte `json:"state_encrypted"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ID pgtype.UUID `json:"id"`
+ LeaseToken pgtype.UUID `json:"lease_token"`
+}
+
+func (q *Queries) UpdateWeixinLoginSession(ctx context.Context, arg UpdateWeixinLoginSessionParams) (int64, error) {
+ result, err := q.db.Exec(ctx, updateWeixinLoginSession,
+ arg.Status,
+ arg.StateEncrypted,
+ arg.InstallationID,
+ arg.ID,
+ arg.LeaseToken,
+ )
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index f2b096a141..2f796ffb04 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -492,6 +492,13 @@ deleted_channel_binding_tokens AS (
deleted_wecom_install_sessions AS (
DELETE FROM wecom_install_session WHERE workspace_id = $1
),
+deleted_weixin_login_sessions AS (
+ DELETE FROM weixin_login_session WHERE workspace_id = $1
+),
+deleted_weixin_account_states AS (
+ DELETE FROM weixin_account_state
+ WHERE installation_id IN (SELECT id FROM ws_channel_installations)
+),
deleted_workspace_composio_connections AS (
DELETE FROM workspace_composio_connection WHERE workspace_id = $1
),
diff --git a/server/pkg/db/queries/weixin.sql b/server/pkg/db/queries/weixin.sql
new file mode 100644
index 0000000000..677dd3a40f
--- /dev/null
+++ b/server/pkg/db/queries/weixin.sql
@@ -0,0 +1,109 @@
+-- name: CreateWeixinLoginSession :one
+INSERT INTO weixin_login_session (id, workspace_id, agent_id, initiator_user_id, state_encrypted, expires_at)
+VALUES ($1, $2, $3, $4, $5, now() + interval '5 minutes') RETURNING *;
+
+-- name: GetWeixinLoginSession :one
+SELECT * FROM weixin_login_session
+WHERE id = $1 AND workspace_id = $2 AND initiator_user_id = $3;
+
+-- name: LockWeixinLoginSession :one
+SELECT * FROM weixin_login_session
+WHERE id = $1 AND lease_token = $2 AND expires_at > now()
+ AND (status IN ('wait', 'scaned', 'scaned_but_redirect') OR strpos(status, 'need_verifycode') > 0)
+FOR UPDATE;
+
+-- name: ClaimWeixinLoginSession :one
+UPDATE weixin_login_session
+SET lease_token = sqlc.arg(lease_token), lease_expires_at = now() + interval '50 seconds'
+WHERE id = sqlc.arg(id) AND workspace_id = sqlc.arg(workspace_id)
+ AND initiator_user_id = sqlc.arg(initiator_user_id) AND expires_at > now()
+ AND (status IN ('wait', 'scaned', 'scaned_but_redirect') OR strpos(status, 'need_verifycode') > 0)
+ AND (lease_expires_at IS NULL OR lease_expires_at < now())
+RETURNING *;
+
+-- name: UpdateWeixinLoginSession :execrows
+UPDATE weixin_login_session
+SET status = sqlc.arg(status), state_encrypted = sqlc.arg(state_encrypted),
+ installation_id = sqlc.narg(installation_id), lease_token = NULL, lease_expires_at = NULL
+WHERE id = sqlc.arg(id) AND lease_token = sqlc.arg(lease_token)
+ AND (status IN ('wait', 'scaned', 'scaned_but_redirect') OR strpos(status, 'need_verifycode') > 0);
+
+-- name: ReleaseWeixinLoginSession :exec
+UPDATE weixin_login_session SET lease_token = NULL, lease_expires_at = NULL
+WHERE id = $1 AND lease_token = $2;
+
+-- name: CancelWeixinLoginSession :execrows
+UPDATE weixin_login_session SET status = 'cancelled', state_encrypted = '', lease_token = NULL, lease_expires_at = NULL
+WHERE id = $1 AND workspace_id = $2 AND initiator_user_id = $3
+ AND (status IN ('wait', 'scaned', 'scaned_but_redirect') OR strpos(status, 'need_verifycode') > 0);
+
+-- name: CancelPreviousWeixinLogins :exec
+UPDATE weixin_login_session SET status = 'cancelled', state_encrypted = '', lease_token = NULL, lease_expires_at = NULL
+WHERE workspace_id = $1 AND agent_id = $2 AND initiator_user_id = $3
+ AND (status IN ('wait', 'scaned', 'scaned_but_redirect') OR strpos(status, 'need_verifycode') > 0);
+
+-- name: PurgeWeixinState :exec
+WITH expired AS (
+ DELETE FROM weixin_login_session WHERE expires_at < now() - interval '1 hour'
+)
+DELETE FROM weixin_account_state state
+WHERE NOT EXISTS (SELECT 1 FROM channel_installation ci WHERE ci.id = state.installation_id AND ci.channel_type = 'weixin');
+
+-- name: GetWeixinInstallationForAgent :one
+SELECT * FROM channel_installation
+WHERE workspace_id = $1 AND agent_id = $2 AND channel_type = 'weixin' FOR UPDATE;
+
+-- name: ResetWeixinAccountState :exec
+INSERT INTO weixin_account_state (installation_id, bot_id, user_id)
+VALUES ($1, $2, $3)
+ON CONFLICT (installation_id) DO UPDATE SET bot_id = EXCLUDED.bot_id, user_id = EXCLUDED.user_id,
+ get_updates_buf = '', context_token_encrypted = '', context_time_ms = 0, updated_at = now();
+
+-- name: GetWeixinAccountState :one
+SELECT * FROM weixin_account_state WHERE installation_id = $1 AND bot_id = $2;
+
+-- name: SaveWeixinContext :execrows
+UPDATE weixin_account_state SET context_token_encrypted = $4, context_time_ms = $5, updated_at = now()
+WHERE installation_id = $1 AND bot_id = $2 AND user_id = $3 AND context_time_ms <= $5;
+
+-- name: SaveWeixinCursor :execrows
+UPDATE weixin_account_state SET get_updates_buf = $3, updated_at = now()
+WHERE installation_id = $1 AND bot_id = $2;
+
+-- name: DeleteWeixinAccountState :exec
+DELETE FROM weixin_account_state WHERE installation_id = $1;
+
+-- name: ExpireWeixinInstallation :execrows
+UPDATE channel_installation SET status = 'revoked',
+ config = jsonb_set(config, '{authorization_expired}', 'true'), updated_at = now()
+WHERE id = $1 AND channel_type = 'weixin' AND status = 'active' AND config = $2;
+
+-- name: IsWeixinTypingActive :one
+SELECT EXISTS (
+ SELECT 1 FROM chat_session s
+ JOIN channel_installation i ON i.id = @installation_id AND i.workspace_id = s.workspace_id
+ JOIN channel_chat_session_binding b ON b.chat_session_id = s.id AND b.installation_id = i.id
+ JOIN chat_message m ON m.chat_session_id = s.id
+ WHERE s.id = @chat_session_id AND s.status = 'active'
+ AND i.channel_type = 'weixin' AND i.status = 'active' AND i.config = @config
+ AND b.channel_type = 'weixin' AND b.retired_at IS NULL
+ AND m.channel_ingested AND m.role = 'user' AND NOT m.channel_typing_settled
+ AND COALESCE(m.channel_context_revision, 1) = b.context_revision
+ AND ((m.task_id IS NULL AND m.created_at > now() - interval '2 minutes') OR EXISTS (
+ SELECT 1 FROM agent_task_queue t WHERE t.chat_session_id = s.id
+ AND (t.id = m.task_id OR t.chat_input_task_id = m.task_id)
+ AND t.status IN ('queued','dispatched','running','waiting_local_directory','deferred')
+ ))
+) AS active;
+
+-- name: SettleWeixinTypingInputs :exec
+UPDATE chat_message m SET channel_typing_settled = true
+FROM chat_message cutoff, chat_session s, channel_installation i
+WHERE cutoff.id = @through_message_id AND cutoff.chat_session_id = s.id
+ AND s.id = @chat_session_id AND s.workspace_id = @workspace_id
+ AND i.id = @installation_id AND i.workspace_id = s.workspace_id AND i.channel_type = 'weixin'
+ AND EXISTS (SELECT 1 FROM channel_chat_session_binding b WHERE b.chat_session_id = s.id
+ AND b.installation_id = i.id AND b.channel_type = 'weixin')
+ AND m.chat_session_id = s.id AND m.channel_ingested AND m.role = 'user' AND m.task_id IS NULL
+ AND COALESCE(m.channel_context_revision, 1) = @context_revision
+ AND (m.created_at, m.id) <= (cutoff.created_at, cutoff.id);
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index 6c5a21d434..9779dc6b73 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -502,6 +502,13 @@ deleted_channel_binding_tokens AS (
deleted_wecom_install_sessions AS (
DELETE FROM wecom_install_session WHERE workspace_id = $1
),
+deleted_weixin_login_sessions AS (
+ DELETE FROM weixin_login_session WHERE workspace_id = $1
+),
+deleted_weixin_account_states AS (
+ DELETE FROM weixin_account_state
+ WHERE installation_id IN (SELECT id FROM ws_channel_installations)
+),
deleted_workspace_composio_connections AS (
DELETE FROM workspace_composio_connection WHERE workspace_id = $1
),
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index 0154804eac..50f34a735e 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -250,6 +250,8 @@ const (
// Telegram installation lifecycle. Same contract as the Slack pair:
// front-ends invalidate the Telegram installations query on either.
+ EventWeixinInstallationCreated = "weixin_installation:created"
+ EventWeixinInstallationRevoked = "weixin_installation:revoked"
EventTelegramInstallationCreated = "telegram_installation:created"
EventTelegramInstallationRevoked = "telegram_installation:revoked"
)