Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9474 fix(weixin): let agent owners manage WeChat connections (#10802)
Pogačar4ad6d830364e
diff --git a/apps/docs/content/docs/channels.fr.mdx b/apps/docs/content/docs/channels.fr.mdxindex 4a4a0e2221..ae29454bda 100644--- a/apps/docs/content/docs/channels.fr.mdx+++ b/apps/docs/content/docs/channels.fr.mdx@@ -87,7 +87,7 @@ L'association de compte confirme uniquement l'identité de l'expéditeur. Les au## Gérer les connexions-Les propriétaires et administrateurs de l'espace de travail peuvent connecter ou déconnecter des bots ; pour les bots Feishu/Lark, la connexion et la déconnexion sont aussi ouvertes au propriétaire de l'agent. Les membres ordinaires peuvent consulter les intégrations connectées et utiliser les agents auxquels ils ont accès.+Les propriétaires et administrateurs de l'espace de travail peuvent connecter ou déconnecter des bots ; pour Feishu/Lark, DingTalk et WeChat, la connexion et la déconnexion sont aussi ouvertes au propriétaire de l'agent. Les membres ordinaires peuvent consulter les intégrations connectées et utiliser les agents auxquels ils ont accès.Après la déconnexion, le bot ne reçoit plus de nouveaux messages. Les conversations Multica et les historiques d'exécution existants sont conservés.diff --git a/apps/docs/content/docs/channels.ja.mdx b/apps/docs/content/docs/channels.ja.mdxindex d5cf65a9d4..adf69f8a36 100644--- a/apps/docs/content/docs/channels.ja.mdx+++ b/apps/docs/content/docs/channels.ja.mdx@@ -87,7 +87,7 @@ Multica がエージェントを実行するのは、アカウント連携が完## 接続を管理する-ワークスペースの owner と admin は Bot を接続または切断できます。Feishu/Lark Bot の場合は、エージェントの所有者も接続と切断ができます。通常のメンバーは接続済みの連携を確認し、自分に実行権限があるエージェントを利用できます。+ワークスペースの owner と admin は Bot を接続または切断できます。Feishu/Lark、DingTalk、WeChat の場合は、エージェントの所有者も接続と切断ができます。通常のメンバーは接続済みの連携を確認し、自分に実行権限があるエージェントを利用できます。切断すると、Bot は新しいメッセージを受信しなくなります。既存の Multica の会話と実行記録は保持されます。diff --git a/apps/docs/content/docs/channels.ko.mdx b/apps/docs/content/docs/channels.ko.mdxindex 23cb3523dc..ebfb7dd316 100644--- a/apps/docs/content/docs/channels.ko.mdx+++ b/apps/docs/content/docs/channels.ko.mdx@@ -87,7 +87,7 @@ Feishu/Lark, Slack, DingTalk, WeCom, Telegram에서는 멤버가 Bot에 처음## 연결 관리-워크스페이스 owner와 admin은 Bot을 연결하거나 연결 해제할 수 있습니다. Feishu/Lark Bot은 에이전트 owner도 연결하고 연결 해제할 수 있습니다. 일반 멤버는 이미 연결된 연동을 확인하고 자신에게 호출 권한이 있는 에이전트를 사용할 수 있습니다.+워크스페이스 owner와 admin은 Bot을 연결하거나 연결 해제할 수 있습니다. Feishu/Lark, DingTalk, WeChat은 에이전트 owner도 연결하고 연결 해제할 수 있습니다. 일반 멤버는 이미 연결된 연동을 확인하고 자신에게 호출 권한이 있는 에이전트를 사용할 수 있습니다.연결을 해제하면 Bot이 새 메시지를 받지 않습니다. 기존 Multica 대화와 실행 기록은 그대로 유지됩니다.diff --git a/apps/docs/content/docs/channels.mdx b/apps/docs/content/docs/channels.mdxindex 9d60b239a2..f251d21d0f 100644--- a/apps/docs/content/docs/channels.mdx+++ b/apps/docs/content/docs/channels.mdx@@ -87,7 +87,7 @@ Account binding only confirms who the sender is. Other members on the chat platf## Manage connections-Workspace owners and admins can connect or disconnect Bots; for Feishu/Lark Bots, connecting and disconnecting is also open to the agent's owner. Regular members can view connected integrations and use the agents they have access to.+Workspace owners and admins can connect or disconnect Bots; for Feishu/Lark, DingTalk, and WeChat, the agent's owner can also connect and disconnect its Bots. Regular members can view connected integrations and use the agents they have access to.After disconnecting, the Bot stops receiving new messages. Existing Multica conversations and run records are kept.diff --git a/apps/docs/content/docs/channels.zh-Hant.mdx b/apps/docs/content/docs/channels.zh-Hant.mdxindex 4e1f4e6d81..fc25a697d3 100644--- a/apps/docs/content/docs/channels.zh-Hant.mdx+++ b/apps/docs/content/docs/channels.zh-Hant.mdx@@ -87,7 +87,7 @@ Telegram 會把圖片、檔案、影片和音訊作為附件轉交給 AI 代理## 管理連線-工作區 owner 和 admin 可以連線或斷開 Bot;飛書/Lark Bot 的連線和斷開還對 AI 代理所有者開放。普通成員可以檢視已經連線的整合並使用自己有權呼叫的 AI 代理。+工作區 owner 和 admin 可以連線或斷開 Bot;飛書/Lark、釘釘和微信的連線和斷開還對 AI 代理所有者開放。普通成員可以檢視已經連線的整合並使用自己有權呼叫的 AI 代理。斷開後,Bot 不再接收新訊息。已有的 Multica 對話和執行記錄仍然保留。diff --git a/apps/docs/content/docs/channels.zh.mdx b/apps/docs/content/docs/channels.zh.mdxindex 26bfca6d72..54038019b5 100644--- a/apps/docs/content/docs/channels.zh.mdx+++ b/apps/docs/content/docs/channels.zh.mdx@@ -87,7 +87,7 @@ Telegram 会把图片、文件、视频和音频作为附件转交给智能体## 管理连接-工作区 owner 和 admin 可以连接或断开 Bot;飞书/Lark Bot 的连接和断开还对智能体所有者开放。普通成员可以查看已经连接的集成并使用自己有权调用的智能体。+工作区 owner 和 admin 可以连接或断开 Bot;飞书/Lark、钉钉和微信的连接和断开还对智能体所有者开放。普通成员可以查看已经连接的集成并使用自己有权调用的智能体。断开后,Bot 不再接收新消息。已有的 Multica 对话和执行记录仍然保留。diff --git a/apps/docs/content/docs/weixin-bot-integration.fr.mdx b/apps/docs/content/docs/weixin-bot-integration.fr.mdxindex 37ef5d4960..647a26d606 100644--- a/apps/docs/content/docs/weixin-bot-integration.fr.mdx+++ b/apps/docs/content/docs/weixin-bot-integration.fr.mdx@@ -7,7 +7,7 @@ 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**. Le QR code s'affiche aussitôt.+1. Ouvrez un agent dont vous êtes propriétaire. Les propriétaires et administrateurs de l’espace de travail peuvent connecter n’importe quel agent de cet espace. 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.@@ -34,7 +34,7 @@ En cas de forte charge, une notification de réponse WeChat peut être omise ; l## Se déconnecter-Dans les canaux de messagerie de l'agent, choisissez **Gérer WeChat → Déconnecter**. Les nouveaux messages ne parviennent plus à l'agent et le contexte de réponse enregistré est supprimé. L'historique des discussions Multica est conservé. Une réponse iLink signalant explicitement l'expiration de l'autorisation désactive aussi la connexion et affiche un avis d'expiration ; reconnectez-vous en scannant un nouveau QR code. Renouveler l'autorisation d'une connexion existante au même agent conserve sa discussion et son curseur de réception. Si le bot est déjà connecté à un autre agent de cet espace de travail, la boîte de dialogue nomme cet agent pour vous permettre de le déconnecter d'abord. Les identités des agents d'autres espaces restent privées.+Dans les canaux de messagerie de l'agent, choisissez **Gérer WeChat → Déconnecter**. Les nouveaux messages ne parviennent plus à l'agent et le contexte de réponse enregistré est supprimé. L'historique des discussions Multica est conservé. Une réponse iLink signalant explicitement l'expiration de l'autorisation désactive aussi la connexion et affiche un avis d'expiration ; reconnectez-vous en scannant un nouveau QR code. Renouveler l'autorisation d'une connexion existante au même agent conserve sa discussion et son curseur de réception. Si le bot est déjà connecté à un autre agent de cet espace de travail, la boîte de dialogue nomme cet agent si vous pouvez le gérer, pour vous permettre de le déconnecter d'abord. Les identités des agents d'autres espaces restent privées.diff --git a/apps/docs/content/docs/weixin-bot-integration.ja.mdx b/apps/docs/content/docs/weixin-bot-integration.ja.mdxindex f8876b0239..153f6b58bb 100644--- a/apps/docs/content/docs/weixin-bot-integration.ja.mdx+++ b/apps/docs/content/docs/weixin-bot-integration.ja.mdx@@ -7,7 +7,7 @@ Multica は Tencent の [OpenClaw Weixin プラグイン](https://github.com/Ten## 接続する-1. ワークスペースの owner または admin としてログインします。エージェントを開き、メッセージチャネルの **メッセージチャネルを追加** から **WeChat** を選びます。QR コードがすぐに表示されます。+1. 自分が所有するエージェントを開きます。ワークスペースの所有者または管理者は、ワークスペース内のどのエージェントにも接続できます。メッセージチャネルの **メッセージチャネルを追加** から **WeChat** を選びます。QR コードがすぐに表示されます。2. **自分の WeChat アカウント** で QR コードをスキャンし、スマートフォンで承認します。WeChat が確認コードを求めた場合は、スマートフォンに表示された数字をダイアログに入力します。接続が完了するとダイアログが閉じ、エージェントのメッセージチャネルに WeChat が表示されます。3. WeChat で Bot に新しい DM を送ります。エージェントが作業を実行するには、オンラインのランタイムが必要です。@@ -34,7 +34,7 @@ Multica は Tencent の [OpenClaw Weixin プラグイン](https://github.com/Ten## 接続を解除する-エージェントのメッセージチャネルで **WeChat を管理 → 接続を解除** を選びます。新しいメッセージはエージェントに届かなくなり、保存された返信用コンテキストも削除されます。Multica のチャット履歴は残ります。iLink が明示的に認証期限切れを返した場合も接続を無効化し、期限切れの通知を表示します。新しい QR コードをスキャンして再接続してください。同じエージェントへの既存接続を再認証した場合は、チャットと受信カーソルを保持します。同じワークスペースの別のエージェントに接続済みの場合、ダイアログにそのエージェント名が表示されるので、先にそこで接続を解除してください。他のワークスペースのエージェント情報は表示されません。+エージェントのメッセージチャネルで **WeChat を管理 → 接続を解除** を選びます。新しいメッセージはエージェントに届かなくなり、保存された返信用コンテキストも削除されます。Multica のチャット履歴は残ります。iLink が明示的に認証期限切れを返した場合も接続を無効化し、期限切れの通知を表示します。新しい QR コードをスキャンして再接続してください。同じエージェントへの既存接続を再認証した場合は、チャットと受信カーソルを保持します。同じワークスペースの別のエージェントに接続済みの場合、そのエージェントを管理できる場合はダイアログにエージェント名が表示されるので、先にそこで接続を解除してください。他のワークスペースのエージェント情報は表示されません。diff --git a/apps/docs/content/docs/weixin-bot-integration.ko.mdx b/apps/docs/content/docs/weixin-bot-integration.ko.mdxindex 67bd2f7707..6afa3600ba 100644--- a/apps/docs/content/docs/weixin-bot-integration.ko.mdx+++ b/apps/docs/content/docs/weixin-bot-integration.ko.mdx@@ -7,7 +7,7 @@ Multica는 Tencent의 [OpenClaw Weixin 플러그인](https://github.com/Tencent/## 연결하기-1. 워크스페이스 owner 또는 admin으로 로그인합니다. 에이전트를 열고 메시지 채널에서 **메시지 채널 추가** 를 선택한 뒤 **WeChat** 을 선택합니다. QR 코드가 바로 표시됩니다.+1. 내가 소유한 에이전트를 엽니다. 워크스페이스 소유자나 관리자는 워크스페이스의 모든 에이전트에 연결할 수 있습니다. 메시지 채널에서 **메시지 채널 추가** 를 선택한 뒤 **WeChat** 을 선택합니다. QR 코드가 바로 표시됩니다.2. **본인의 WeChat 계정** 으로 QR 코드를 스캔하고 휴대폰에서 승인합니다. WeChat이 인증 코드를 요구하면 휴대폰에 표시된 숫자를 대화 상자에 입력합니다. 연결되면 대화 상자가 닫히고 에이전트의 메시지 채널에 WeChat이 표시됩니다.3. WeChat에서 Bot에 새 DM을 보냅니다. 에이전트가 작업을 실행하려면 온라인 런타임이 필요합니다.@@ -34,7 +34,7 @@ Multica는 Tencent의 [OpenClaw Weixin 플러그인](https://github.com/Tencent/## 연결 해제-에이전트의 메시지 채널에서 **WeChat 관리 → 연결 해제** 를 선택합니다. 새 메시지는 에이전트에 전달되지 않고, 저장된 답변 컨텍스트도 삭제됩니다. Multica 채팅 기록은 유지됩니다. iLink가 명시적으로 인증 만료 응답을 반환해도 연결을 비활성화하고 만료 안내를 표시합니다. 새 QR 코드를 스캔해 다시 연결하세요. 같은 에이전트의 기존 연결을 재인증하면 채팅과 수신 커서를 유지합니다. 같은 워크스페이스의 다른 에이전트에 이미 연결된 Bot이면 대화 상자에 해당 에이전트 이름을 표시하므로 먼저 그곳에서 연결을 해제하세요. 다른 워크스페이스의 에이전트 정보는 표시하지 않습니다.+에이전트의 메시지 채널에서 **WeChat 관리 → 연결 해제** 를 선택합니다. 새 메시지는 에이전트에 전달되지 않고, 저장된 답변 컨텍스트도 삭제됩니다. Multica 채팅 기록은 유지됩니다. iLink가 명시적으로 인증 만료 응답을 반환해도 연결을 비활성화하고 만료 안내를 표시합니다. 새 QR 코드를 스캔해 다시 연결하세요. 같은 에이전트의 기존 연결을 재인증하면 채팅과 수신 커서를 유지합니다. 같은 워크스페이스의 다른 에이전트에 이미 연결된 Bot이면 해당 에이전트를 관리할 수 있으면 대화 상자에 에이전트 이름을 표시하므로 먼저 그곳에서 연결을 해제하세요. 다른 워크스페이스의 에이전트 정보는 표시하지 않습니다.diff --git a/apps/docs/content/docs/weixin-bot-integration.mdx b/apps/docs/content/docs/weixin-bot-integration.mdxindex c5700f2469..5f6b3c7951 100644--- a/apps/docs/content/docs/weixin-bot-integration.mdx+++ b/apps/docs/content/docs/weixin-bot-integration.mdx@@ -7,7 +7,7 @@ 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**, then select **WeChat**. The QR code appears right away.+1. Open an agent you own, or any agent if you are a workspace owner or admin. 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.@@ -34,7 +34,7 @@ Under heavy load, a WeChat reply notification may be skipped; the answer remains## 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.+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 if you can manage it, so you can disconnect it there first; other workspaces' agent identities remain private.diff --git a/apps/docs/content/docs/weixin-bot-integration.zh-Hant.mdx b/apps/docs/content/docs/weixin-bot-integration.zh-Hant.mdxindex 4c12229a02..3233cc28f3 100644--- a/apps/docs/content/docs/weixin-bot-integration.zh-Hant.mdx+++ b/apps/docs/content/docs/weixin-bot-integration.zh-Hant.mdx@@ -7,7 +7,7 @@ Multica 參考騰訊 [OpenClaw Weixin 外掛](https://github.com/Tencent/opencla## 連線-1. 以工作區 owner 或 admin 身分登入,開啟 AI 代理,在 "訊息渠道" 中選擇 "新增訊息管道",選擇微信後會直接顯示 QR 碼。+1. 開啟你擁有的 AI 代理。工作區所有者和管理員可以為工作區內的任何 AI 代理操作。在 "訊息渠道" 中選擇 "新增訊息管道",選擇微信後會直接顯示 QR 碼。2. 用**你自己的微信帳號**掃碼,並在手機上確認。微信要求驗證碼時,在彈窗中輸入手機顯示的數字。連接成功後彈窗會自動關閉,微信會出現在 AI 代理的 "訊息渠道" 中。3. 在微信中向機器人傳送一條新私訊。AI 代理需要線上的執行環境才能執行任務。@@ -30,7 +30,7 @@ Multica 參考騰訊 [OpenClaw Weixin 外掛](https://github.com/Tencent/opencla## 中斷連線-在 AI 代理的 "訊息渠道" 中選擇 "管理微信 → 中斷連接"。新訊息停止進入 AI 代理,已儲存的回覆上下文會刪除,Multica 聊天記錄保留。微信明確返回授權過期時也會停用連線並顯示授權過期提示,需要重新掃碼。重複授權同一 AI 代理的現有連線會保留聊天和接收游標。如果機器人已連接本工作區的其他 AI 代理,彈窗會指出該 AI 代理,請先在該處中斷連線;其他工作區的 AI 代理資訊不會顯示。+在 AI 代理的 "訊息渠道" 中選擇 "管理微信 → 中斷連接"。新訊息停止進入 AI 代理,已儲存的回覆上下文會刪除,Multica 聊天記錄保留。微信明確返回授權過期時也會停用連線並顯示授權過期提示,需要重新掃碼。重複授權同一 AI 代理的現有連線會保留聊天和接收游標。如果機器人已連接本工作區的其他 AI 代理,且你有權管理該 AI 代理,彈窗會指出它,請先在該處中斷連線;其他工作區的 AI 代理資訊不會顯示。## 自託管配置diff --git a/apps/docs/content/docs/weixin-bot-integration.zh.mdx b/apps/docs/content/docs/weixin-bot-integration.zh.mdxindex 23eb57f17c..794cf4e6f0 100644--- a/apps/docs/content/docs/weixin-bot-integration.zh.mdx+++ b/apps/docs/content/docs/weixin-bot-integration.zh.mdx@@ -7,7 +7,7 @@ Multica 参考腾讯 [OpenClaw Weixin 插件](https://github.com/Tencent/opencla## 连接-1. 以工作区所有者或管理员身份登录,打开智能体,在「消息渠道」中选择「添加消息渠道」,选择微信后会直接显示二维码。+1. 打开你拥有的智能体。工作区所有者和管理员可以为工作区内的任意智能体操作。在「消息渠道」中选择「添加消息渠道」,选择微信后会直接显示二维码。2. 用**你自己的微信账号**扫码,并在手机上确认。微信要求验证码时,在弹窗中输入手机显示的数字。连接成功后弹窗自动关闭,微信会出现在智能体的「消息渠道」中。3. 在微信中向机器人发送一条新私聊消息。智能体需要在线的运行环境才能执行任务。@@ -30,7 +30,7 @@ Multica 参考腾讯 [OpenClaw Weixin 插件](https://github.com/Tencent/opencla## 断开连接-在智能体的「消息渠道」中选择「管理微信 → 断开连接」。新消息停止进入智能体,已保存的回复上下文会删除,Multica 聊天记录保留。微信明确返回授权过期时也会停用连接并显示授权过期提示,需要重新扫码。重复授权同一智能体的现有连接会保留聊天和接收游标。如果机器人已连接本工作区的另一个智能体,弹窗会指出该智能体,请先在那里断开;其他工作区的智能体信息不会显示。+在智能体的「消息渠道」中选择「管理微信 → 断开连接」。新消息停止进入智能体,已保存的回复上下文会删除,Multica 聊天记录保留。微信明确返回授权过期时也会停用连接并显示授权过期提示,需要重新扫码。重复授权同一智能体的现有连接会保留聊天和接收游标。如果机器人已连接本工作区的另一个智能体,且你有权管理该智能体,弹窗会指出它,请先在那里断开;其他工作区的智能体信息不会显示。## 自托管配置diff --git a/e2e/weixin.spec.ts b/e2e/weixin.spec.tsindex dd3be5ac71..00c2403d32 100644--- a/e2e/weixin.spec.ts+++ b/e2e/weixin.spec.ts@@ -3,16 +3,21 @@ 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 ({+test("An agent owner can connect and disconnect WeChat as a workspace member", async ({page,}, testInfo) => {+ const admin = new TestApiClient();const api = new TestApiClient();const run = `${Date.now()}-${process.pid}`;+ await admin.login(`e2e-weixin-admin-${run}@example.test`, "Workspace Owner");+ const workspace = await admin.ensureWorkspace("WeChat review", `weixin-${run}`);const identity = await api.login(- `e2e-weixin-${run}@multica.ai`,- "WeChat E2E",+ `e2e-weixin-member-${run}@example.test`,+ "Agent Owner",);- const workspace = await api.ensureWorkspace("WeChat review", `weixin-${run}`);+ await admin.addMemberByEmail(api.getEmail());+ api.setWorkspaceId(workspace.id);+ api.setWorkspaceSlug(workspace.slug);await api.markUserOnboarded();const token = api.getToken();if (!token) throw new Error("test login returned no token");@@ -112,7 +117,10 @@ test("WeChat QR verification, connection listing, and disconnect", async ({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();+ const wechat = connectDialog.getByRole("button", { name: "WeChat", exact: true });+ await expect(wechat).toBeEnabled();+ await connectDialog.screenshot({ path: testInfo.outputPath("weixin-member-platform.png") });+ await wechat.click();// Choosing WeChat shows the QR straight away, with the guide below it.await expect(connectDialog.getByRole("img", { name: "WeChat connection QR code" }),@@ -120,10 +128,7 @@ test("WeChat QR verification, connection listing, and disconnect", async ({await expect(connectDialog.getByRole("button", { name: "Setup guide" }),).toBeVisible();- await page.screenshot({- path: testInfo.outputPath("weixin-qr.png"),- fullPage: true,- });+ await connectDialog.screenshot({ path: testInfo.outputPath("weixin-qr.png") });await expect(connectDialog.getByLabel("Verification code")).toBeVisible();await page.screenshot({path: testInfo.outputPath("weixin-verification.png"),@@ -156,5 +161,6 @@ test("WeChat QR verification, connection listing, and disconnect", async ({await expect(page.getByRole("button", { name: "Manage WeChat" })).toHaveCount(0);} finally {await api.cleanup();+ await admin.deleteWorkspace();}});diff --git a/packages/views/settings/components/messaging-channels.test.tsx b/packages/views/settings/components/messaging-channels.test.tsxindex c9fcfd313c..14e865b332 100644--- a/packages/views/settings/components/messaging-channels.test.tsx+++ b/packages/views/settings/components/messaging-channels.test.tsx@@ -241,7 +241,7 @@ describe("agent messaging channels", () => {expect(container).toBeEmptyDOMElement();});- it("gives an agent owner Lark and DingTalk, with admin-only platforms labelled", async () => {+ it("gives an agent owner Feishu, DingTalk and WeChat, with admin-only platforms labelled", async () => {state.role = "member";show(<AgentChannelsSection agent={agent} />);await waitFor(() =>@@ -259,6 +259,9 @@ describe("agent messaging channels", () => {expect(within(dialog).getByRole("button", { name: /^DingTalk$/ }),).toBeEnabled();+ expect(+ within(dialog).getByRole("button", { name: /^WeChat$/ }),+ ).toBeEnabled();expect(within(dialog).getByRole("button", { name: /Slack Ask an admin/ }),).toBeDisabled();@@ -349,6 +352,7 @@ describe("agent messaging channels", () => {it.each(["lark", "slack", "dingtalk", "wecom", "telegram", "weixin"] as const)("confirms %s disconnect and preserves the connection on failure",async (channel) => {+ if (channel === "weixin") state.role = "member";const methods = {lark: ["listLarkInstallations", "deleteLarkInstallation"],slack: ["listSlackInstallations", "deleteSlackInstallation"],@@ -397,7 +401,8 @@ const platformName = {} as const;describe("shared connection dialog", () => {- it("shows the WeChat QR as soon as WeChat is chosen and cancels it on close", async () => {+ it("shows the WeChat QR to the agent owner and cancels it on close", async () => {+ state.role = "member";const login = {id: "login-1",status: "wait",diff --git a/packages/views/settings/components/use-messaging-channels.ts b/packages/views/settings/components/use-messaging-channels.tsindex ec2064ec7d..a71011944f 100644--- a/packages/views/settings/components/use-messaging-channels.ts+++ b/packages/views/settings/components/use-messaging-channels.ts@@ -91,7 +91,7 @@ export function useMessagingChannels() {const canManage = (channel: ChannelIntegration, agent: Agent) =>!!member &&(isAdmin ||- ((channel === "lark" || channel === "dingtalk") &&+ ((channel === "lark" || channel === "dingtalk" || channel === "weixin") &&agent.owner_id === userId));const available = (channel: ChannelIntegration) =>queries[channel].data?.configured === true &&diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex ee16de438f..f6144f9023 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2008,9 +2008,6 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.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)diff --git a/server/internal/handler/weixin.go b/server/internal/handler/weixin.goindex f820a21d4e..9b53188403 100644--- a/server/internal/handler/weixin.go+++ b/server/internal/handler/weixin.go@@ -77,6 +77,9 @@ func (h *Handler) BeginWeixinLogin(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "agent not found in this workspace")return}+ if !h.canManageAgent(w, r, row) {+ return+ }view, err := h.WeixinInstall.Begin(r.Context(), workspace, agent, initiator)if err != nil {writeWeixinError(w, err)@@ -86,7 +89,7 @@ func (h *Handler) BeginWeixinLogin(w http.ResponseWriter, r *http.Request) {}// POST because a confirmed provider response commits the binding. Both the-// session and its QR view are scoped to the initiating signed-in admin.+// session and its QR view are scoped to the initiating user.func (h *Handler) PollWeixinLogin(w http.ResponseWriter, r *http.Request) {w.Header().Set("Cache-Control", "no-store")if h.WeixinInstall == nil {@@ -172,7 +175,11 @@ func (h *Handler) RevokeWeixinInstallation(w http.ResponseWriter, r *http.Requesif !ok {return}- if err := h.WeixinInstall.Revoke(r.Context(), installation, workspace); err != nil {+ actor, ok := parseUUIDOrBadRequest(w, userID, "user id")+ if !ok {+ return+ }+ if err := h.WeixinInstall.Revoke(r.Context(), installation, workspace, actor); err != nil {writeWeixinError(w, err)return}diff --git a/server/internal/handler/weixin_test.go b/server/internal/handler/weixin_test.goindex a267c1b647..ae02209979 100644--- a/server/internal/handler/weixin_test.go+++ b/server/internal/handler/weixin_test.go@@ -1,6 +1,7 @@package handlerimport (+ "bytes""encoding/json""net/http""net/http/httptest"@@ -9,6 +10,7 @@ import ("github.com/multica-ai/multica/server/internal/integrations/weixin""github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util/secretbox"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -83,3 +85,22 @@ func TestWeixinExpiredAuthorizationProjection(t *testing.T) {t.Fatal("manual disconnect shown as expired")}}++func TestBeginWeixinLoginRejectsUnrelatedMember(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ agentID, _, otherMember := privateAgentTestFixture(t)+ box, err := secretbox.New(bytes.Repeat([]byte{1}, 32))+ if err != nil {+ t.Fatal(err)+ }+ install, err := weixin.NewInstallService(testHandler.Queries, testPool, box)+ if err != nil {+ t.Fatal(err)+ }+ h := &Handler{Queries: testHandler.Queries, WeixinInstall: install}+ req := newRequestAs(otherMember, http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/weixin/logins?agent_id="+agentID, nil)+ req = withURLParam(req, "id", testWorkspaceID)+ testutil.Call(t, h.BeginWeixinLogin, req).Want(http.StatusForbidden)+}diff --git a/server/internal/integrations/weixin/database_test.go b/server/internal/integrations/weixin/database_test.goindex 53f0e3d3b6..963b6da32f 100644--- a/server/internal/integrations/weixin/database_test.go+++ b/server/internal/integrations/weixin/database_test.go@@ -228,6 +228,8 @@ func TestLoginExpiryReplacementAndRevokedMembership(t *testing.T) {}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)+ other := x.f.User(t, "Other agent owner", util.UUIDToString(dbid.NewV7())+"@example.test")+ x.f.Exec(t, `UPDATE agent SET owner_id=$1 WHERE id=$2`, other, x.agent)if _, err := x.svc.Poll(context.Background(), next, x.workspace, x.user, ""); !errors.Is(err, ErrAccess) {t.Fatalf("demoted admin installed: %v", err)}@@ -241,11 +243,17 @@ func TestLoginBotOwnershipAndRevoke(t *testing.T) {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) {+ if err := x.svc.Revoke(context.Background(), inst.ID, y.workspace, y.user); !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)+ other := x.f.User(t, "Unrelated member", util.UUIDToString(dbid.NewV7())+"@example.test")+ x.f.Member(t, x.f.WorkspaceID, other, "member")+ if err := x.svc.Revoke(context.Background(), inst.ID, x.workspace, testUUID(t, other)); !errors.Is(err, ErrAccess) {+ t.Fatalf("unrelated member revoke: %v", err)+ }+ 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.Revoke(context.Background(), inst.ID, x.workspace, x.user); err != nil {+ t.Fatalf("agent owner revoke: %v", err)}y.connect(t)if count := x.f.Count(t, "SELECT count(*) FROM weixin_account_state WHERE installation_id=$1", inst.ID); count != 0 {@@ -255,6 +263,7 @@ func TestLoginBotOwnershipAndRevoke(t *testing.T) {func TestLoginTokensAreScopedAndBoundRedirectPreservesInstallation(t *testing.T) {x := newDatabaseFixture(t)+ x.f.Exec(t, `UPDATE member SET role='member' WHERE workspace_id=$1 AND user_id=$2`, x.workspace, x.user)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)@@ -295,13 +304,15 @@ func TestBoundRedirectRejectsMissingRevokedOrChangedInstallation(t *testing.T) {id := x.begin(t)switch kind {case "revoked":- if err := x.svc.Revoke(context.Background(), inst.ID, x.workspace); err != nil {+ if err := x.svc.Revoke(context.Background(), inst.ID, x.workspace, x.user); 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)+ other := x.f.User(t, "Other agent owner", util.UUIDToString(dbid.NewV7())+"@example.test")+ x.f.Exec(t, `UPDATE agent SET owner_id=$1 WHERE id=$2`, other, x.agent)}x.status.Store(qrStatus{Status: "binded_redirect"})if _, err := x.svc.Poll(context.Background(), id, x.workspace, x.user, ""); err == nil {@@ -311,7 +322,7 @@ func TestBoundRedirectRejectsMissingRevokedOrChangedInstallation(t *testing.T) {}}-func TestLoginConflictNamesOnlyCurrentWorkspaceAgent(t *testing.T) {+func TestLoginConflictNamesOnlyManageableAgents(t *testing.T) {x := newDatabaseFixture(t)x.connect(t)other := testUUID(t, x.f.Agent(t, "Another agent", ""))@@ -324,6 +335,18 @@ func TestLoginConflictNamesOnlyCurrentWorkspaceAgent(t *testing.T) {if !errors.As(err, &conflict) || conflict.AgentID != util.UUIDToString(x.agent) || conflict.AgentName != "WeChat test agent" {t.Fatalf("missing conflict owner: %v", err)}+ member := x.f.User(t, "Another agent owner", util.UUIDToString(dbid.NewV7())+"@example.test")+ x.f.Member(t, x.f.WorkspaceID, member, "member")+ x.f.Exec(t, `UPDATE agent SET owner_id=$1 WHERE id=$2`, member, other)+ memberID := testUUID(t, member)+ view, err = x.svc.Begin(context.Background(), x.workspace, other, memberID)+ if err != nil {+ t.Fatal(err)+ }+ _, err = x.svc.Poll(context.Background(), testUUID(t, view.ID), x.workspace, memberID, "")+ if !errors.Is(err, ErrConflict) || errors.As(err, &conflict) {+ t.Fatalf("member conflict disclosed another owner's agent: %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, "")@@ -386,7 +409,7 @@ func TestTypingTracksDurableInputsAndRetryAcrossReplicas(t *testing.T) {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 {+ if err := x.svc.Revoke(ctx, inst.ID, x.workspace, x.user); err != nil {t.Fatal(err)}assertActive(false)@@ -471,7 +494,7 @@ func TestOutboundDedupUnknownAndRouting(t *testing.T) {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 {+ if err := x.svc.Revoke(ctx, inst.ID, x.workspace, x.user); err != nil {t.Fatal(err)}}diff --git a/server/internal/integrations/weixin/install.go b/server/internal/integrations/weixin/install.goindex 3b9f82f8bd..ea6797e104 100644--- a/server/internal/integrations/weixin/install.go+++ b/server/internal/integrations/weixin/install.go@@ -245,6 +245,25 @@ func (s *InstallService) Poll(ctx context.Context, session, workspace, initiatorreturn s.Get(ctx, session, workspace, initiator)}+func canManageAgent(member db.Member, agent db.Agent) bool {+ return member.Role == "owner" || member.Role == "admin" ||+ (member.Role == "member" && agent.OwnerID.Valid && agent.OwnerID == member.UserID)+}++// Check again when a QR scan completes, since agent access can change while+// the session is open.+func authorizeLogin(ctx context.Context, q *db.Queries, session db.WeixinLoginSession) (db.Member, error) {+ member, err := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: session.InitiatorUserID, WorkspaceID: session.WorkspaceID})+ if err != nil {+ return db.Member{}, ErrAccess+ }+ agent, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: session.AgentID, WorkspaceID: session.WorkspaceID})+ if err != nil || agent.ArchivedAt.Valid || !canManageAgent(member, agent) {+ return db.Member{}, ErrAccess+ }+ return member, nil+}+func (s *InstallService) complete(ctx context.Context, session db.WeixinLoginSession, result qrStatus) error {tx, err := s.tx.Begin(ctx)if err != nil {@@ -255,13 +274,9 @@ func (s *InstallService) complete(ctx context.Context, session db.WeixinLoginSesif _, 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+ member, err := authorizeLogin(ctx, q, session)+ if err != nil {+ return err}if err := q.LockChannelInstallationAppIDSlot(ctx, db.LockChannelInstallationAppIDSlotParams{ChannelType: string(TypeWeixin), AppID: result.BotID}); err != nil {return err@@ -271,7 +286,7 @@ func (s *InstallService) complete(ctx context.Context, session db.WeixinLoginSesreturn 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)+ return s.conflict(ctx, q, member, 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@@ -283,7 +298,7 @@ func (s *InstallService) complete(ctx context.Context, session db.WeixinLoginSesif 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)+ return s.conflict(ctx, q, member, 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 {@@ -312,12 +327,12 @@ func (s *InstallService) complete(ctx context.Context, session db.WeixinLoginSesreturn tx.Commit(ctx)}-func (s *InstallService) conflict(ctx context.Context, q *db.Queries, requestedWorkspace, ownerWorkspace, agentID pgtype.UUID) error {+func (s *InstallService) conflict(ctx context.Context, q *db.Queries, member db.Member, 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 {+ if err != nil || !canManageAgent(member, agent) {return ErrConflict}return &ConflictError{AgentID: util.UUIDToString(agent.ID), AgentName: agent.Name}@@ -337,13 +352,8 @@ func (s *InstallService) confirmExisting(ctx context.Context, session db.WeixinLif _, 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 := authorizeLogin(ctx, q, session); err != nil {+ return err}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) {@@ -364,7 +374,7 @@ func (s *InstallService) List(ctx context.Context, workspace pgtype.UUID) ([]db.return s.q.ListChannelInstallationsByWorkspace(ctx, db.ListChannelInstallationsByWorkspaceParams{WorkspaceID: workspace, ChannelType: string(TypeWeixin)})}-func (s *InstallService) Revoke(ctx context.Context, installation, workspace pgtype.UUID) error {+func (s *InstallService) Revoke(ctx context.Context, installation, workspace, actor pgtype.UUID) error {tx, err := s.tx.Begin(ctx)if err != nil {return err@@ -378,6 +388,21 @@ func (s *InstallService) Revoke(ctx context.Context, installation, workspace pgtif err != nil {return err}+ member, err := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: actor, WorkspaceID: workspace})+ if errors.Is(err, pgx.ErrNoRows) {+ return ErrAccess+ }+ if err != nil {+ return err+ }+ agent, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: row.AgentID, WorkspaceID: workspace})+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {+ return err+ }+ // For an orphaned installation the zero-value agent leaves cleanup to workspace admins.+ if !canManageAgent(member, agent) {+ return ErrAccess+ }if err := q.SetChannelInstallationStatus(ctx, db.SetChannelInstallationStatusParams{ID: row.ID, Status: "revoked"}); err != nil {return err}