Skip to content

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

Go

MUL-8549 fix(weixin): show the QR directly in the connect dialog (#10795)

Multica Eve861c0ca357db
diff --git a/apps/docs/content/docs/weixin-bot-integration.fr.mdx b/apps/docs/content/docs/weixin-bot-integration.fr.mdx
index f92dcfd8da..37ef5d4960 100644
--- a/apps/docs/content/docs/weixin-bot-integration.fr.mdx
+++ b/apps/docs/content/docs/weixin-bot-integration.fr.mdx
@@ -7,8 +7,8 @@ Multica se connecte au service iLink Bot de WeChat avec le protocole implément
## Se connecter
-1. Connectez-vous en tant que propriétaire ou administrateur de l'espace de travail. Ouvrez un agent, choisissez **Ajouter un canal de messagerie** dans ses canaux de messagerie, puis **WeChat** et **Connecter WeChat**.
-2. Scannez le QR code avec **votre propre compte WeChat** et confirmez sur votre téléphone. Si WeChat demande un code de vérification, saisissez les chiffres affichés sur le téléphone dans la boîte de dialogue.
+1. Connectez-vous en tant que propriétaire ou administrateur de l'espace de travail. Ouvrez un agent, choisissez **Ajouter un canal de messagerie** dans ses canaux de messagerie, puis **WeChat**. Le QR code s'affiche aussitôt.
+2. Scannez le QR code avec **votre propre compte WeChat** et confirmez sur votre téléphone. Si WeChat demande un code de vérification, saisissez les chiffres affichés sur le téléphone dans la boîte de dialogue. Une fois la connexion établie, la boîte de dialogue se ferme et WeChat apparaît dans les canaux de messagerie de l'agent.
3. Envoyez un nouveau message privé au bot dans WeChat. L'agent a besoin d'un environnement d'exécution en ligne pour travailler.
Le compte qui scanne le code est associé à l'utilisateur Multica qui a ouvert cette boîte de dialogue. Ses messages utilisent les permissions de cet utilisateur dans l'espace de travail. Ne partagez pas le QR code et ne demandez pas à quelqu'un d'autre de le scanner. Les autres comptes WeChat et les messages de groupe ne sont pas acceptés.
diff --git a/apps/docs/content/docs/weixin-bot-integration.ja.mdx b/apps/docs/content/docs/weixin-bot-integration.ja.mdx
index d1ee70b92e..f8876b0239 100644
--- a/apps/docs/content/docs/weixin-bot-integration.ja.mdx
+++ b/apps/docs/content/docs/weixin-bot-integration.ja.mdx
@@ -7,8 +7,8 @@ Multica は Tencent の [OpenClaw Weixin プラグイン](https://github.com/Ten
## 接続する
-1. ワークスペースの owner または admin としてログインします。エージェントを開き、メッセージチャネルの **メッセージチャネルを追加** から **WeChat** を選び、**WeChat に接続** をクリックします。
-2. **自分の WeChat アカウント** で QR コードをスキャンし、スマートフォンで承認します。WeChat が確認コードを求めた場合は、スマートフォンに表示された数字をダイアログに入力します。
+1. ワークスペースの owner または admin としてログインします。エージェントを開き、メッセージチャネルの **メッセージチャネルを追加** から **WeChat** を選びます。QR コードがすぐに表示されます。
+2. **自分の WeChat アカウント** で QR コードをスキャンし、スマートフォンで承認します。WeChat が確認コードを求めた場合は、スマートフォンに表示された数字をダイアログに入力します。接続が完了するとダイアログが閉じ、エージェントのメッセージチャネルに WeChat が表示されます。
3. WeChat で Bot に新しい DM を送ります。エージェントが作業を実行するには、オンラインのランタイムが必要です。
スキャンしたアカウントは、このダイアログを開いた Multica ユーザーに紐づきます。メッセージはそのユーザーのワークスペース権限で実行されます。QR コードを共有したり、他の人にスキャンを頼んだりしないでください。他の WeChat アカウントやグループからのメッセージは受け付けません。
diff --git a/apps/docs/content/docs/weixin-bot-integration.ko.mdx b/apps/docs/content/docs/weixin-bot-integration.ko.mdx
index 4a41a74eb9..67bd2f7707 100644
--- a/apps/docs/content/docs/weixin-bot-integration.ko.mdx
+++ b/apps/docs/content/docs/weixin-bot-integration.ko.mdx
@@ -7,8 +7,8 @@ Multica는 Tencent의 [OpenClaw Weixin 플러그인](https://github.com/Tencent/
## 연결하기
-1. 워크스페이스 owner 또는 admin으로 로그인합니다. 에이전트를 열고 메시지 채널에서 **메시지 채널 추가** 를 선택한 뒤 **WeChat**, **WeChat 연결** 을 선택합니다.
-2. **본인의 WeChat 계정** 으로 QR 코드를 스캔하고 휴대폰에서 승인합니다. WeChat이 인증 코드를 요구하면 휴대폰에 표시된 숫자를 대화 상자에 입력합니다.
+1. 워크스페이스 owner 또는 admin으로 로그인합니다. 에이전트를 열고 메시지 채널에서 **메시지 채널 추가** 를 선택한 뒤 **WeChat** 을 선택합니다. QR 코드가 바로 표시됩니다.
+2. **본인의 WeChat 계정** 으로 QR 코드를 스캔하고 휴대폰에서 승인합니다. WeChat이 인증 코드를 요구하면 휴대폰에 표시된 숫자를 대화 상자에 입력합니다. 연결되면 대화 상자가 닫히고 에이전트의 메시지 채널에 WeChat이 표시됩니다.
3. WeChat에서 Bot에 새 DM을 보냅니다. 에이전트가 작업을 실행하려면 온라인 런타임이 필요합니다.
스캔한 계정은 이 대화 상자를 연 Multica 사용자에게 연결됩니다. 메시지는 그 사용자의 워크스페이스 권한으로 실행됩니다. QR 코드를 공유하거나 다른 사람에게 스캔을 부탁하지 마세요. 다른 WeChat 계정이나 그룹의 메시지는 받지 않습니다.
diff --git a/apps/docs/content/docs/weixin-bot-integration.mdx b/apps/docs/content/docs/weixin-bot-integration.mdx
index 361a9aa4ed..c5700f2469 100644
--- a/apps/docs/content/docs/weixin-bot-integration.mdx
+++ b/apps/docs/content/docs/weixin-bot-integration.mdx
@@ -7,8 +7,8 @@ Multica connects to WeChat's iLink Bot service using the protocol implemented by
## 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.
+1. Sign in as a workspace owner or admin. Open an agent, choose **Add messaging channel** under **Messaging**, then select **WeChat**. The QR code appears right away.
+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. Once connected, the dialog closes and WeChat appears under the agent's **Messaging**.
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.
diff --git a/apps/docs/content/docs/weixin-bot-integration.zh-Hant.mdx b/apps/docs/content/docs/weixin-bot-integration.zh-Hant.mdx
index 16300512f6..4c12229a02 100644
--- a/apps/docs/content/docs/weixin-bot-integration.zh-Hant.mdx
+++ b/apps/docs/content/docs/weixin-bot-integration.zh-Hant.mdx
@@ -7,8 +7,8 @@ Multica 參考騰訊 [OpenClaw Weixin 外掛](https://github.com/Tencent/opencla
## 連線
-1. 以工作區 owner 或 admin 身分登入,開啟 AI 代理,在 "訊息渠道" 中選擇 "新增訊息管道",選擇微信後點選 "連接微信"。
-2. 用**你自己的微信帳號**掃碼,並在手機上確認。微信要求驗證碼時,在彈窗中輸入手機顯示的數字。
+1. 以工作區 owner 或 admin 身分登入,開啟 AI 代理,在 "訊息渠道" 中選擇 "新增訊息管道",選擇微信後會直接顯示 QR 碼。
+2. 用**你自己的微信帳號**掃碼,並在手機上確認。微信要求驗證碼時,在彈窗中輸入手機顯示的數字。連接成功後彈窗會自動關閉,微信會出現在 AI 代理的 "訊息渠道" 中。
3. 在微信中向機器人傳送一條新私訊。AI 代理需要線上的執行環境才能執行任務。
掃碼的微信帳號會繫結到發起連線的 Multica 使用者,訊息按該使用者的工作區權限執行。請勿分享 QR 碼或讓他人代掃。其他微信帳號和群聊訊息不會被接收。
diff --git a/apps/docs/content/docs/weixin-bot-integration.zh.mdx b/apps/docs/content/docs/weixin-bot-integration.zh.mdx
index fdcf7a64cd..23eb57f17c 100644
--- a/apps/docs/content/docs/weixin-bot-integration.zh.mdx
+++ b/apps/docs/content/docs/weixin-bot-integration.zh.mdx
@@ -7,8 +7,8 @@ Multica 参考腾讯 [OpenClaw Weixin 插件](https://github.com/Tencent/opencla
## 连接
-1. 以工作区所有者或管理员身份登录,打开智能体,在「消息渠道」中选择「添加消息渠道」,选择微信后点击「连接微信」。
-2. 用**你自己的微信账号**扫码,并在手机上确认。微信要求验证码时,在弹窗中输入手机显示的数字。
+1. 以工作区所有者或管理员身份登录,打开智能体,在「消息渠道」中选择「添加消息渠道」,选择微信后会直接显示二维码。
+2. 用**你自己的微信账号**扫码,并在手机上确认。微信要求验证码时,在弹窗中输入手机显示的数字。连接成功后弹窗自动关闭,微信会出现在智能体的「消息渠道」中。
3. 在微信中向机器人发送一条新私聊消息。智能体需要在线的运行环境才能执行任务。
扫码的微信账号会绑定到发起连接的 Multica 用户,消息按该用户的工作区权限执行。请勿分享二维码或让他人代扫。其他微信账号和群聊消息不会被接收。
diff --git a/apps/docs/public/images/docs/weixin/qr-login.png b/apps/docs/public/images/docs/weixin/qr-login.png
index 80a42a1b0a..fa83ccccdb 100644
Binary files a/apps/docs/public/images/docs/weixin/qr-login.png and b/apps/docs/public/images/docs/weixin/qr-login.png differ
diff --git a/e2e/weixin.spec.ts b/e2e/weixin.spec.ts
index 396b76427d..dd3be5ac71 100644
--- a/e2e/weixin.spec.ts
+++ b/e2e/weixin.spec.ts
@@ -113,32 +113,33 @@ test("WeChat QR verification, connection listing, and disconnect", async ({
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();
+ // Choosing WeChat shows the QR straight away, with the guide below it.
+ await expect(
+ connectDialog.getByRole("img", { name: "WeChat connection QR code" }),
+ ).toBeVisible();
+ await expect(
+ connectDialog.getByRole("button", { name: "Setup guide" }),
+ ).toBeVisible();
await page.screenshot({
path: testInfo.outputPath("weixin-qr.png"),
fullPage: true,
});
- await expect(dialog.getByLabel("Verification code")).toBeVisible();
+ await expect(connectDialog.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 connectDialog.getByLabel("Verification code").fill("001234");
+ await connectDialog
+ .getByRole("button", { name: "Verify", exact: true })
+ .click();
+ // A confirmed login closes the dialog and the agent lists the channel.
+ await expect(connectDialog).toBeHidden();
await expect(page.getByRole("button", { name: "Manage WeChat" })).toBeVisible();
+ await page.screenshot({
+ path: testInfo.outputPath("weixin-agent-connected.png"),
+ fullPage: true,
+ });
await page.goto(
`/${workspace.slug}/settings?tab=channels&integration=weixin`,
{ waitUntil: "domcontentloaded" },
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 00b8c88f27..020a7f9138 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -1721,20 +1721,10 @@
"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.",
+ "privacy_hint": "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.",
diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.json
index 7d91483086..ff7efd2204 100644
--- a/packages/views/locales/es/settings.json
+++ b/packages/views/locales/es/settings.json
@@ -1721,20 +1721,10 @@
"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.",
+ "privacy_hint": "Los 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.",
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index 3c00f03d49..c3b6f77956 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -1721,20 +1721,10 @@
"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.",
+ "privacy_hint": "Les 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.",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 1e92661713..b0ac3d1c60 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -1705,20 +1705,10 @@
"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 コードを共有しないでください。",
+ "privacy_hint": "メッセージはこのワークスペースであなたの権限で実行されます。QR コードを共有しないでください。",
"qr_label": "WeChat 接続用 QR コード",
"scan_hint": "WeChat で読み取り、スマートフォンで確認してください。",
"scanned": "読み取り済み。WeChat で接続を確認してください。",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 242633d859..71ff975df1 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -1705,20 +1705,10 @@
"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 코드를 공유하지 마세요.",
+ "privacy_hint": "메시지는 이 워크스페이스에서 본인의 권한으로 실행됩니다. QR 코드를 공유하지 마세요.",
"qr_label": "WeChat 연결 QR 코드",
"scan_hint": "WeChat으로 스캔한 후 휴대폰에서 확인하세요.",
"scanned": "스캔되었습니다. WeChat에서 연결을 확인하세요.",
diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.json
index 0ba953f51f..8b09aba969 100644
--- a/packages/views/locales/ru/settings.json
+++ b/packages/views/locales/ru/settings.json
@@ -1752,20 +1752,10 @@
"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-кодом.",
+ "privacy_hint": "Сообщения будут обрабатываться от вашего имени в этом рабочем пространстве. Не делитесь QR-кодом.",
"qr_label": "QR-код для подключения WeChat",
"scan_hint": "Отсканируйте QR-код в WeChat и подтвердите подключение на телефоне.",
"scanned": "QR-код отсканирован. Подтвердите подключение в WeChat.",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index f49198f3d5..39b4a1f5fb 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -1705,20 +1705,10 @@
"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": "请用你自己的微信扫码,消息将以你的身份在此工作区执行。请勿分享二维码。",
+ "privacy_hint": "消息将以你的身份在此工作区执行,请勿分享二维码。",
"qr_label": "微信连接二维码",
"scan_hint": "使用微信扫码,并在手机上确认。",
"scanned": "已扫码,请在微信中确认连接。",
diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.json
index 65fcf68edc..4da9730e12 100644
--- a/packages/views/locales/zh-Hant/settings.json
+++ b/packages/views/locales/zh-Hant/settings.json
@@ -1705,20 +1705,10 @@
"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 碼。",
+ "privacy_hint": "訊息將以你的身分在此工作區執行,請勿分享 QR 碼。",
"qr_label": "微信連線 QR 碼",
"scan_hint": "使用微信掃碼,並在手機上確認。",
"scanned": "已掃碼,請在微信中確認連線。",
diff --git a/packages/views/settings/components/channel-connect-dialog.tsx b/packages/views/settings/components/channel-connect-dialog.tsx
index 4fc5982712..9a2e7fed17 100644
--- a/packages/views/settings/components/channel-connect-dialog.tsx
+++ b/packages/views/settings/components/channel-connect-dialog.tsx
@@ -27,7 +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";
+import { WeixinChannelAuthorization } from "./weixin-channel-authorization";
export function ChannelConnectDialog({
agents,
@@ -106,6 +106,10 @@ function ChannelConnectSteps({
setChannel(id);
setAuthorizing(true);
};
+ const openGuide = () =>
+ openExternal(
+ `https://multica.ai/docs${docsLocalePrefix(i18n.language)}/${channel}-bot-integration`,
+ );
const scanWecom =
channel === "wecom" &&
queries.wecom.data?.scan_install_supported === true &&
@@ -225,17 +229,11 @@ function ChannelConnectSteps({
</>
) : (
<>
- <Button
- variant="link"
- className="w-fit p-0"
- onClick={() =>
- openExternal(
- `https://multica.ai/docs${docsLocalePrefix(i18n.language)}/${channel === "lark" ? "lark" : channel}-bot-integration`,
- )
- }
- >
- {t(($) => $.channels.setup_guide)}
- </Button>
+ {channel === "weixin" ? null : (
+ <Button variant="link" className="w-fit p-0" onClick={openGuide}>
+ {t(($) => $.channels.setup_guide)}
+ </Button>
+ )}
{channel === "wecom" && queries.wecom.data?.scan_install_supported ? (
<div className="space-y-1.5">
<Label htmlFor="channel-method">
@@ -270,7 +268,13 @@ function ChannelConnectSteps({
onClose={onClose}
/>
) : channel === "weixin" ? (
- <WeixinAgentBindButton agentId={agent.id} agentName={agent.name} onBusyChange={onBusyChange} />
+ // The QR is the whole step, so its guide moves below it.
+ <WeixinChannelAuthorization
+ wsId={wsId}
+ agentId={agent.id}
+ onOpenGuide={openGuide}
+ onClose={onClose}
+ />
) : scanWecom ? (
<WecomChannelAuthorization
wsId={wsId}
diff --git a/packages/views/settings/components/messaging-channels.test.tsx b/packages/views/settings/components/messaging-channels.test.tsx
index 61fa461de9..c9fcfd313c 100644
--- a/packages/views/settings/components/messaging-channels.test.tsx
+++ b/packages/views/settings/components/messaging-channels.test.tsx
@@ -1,3 +1,4 @@
+import { useState } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, screen, waitFor, within } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
@@ -396,7 +397,7 @@ const platformName = {
} as const;
describe("shared connection dialog", () => {
- it("starts and cancels a WeChat QR login for the selected agent", async () => {
+ it("shows the WeChat QR as soon as WeChat is chosen and cancels it on close", async () => {
const login = {
id: "login-1",
status: "wait",
@@ -406,25 +407,37 @@ describe("shared connection dialog", () => {
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()}
- />,
- );
+ function Harness() {
+ const [open, setOpen] = useState(true);
+ return (
+ <ChannelConnectDialog
+ agents={[agent]}
+ initialAgent={agent}
+ initialChannel="weixin"
+ open={open}
+ onOpenChange={setOpen}
+ />
+ );
+ }
+ show(<Harness />);
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();
+ const qr = await screen.findByTitle("WeChat connection QR code");
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());
+ expect(screen.queryByRole("button", { name: "Connect WeChat" })).toBeNull();
+ const guide = screen.getByRole("button", { name: "Setup guide" });
+ expect(
+ qr.compareDocumentPosition(guide) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ fireEvent.click(guide);
+ expect(state.open).toHaveBeenCalledWith(
+ "https://multica.ai/docs/weixin-bot-integration",
+ );
+ // The footer's Close; the header's icon button shares the name.
+ fireEvent.click(screen.getAllByRole("button", { name: "Close" })[0]!);
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ expect(api.cancelWeixinLogin).toHaveBeenCalledWith("ws-1", login.id);
});
it("offers only Feishu for new connections while international Lark is disabled", async () => {
diff --git a/packages/views/settings/components/weixin-channel-authorization.test.tsx b/packages/views/settings/components/weixin-channel-authorization.test.tsx
new file mode 100644
index 0000000000..6c7f3cd4c2
--- /dev/null
+++ b/packages/views/settings/components/weixin-channel-authorization.test.tsx
@@ -0,0 +1,194 @@
+// @vitest-environment jsdom
+import { StrictMode } from "react";
+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(() => ({
+ begin: vi.fn(),
+ poll: vi.fn(),
+ cancel: vi.fn(),
+ toast: vi.fn(),
+}));
+vi.mock("@multica/core/api", () => ({
+ api: {
+ beginWeixinLogin: mocks.begin,
+ pollWeixinLogin: mocks.poll,
+ cancelWeixinLogin: mocks.cancel,
+ },
+ clientErrorMessage: () => undefined,
+}));
+vi.mock("sonner", () => ({ toast: { success: mocks.toast } }));
+
+import { WeixinChannelAuthorization } from "./weixin-channel-authorization";
+
+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(),
+};
+
+function renderAuthorization(onClose = vi.fn(), onOpenGuide = vi.fn()) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ const invalidate = vi.spyOn(client, "invalidateQueries");
+ const result = render(
+ <StrictMode>
+ <QueryClientProvider client={client}>
+ <I18nProvider
+ locale="en"
+ resources={{ en: { common: enCommon, settings: enSettings } }}
+ >
+ <WeixinChannelAuthorization
+ wsId="workspace-1"
+ agentId="agent-1"
+ onOpenGuide={onOpenGuide}
+ onClose={onClose}
+ />
+ </I18nProvider>
+ </QueryClientProvider>
+ </StrictMode>,
+ );
+ return { ...result, onClose, onOpenGuide, invalidate };
+}
+
+describe("WeChat QR connection", () => {
+ beforeEach(() => {
+ cleanup();
+ vi.resetAllMocks();
+ mocks.begin.mockResolvedValue(login);
+ mocks.poll.mockResolvedValue(login);
+ mocks.cancel.mockResolvedValue(undefined);
+ });
+
+ it("shows the QR on open with the guide below it, requesting one login", async () => {
+ const user = userEvent.setup();
+ const { onOpenGuide } = renderAuthorization();
+ const qr = await screen.findByTitle("WeChat connection QR code");
+ const guide = screen.getByRole("button", { name: "Setup guide" });
+ expect(
+ qr.compareDocumentPosition(guide) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ await user.click(guide);
+ expect(onOpenGuide).toHaveBeenCalledTimes(1);
+ expect(mocks.begin).toHaveBeenCalledTimes(1);
+ expect(mocks.begin).toHaveBeenCalledWith("workspace-1", "agent-1");
+ expect(
+ screen.queryByRole("button", { name: "Connect WeChat" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it.each(["need_verifycode", "confirmed_but_need_verifycode"])(
+ "submits the phone code for %s, then announces the connection and closes",
+ async (status) => {
+ const user = userEvent.setup();
+ mocks.poll
+ .mockResolvedValueOnce({ ...login, status })
+ .mockResolvedValue({
+ id: login.id,
+ status: "confirmed",
+ installation_id: "bot-1",
+ expires_at: login.expires_at,
+ });
+ const { onClose, invalidate } = renderAuthorization();
+ 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",
+ ),
+ );
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+ expect(mocks.toast).toHaveBeenCalledTimes(1);
+ expect(mocks.toast).toHaveBeenCalledWith(
+ "Connected. Send a new message to the bot in WeChat to start.",
+ );
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: ["weixin", "workspace-1", "installations"],
+ });
+ expect(mocks.cancel).not.toHaveBeenCalled();
+ },
+ );
+
+ it("cancels the pending login when the dialog closes", async () => {
+ const { unmount } = renderAuthorization();
+ await screen.findByTitle("WeChat connection QR code");
+ unmount();
+ expect(mocks.cancel).toHaveBeenCalledWith("workspace-1", "login-1");
+ });
+
+ it("cancels a login that arrives after the dialog closed", async () => {
+ let resolve!: (value: typeof login) => void;
+ mocks.begin.mockReturnValue(
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ const { unmount } = renderAuthorization();
+ expect(await screen.findByRole("status")).toHaveTextContent("Connecting…");
+ unmount();
+ resolve(login);
+ await waitFor(() =>
+ 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,
+ });
+ renderAuthorization();
+ 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("names the agent owning a conflicting WeChat connection", async () => {
+ mocks.poll.mockRejectedValue(
+ new ApiError("already connected", 409, "Conflict", {
+ code: "weixin_already_connected",
+ agent_id: "other-agent",
+ agent_name: "Research Assistant",
+ }),
+ );
+ renderAuthorization();
+ 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 () => {
+ mocks.poll.mockRejectedValue(
+ new ApiError("already connected", 409, "Conflict", {
+ code: "weixin_already_connected",
+ }),
+ );
+ renderAuthorization();
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "This WeChat account is connected elsewhere. Disconnect the existing connection first.",
+ );
+ });
+});
diff --git a/packages/views/settings/components/weixin-channel-authorization.tsx b/packages/views/settings/components/weixin-channel-authorization.tsx
new file mode 100644
index 0000000000..a22d25cfaf
--- /dev/null
+++ b/packages/views/settings/components/weixin-channel-authorization.tsx
@@ -0,0 +1,295 @@
+"use client";
+
+// The QR half of connecting WeChat, rendered inside the shared connection
+// dialog like the Lark and WeCom scan flows: the login starts on mount, the QR
+// shows immediately, and a confirmed login closes the dialog.
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { QRCode } from "react-qr-code";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { api, clientErrorMessage } from "@multica/core/api";
+import type { WeixinLogin } from "@multica/core/types";
+import {
+ weixinKeys,
+ isWeixinLoginPending,
+ isWeixinVerificationRequired,
+ weixinConflict,
+} from "@multica/core/weixin";
+import { Button } from "@multica/ui/components/ui/button";
+import { DialogFooter } from "@multica/ui/components/ui/dialog";
+import { Input } from "@multica/ui/components/ui/input";
+import { Label } from "@multica/ui/components/ui/label";
+import { BookOpen } from "@multica/ui/icons";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../../i18n";
+
+const pollsProvider = (status?: string) =>
+ isWeixinLoginPending(status) && !isWeixinVerificationRequired(status);
+
+export function WeixinChannelAuthorization({
+ wsId,
+ agentId,
+ onOpenGuide,
+ onClose,
+}: {
+ wsId: string;
+ agentId: string;
+ onOpenGuide: () => void;
+ onClose: () => void;
+}) {
+ const { t } = useT("settings");
+ const qc = useQueryClient();
+ const [loginId, setLoginId] = useState("");
+ const [code, setCode] = useState("");
+ const [beginning, setBeginning] = useState(false);
+ const [beginError, setBeginError] = useState<unknown>(null);
+ // The login that closing this dialog must cancel, and whether a begin that
+ // resolves later still has a dialog to show its QR in.
+ const pendingLogin = useRef("");
+ const mounted = useRef(false);
+ const announced = useRef("");
+ const key = weixinKeys.login(wsId, loginId);
+
+ // Plain async state rather than useMutation: this starts from a mount
+ // effect, and StrictMode's replay detaches a mutation observer from a
+ // mutation started there, leaving it pending forever.
+ const startLogin = useCallback(async () => {
+ setBeginning(true);
+ setBeginError(null);
+ try {
+ const login = await api.beginWeixinLogin(wsId, agentId);
+ if (!login.id || login.status === "error")
+ throw new Error(t(($) => $.weixin.action_failed));
+ // A QR requested just before the dialog closed is cancelled instead of
+ // left pending.
+ if (!mounted.current) {
+ void api.cancelWeixinLogin(wsId, login.id).catch(() => undefined);
+ return;
+ }
+ qc.setQueryData(weixinKeys.login(wsId, login.id), login);
+ pendingLogin.current = login.id;
+ setLoginId(login.id);
+ setCode("");
+ } catch (reason) {
+ if (mounted.current) setBeginError(reason);
+ } finally {
+ if (mounted.current) setBeginning(false);
+ }
+ }, [agentId, qc, t, wsId]);
+
+ // Closing the dialog unmounts this step; cancel the login it left pending.
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ const id = pendingLogin.current;
+ pendingLogin.current = "";
+ if (id) void api.cancelWeixinLogin(wsId, id).catch(() => undefined);
+ };
+ }, [wsId]);
+ // Runs after the effect above. StrictMode replays effects on the same
+ // instance; the guard keeps that replay from requesting a second QR.
+ const started = useRef(false);
+ useEffect(() => {
+ if (started.current) return;
+ started.current = true;
+ void startLogin();
+ }, [startLogin]);
+
+ const poll = useQuery({
+ queryKey: key,
+ queryFn: ({ signal }) => api.pollWeixinLogin(wsId, loginId, "", signal),
+ enabled: (query) =>
+ !!loginId &&
+ pollsProvider((query.state.data as WeixinLogin | undefined)?.status),
+ refetchInterval: (query) =>
+ !weixinConflict(query.state.error) &&
+ pollsProvider((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 || !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);
+ }, [login, refetchLogin]);
+
+ const confirmedId = login?.status === "confirmed" ? login.id : "";
+ useEffect(() => {
+ if (!confirmedId || announced.current === confirmedId) return;
+ announced.current = confirmedId;
+ pendingLogin.current = "";
+ void qc.invalidateQueries({ queryKey: weixinKeys.installations(wsId) });
+ toast.success(t(($) => $.weixin.success));
+ }, [confirmedId, qc, t, wsId]);
+ // Close after a beat so the confirmed state is visible. Kept apart from the
+ // effect above: onClose changes identity on every parent render.
+ useEffect(() => {
+ if (!confirmedId) return;
+ const timer = setTimeout(onClose, 800);
+ return () => clearTimeout(timer);
+ }, [confirmedId, onClose]);
+
+ 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 = !!beginError || poll.isError || verify.isError;
+ const error = beginError ?? 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));
+
+ const showPlate =
+ !conflict && (beginning || (pending && !!login?.qr_code_url));
+ // Once scanned, the code is spent: fade it so the next step stands out.
+ const scanned = pending && status !== "wait";
+ return (
+ <>
+ <div className="flex flex-col items-center gap-4 py-2 text-center">
+ {showPlate && (
+ // White plate in every theme: a QR needs light quiet zones. The
+ // placeholder keeps its size so the dialog does not jump.
+ <div
+ className={cn(
+ "flex size-52 items-center justify-center rounded-lg border",
+ beginning ? "bg-muted/50" : "bg-white",
+ )}
+ >
+ {beginning ? (
+ <p role="status" className="text-caption text-muted-foreground">
+ {t(($) => $.weixin.loading)}
+ </p>
+ ) : (
+ login?.qr_code_url && (
+ <QRCode
+ value={login.qr_code_url}
+ size={176}
+ title={t(($) => $.weixin.qr_label)}
+ className={cn("transition-opacity", scanned && "opacity-30")}
+ />
+ )
+ )}
+ </div>
+ )}
+ {login && !beginning && !conflict && (
+ <div className="max-w-md space-y-1">
+ <p role="status" className="text-body font-medium text-balance">
+ {statusText}
+ </p>
+ {status === "wait" && (
+ <p className="text-caption text-balance text-muted-foreground">
+ {t(($) => $.weixin.privacy_hint)}
+ </p>
+ )}
+ </div>
+ )}
+ {!beginning && isWeixinVerificationRequired(status) && (
+ <form
+ className="w-full max-w-xs space-y-1.5 text-left"
+ onSubmit={(event) => {
+ event.preventDefault();
+ verify.mutate();
+ }}
+ >
+ <Label htmlFor={`weixin-code-${agentId}`}>
+ {t(($) => $.weixin.verify_label)}
+ </Label>
+ <div className="flex gap-2">
+ <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>
+ </div>
+ </form>
+ )}
+ {failed && (
+ <p
+ role="alert"
+ className="max-w-sm text-caption text-balance text-destructive"
+ >
+ {errorText}
+ </p>
+ )}
+ </div>
+ <DialogFooter className="items-center sm:justify-between">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-muted-foreground"
+ onClick={onOpenGuide}
+ >
+ <BookOpen />
+ {t(($) => $.channels.setup_guide)}
+ </Button>
+ <div className="flex flex-col-reverse gap-2 sm:flex-row">
+ <Button variant="outline" onClick={onClose}>
+ {t(($) => $.weixin.close)}
+ </Button>
+ {!beginning &&
+ status !== "confirmed" &&
+ (!pending || !!beginError) && (
+ <Button onClick={() => void startLogin()}>
+ {t(($) => $.weixin.refresh)}
+ </Button>
+ )}
+ {poll.isError && pending && (
+ <Button onClick={() => void refetchLogin()}>
+ {t(($) => $.weixin.retry)}
+ </Button>
+ )}
+ </div>
+ </DialogFooter>
+ </>
+ );
+}
diff --git a/packages/views/settings/components/weixin-tab.test.tsx b/packages/views/settings/components/weixin-tab.test.tsx
deleted file mode 100644
index 2b485e9666..0000000000
--- a/packages/views/settings/components/weixin-tab.test.tsx
+++ /dev/null
@@ -1,227 +0,0 @@
-// @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
deleted file mode 100644
index 2264593f1e..0000000000
--- a/packages/views/settings/components/weixin-tab.tsx
+++ /dev/null
@@ -1,391 +0,0 @@
-"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>
- </>
- );
-}