Skip to content

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

Go

MUL-5947: feat(dingtalk): route groups to different agents (#6660)

mxbao063-bao8060aa7277d9
diff --git a/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx b/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx
index a98da64c67..092ac33959 100644
--- a/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx
+++ b/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx
@@ -9,7 +9,7 @@ import { Callout } from "fumadocs-ui/components/callout";
DingTalk 連携はコミュニティによってメンテナンスされています。毎リリースに同梱されますが、公式のサポート SLA は付きません。問題があれば [GitHub issues](https://github.com/multica-ai/multica/issues) に報告してください。
-DingTalk は**自分のアプリを持ち込む(BYO: bring-your-own-app)**モデルを採用しています。ワークスペースの admin が DingTalk アプリを作成し、それに Stream モードのロボットを追加して、その認証情報を Multica に貼り付けます。エージェントごとに**専用の** DingTalk アプリを持つため、同じ組織内で複数のエージェントがそれぞれ別個に @ メンションできる異なる Bot を持てます。(これは紐づけがスキャンしてインストールするフローである [Lark](/lark-bot-integration) とは異なります。)
+DingTalk は**自分のアプリを持ち込む(BYO: bring-your-own-app)**モデルを採用しています。ワークスペースの admin が DingTalk アプリを作成し、Stream モードのロボットを追加して、その認証情報を Multica に貼り付けます。セットアップ時に選んだエージェントが DM と新しく検出されたグループのデフォルトになります。同じロボットを複数のグループに追加し、グループごとに別のエージェントへルーティングできます。(これは紐づけがスキャンしてインストールするフローである [Lark](/lark-bot-integration) とは異なります。)
セットアップ全体は以下のとおりで、所要時間は約 5 分です。最終的に、Multica に貼り付ける 2 つの認証情報が得られます。
@@ -59,11 +59,11 @@ DingTalk にはネイティブの入力中/リアクションのインジケ
4. エージェントに **Connected to DingTalk** と表示されます。Bot はこれで、自身の Stream 接続を通じて待ち受けています。
<Callout type="warning">
-2 つの認証情報は**同じ** DingTalk アプリのものでなければならず、そのアプリはちょうど **1 つ**のエージェントに対応します。すでに別のエージェントやワークスペースに接続されているアプリを接続しようとすると拒否されます。アプリを別のエージェントへ移すには、まず切断してください。**新しい**アプリでエージェントを再接続すると、そのエージェントの Bot がその場で更新されます。
+2 つの認証情報は**同じ** DingTalk アプリのものでなければならず、そのアプリは 1 つの Multica ワークスペースに 1 回だけインストールできます。2 つ目のインストールや別のワークスペースへの接続は拒否されます。インストール時のエージェントは DM のデフォルトとして残り、グループは再接続せずに別のエージェントへルーティングできます。
</Callout>
<Callout type="info">
-**複数のエージェント**でこれを設定しますか? フロー全体をエージェントごとに 1 回ずつ繰り返してください——各エージェントが専用の DingTalk アプリと専用の AppKey / AppSecret を持ち、組織内で別々の Bot として表示されます。
+1 つのロボットを**複数のエージェント**で使うには、各 DingTalk グループに追加して一度 @ メンションし、**Settings → Integrations → DingTalk → グループルーティング**でグループごとのエージェントを選びます。別の Bot ID や DM 用エージェントが必要な場合だけ、別の DingTalk アプリをインストールしてください。
</Callout>
## この連携でできること
@@ -72,7 +72,7 @@ DingTalk にはネイティブの入力中/リアクションのインジケ
|---|---|
| **エージェント → Integrations** | owner と admin には **Connect DingTalk** が表示され、接続すると **Connected to DingTalk** バッジと **Disconnect** コントロールに切り替わります。 |
| **Bot に DM** | ワークスペースメンバーが 1:1 チャットで Bot に直接メッセージを送ります。会話はそのエージェントとの Multica [chat](/chat) セッションになり、すべてのメッセージが読み取られます。 |
-| **グループで @ メンション** | Bot をグループに追加し、@ メンションします。読み取られるのはメンションしたメッセージだけで、Bot はグループ全体を聞いているわけではありません。 |
+| **グループで @ メンション** | Bot をグループに追加し、@ メンションします。最初のメンションでグループが検出され、まずデフォルトのエージェントが使われます。owner または admin は**グループルーティング**で別のエージェントを選べます。読み取られるのはメンションしたメッセージだけです。 |
| **画像を送る** | DM の画像も、グループで @ メンションと一緒に送った画像も、会話に入りエージェントが見られるようになります——PNG・JPEG・GIF・WebP・BMP に対応し、1 メッセージあたり最大 4 枚、1 枚あたり 10 MB までです。各画像は Multica のストレージにコピーされるため、DingTalk の一時リンクが失効した後も会話の中に表示され続けます。`/issue` と一緒に送った画像は、チャットの turn ではなく作成されたイシューに添付されます。ファイルと音声には対応していません。 |
| **`/issue` コマンド** | `/issue <タイトル>` で始めると、入力内容からあなた名義の Multica タスクを直接かつ同期的に作成し、同じ会話へ ID とタイトルを返します。続く行は説明になります。同じ DingTalk メッセージの画像は、作成したタスクに添付されます。コマンド自体は Multica Chat に表示されず、作成したタスクが Multica に記録される処理結果になります。 |
| **`/new` コマンド** | `/new <あなたのメッセージ>` で始めると、そのメッセージを過去の文脈なしで実行します。`/new` だけを送ると、同じ fresh-start の意図が次の空でないメッセージに適用され、空の turn は作られません。既存の会話履歴はそのまま残ります。 |
@@ -101,6 +101,8 @@ Bot を使えるのは **ワークスペースのメンバー** だけです。
ワークスペース全体の管理は **Settings → Integrations** にあります。
- **Connected bots** は、ワークスペース内のすべての Bot と、それぞれが紐づくエージェントを一覧表示します(すべてのメンバーから見えます)。
+- **グループルーティング**は Bot が検出したすべてのグループを表示します。owner と admin はグループごとに固定のエージェントを選べ、全メンバーが現在のルートを確認できます。
+- ルートを変更するたびに、選択したエージェント用の新しい Chat セッションが作成されます。エージェント A → B → A と戻しても、A の以前のセッションは再開されません。割り当てたエージェントをアーカイブするとルートは保持されますが、そのエージェントを復元するかグループを再割り当てするまで、処理は停止して利用不可の通知が返ります。
- **Disconnect** は **owner / admin 専用** です。切断すると Bot は DingTalk メッセージの受信を停止し、その接続が破棄されます。インストール記録は監査のために保持され、あとで再接続できます。
## 権限
diff --git a/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx b/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx
index b8a15d03bf..199c901135 100644
--- a/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx
+++ b/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx
@@ -9,7 +9,7 @@ import { Callout } from "fumadocs-ui/components/callout";
DingTalk 연동은 커뮤니티가 유지관리합니다. 매 릴리스에 포함되지만 공식 지원 SLA는 제공되지 않습니다. 문제가 있으면 [GitHub issues](https://github.com/multica-ai/multica/issues)에 보고해 주세요.
-DingTalk은 **자체 앱 사용(BYO)** 모델을 따릅니다: 워크스페이스 admin이 DingTalk 앱을 만들고, 거기에 Stream 모드 로봇을 추가한 다음, 그 자격 증명을 Multica에 붙여넣습니다. 각 에이전트가 **자체** DingTalk 앱을 갖습니다 — 그래서 하나의 조직 안에서 여러 에이전트가 각각 별개로 `@`로 멘션할 수 있는 봇을 가질 수 있습니다. (바인딩이 스캔하여 설치하는 방식인 [Lark](/lark-bot-integration)와는 다릅니다.)
+DingTalk은 **자체 앱 사용(BYO)** 모델을 따릅니다. 워크스페이스 admin이 DingTalk 앱을 만들고 Stream 모드 로봇을 추가한 다음, 그 자격 증명을 Multica에 붙여넣습니다. 설정할 때 선택한 에이전트가 DM과 새로 발견된 그룹의 기본 에이전트가 됩니다. 같은 로봇을 여러 그룹에 추가하고 그룹마다 다른 에이전트로 라우팅할 수 있습니다. (바인딩이 스캔하여 설치하는 방식인 [Lark](/lark-bot-integration)와는 다릅니다.)
전체 설정은 아래에 있으며 약 5분이 걸립니다. 마지막에는 Multica에 붙여넣을 두 개의 자격 증명을 얻게 됩니다:
@@ -59,11 +59,11 @@ DingTalk에는 기본 입력 중 / 반응 표시기가 없으므로 — Slack과
4. 에이전트에 **Connected to DingTalk**이 표시됩니다. 봇은 이제 자체 Stream 연결로 수신 대기합니다.
<Callout type="warning">
-두 자격 증명은 **같은** DingTalk 앱에서 와야 하며, 그 앱은 정확히 **하나의** 에이전트에 매핑됩니다. 이미 다른 에이전트나 워크스페이스에 연결된 앱을 연결하는 것은 거부됩니다. 앱을 다른 에이전트로 옮기려면 먼저 연결을 해제하세요. **새** 앱으로 에이전트를 다시 연결하면 그 에이전트의 봇이 그 자리에서 갱신됩니다.
+두 자격 증명은 **같은** DingTalk 앱에서 와야 하며, 그 앱은 하나의 Multica 워크스페이스에 한 번만 설치할 수 있습니다. 두 번째 설치나 다른 워크스페이스 연결은 거부됩니다. 설치할 때 선택한 에이전트는 DM의 기본값으로 유지되고, 그룹은 앱을 다시 연결하지 않고 다른 에이전트로 라우팅할 수 있습니다.
</Callout>
<Callout type="info">
-**여러 에이전트**에 설정하나요? 에이전트당 전체 과정을 한 번씩 반복하세요 — 각 에이전트가 자체 DingTalk 앱과 자체 AppKey / AppSecret을 가지며, 조직에 별개의 봇으로 나타납니다.
+하나의 로봇을 **여러 에이전트**에서 사용하려면 각 DingTalk 그룹에 추가하고 한 번 @ 멘션한 뒤, **Settings → Integrations → DingTalk → 그룹 라우팅**에서 그룹별 에이전트를 선택하세요. 별도의 봇 ID나 DM 에이전트가 필요할 때만 DingTalk 앱을 따로 설치하면 됩니다.
</Callout>
## 연동이 하는 일
@@ -72,7 +72,7 @@ DingTalk에는 기본 입력 중 / 반응 표시기가 없으므로 — Slack과
|---|---|
| **Agent → Integrations** | owner와 admin에게는 **Connect DingTalk**이 보이며, 연결되면 **Connected to DingTalk** 배지와 **Disconnect** 컨트롤로 바뀝니다. |
| **봇에게 DM** | 워크스페이스 멤버가 1:1 채팅에서 봇에게 직접 메시지를 보냅니다. 그 대화는 에이전트와의 Multica [chat](/chat) 세션이 되며, 모든 메시지를 읽습니다. |
-| **그룹에서 `@`-멘션** | 봇을 그룹에 추가하고 `@`로 멘션하세요. 멘션한 메시지만 읽으며, 봇이 그룹 전체를 듣지는 않습니다. |
+| **그룹에서 `@`-멘션** | 봇을 그룹에 추가하고 `@`로 멘션하세요. 첫 멘션에서 그룹을 발견하고 처음에는 기본 에이전트를 사용합니다. owner 또는 admin은 **그룹 라우팅**에서 다른 에이전트를 선택할 수 있습니다. 멘션한 메시지만 읽습니다. |
| **이미지 보내기** | DM의 이미지, 또는 그룹에서 `@`-멘션과 함께 보낸 이미지는 대화에 들어가 에이전트가 볼 수 있습니다 — PNG, JPEG, GIF, WebP, BMP를 지원하며, 메시지당 최대 4장, 장당 10 MB까지입니다. 각 이미지는 Multica 스토리지로 복사되므로, DingTalk의 임시 링크가 만료된 뒤에도 대화에서 계속 보입니다. `/issue`와 함께 보낸 이미지는 채팅 turn이 아니라 생성된 이슈에 첨부됩니다. 파일과 음성은 지원하지 않습니다. |
| **`/issue` 명령** | `/issue <제목>`으로 시작하면 입력 내용에서 당신 이름의 Multica 태스크를 직접 동기적으로 만들고 같은 대화에 ID와 제목을 돌려줍니다. 다음 줄은 설명이 됩니다. 같은 DingTalk 메시지의 이미지는 생성된 태스크에 첨부됩니다. 명령 자체는 Multica Chat에 표시되지 않으며 생성된 태스크가 Multica에 기록되는 처리 결과입니다. |
| **`/new` 명령** | `/new <당신의 메시지>`로 시작하면 그 메시지를 이전 대화 맥락 없이 실행합니다. `/new`만 보내면 같은 fresh-start 의도가 다음 비어 있지 않은 메시지에 적용되며 빈 turn은 만들어지지 않습니다. 기존 대화 기록은 그대로 유지됩니다. |
@@ -101,6 +101,8 @@ DingTalk에는 기본 입력 중 / 반응 표시기가 없으므로 — Slack과
워크스페이스 전체 관리는 **Settings → Integrations**에 있습니다:
- **Connected bots**는 워크스페이스 내 모든 봇과 각 봇이 바인딩된 에이전트를 나열합니다(모든 멤버에게 보입니다).
+- **그룹 라우팅**은 봇이 발견한 모든 그룹을 보여줍니다. owner와 admin은 그룹마다 고정 에이전트를 선택할 수 있고, 모든 멤버는 현재 라우팅을 볼 수 있습니다.
+- 라우팅을 변경할 때마다 선택한 에이전트의 새 Chat 세션이 생성됩니다. 에이전트 A → B → A로 되돌려도 A의 이전 세션은 재개되지 않습니다. 할당된 에이전트를 보관하면 라우팅은 유지되지만, 해당 에이전트를 복원하거나 그룹을 다시 할당할 때까지 처리가 중지되고 사용할 수 없다는 안내가 표시됩니다.
- **Disconnect**는 **owner / admin 전용**입니다. 봇이 DingTalk 메시지 수신을 멈추고 연결이 해체됩니다. 설치 기록은 감사용으로 유지되며, 이후 다시 연결할 수 있습니다.
## 권한
diff --git a/apps/docs/content/docs/dingtalk-bot-integration.mdx b/apps/docs/content/docs/dingtalk-bot-integration.mdx
index 492cb6d061..af26ba3501 100644
--- a/apps/docs/content/docs/dingtalk-bot-integration.mdx
+++ b/apps/docs/content/docs/dingtalk-bot-integration.mdx
@@ -9,7 +9,7 @@ Connect any [agent](/agents) to a DingTalk bot and your team can work with it fr
DingTalk support is community-maintained: it ships in every release, but it carries no official support SLA. Report problems in [GitHub issues](https://github.com/multica-ai/multica/issues).
-DingTalk uses a **bring-your-own-app (BYO)** model: a workspace admin creates a DingTalk app, adds a Stream-mode robot to it, and pastes its credentials into Multica. Each agent gets **its own** DingTalk app — so several agents can each have a distinct, separately @-mentionable bot in the same organization. (This differs from [Lark](/lark-bot-integration), where binding is a scan-to-install flow.)
+DingTalk uses a **bring-your-own-app (BYO)** model: a workspace admin creates a DingTalk app, adds a Stream-mode robot to it, and pastes its credentials into Multica. The agent selected during setup is the robot's default for DMs and newly discovered groups. The same robot can join multiple groups, and each group can then be routed to a different agent. (This differs from [Lark](/lark-bot-integration), where binding is a scan-to-install flow.)
The whole setup is below and takes about five minutes. You'll end up with two credentials to paste into Multica:
@@ -59,11 +59,11 @@ Open the app's **凭证与基础信息** (Credentials & Basic Information) and c
4. The agent shows **Connected to DingTalk**. The bot is now listening over its own Stream connection.
<Callout type="warning">
-Both credentials must be from the **same** DingTalk app, and that app maps to exactly **one** agent. Connecting an app that's already connected to a different agent or workspace is refused. To move an app to another agent, disconnect it first; re-connecting an agent with a **new** app updates that agent's bot in place.
+Both credentials must be from the **same** DingTalk app, and that app is installed only once in a Multica workspace. Connecting it as a second installation or in another workspace is refused. The installation's agent remains the default for DMs; group routes may target other agents without reconnecting the app.
</Callout>
<Callout type="info">
-Setting this up for **multiple agents**? Repeat the whole flow once per agent — each agent gets its own DingTalk app and its own AppKey / AppSecret, and they show up as separate bots in your organization.
+Want one robot to serve **multiple agents**? Add it to each DingTalk group, @-mention it once so Multica discovers the group, then choose that group's agent under **Settings → Integrations → DingTalk → Group routing**. Install separate DingTalk apps only when you want separate bot identities or separate DM agents.
</Callout>
## What the integration does
@@ -72,7 +72,7 @@ Setting this up for **multiple agents**? Repeat the whole flow once per agent
|---|---|
| **Agent → Integrations** | Owners and admins see **Connect DingTalk**; once connected it flips to a **Connected to DingTalk** badge with a **Disconnect** control. |
| **DM the bot** | A workspace member messages the bot in a 1:1 chat. The conversation becomes a Multica [chat](/chat) session with the agent; every message is read. |
-| **@-mention in a group** | Add the bot to the group and @-mention it. Only the mentioning message is read — the bot does not listen to the whole group. |
+| **@-mention in a group** | Add the bot to the group and @-mention it. The first mention discovers the group and uses the robot's default agent; an owner or admin can then select a different agent under **Group routing**. Only mentioning messages are read — the bot does not listen to the whole group. |
| **Send images** | Images in a DM, or sent alongside a group @-mention, land in the conversation for the agent to see — PNG, JPEG, GIF, WebP, or BMP, up to 4 images per message and 10 MB each. Each image is copied into Multica storage, so it stays visible in the chat after DingTalk's temporary link expires. Images sent with `/issue` go to the created issue instead of the chat turn. Files and voice messages aren't supported. |
| **`/issue` command** | Starting a message with `/issue <title>` creates a Multica issue directly from your input, attributed to you, and posts the issue ID and title back into the same conversation. Put the description on following lines. Images sent in the same DingTalk message are attached to the created issue. The command itself does not appear in Multica Chat; the created issue is the result recorded in Multica. |
| **`/new` command** | Starting a message with `/new <your message>` runs that message without prior conversation context. Sending `/new` by itself records the same fresh-start intent for your next non-empty message without creating an empty turn, and the bot confirms when that intent is ready. The pending intent remains active until a later chat task is successfully queued. The conversation history remains intact. |
@@ -101,6 +101,8 @@ Only **members of the workspace** can use the bot. If you aren't a member, or yo
Workspace-wide management lives in **Settings → Integrations**:
- **Connected bots** lists every bot in the workspace and the agent each is bound to (visible to all members).
+- **Group routing** lists every group discovered by a bot. Owners and admins can select one fixed agent per group; all members can see the current routes.
+- Every route change starts a new chat session for the selected agent. Routing Agent A → Agent B → Agent A does not resume A's earlier session. Archiving an assigned agent preserves the route but pauses processing with an unavailable notice until that agent is restored or the group is reassigned.
- **Disconnect** is **owner / admin only**. It stops the bot from receiving DingTalk messages and tears down its connection; the installation record is kept for audit, and you can re-connect later.
## Permissions
diff --git a/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx b/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx
index cee1f54950..dbe6e91d7a 100644
--- a/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx
+++ b/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx
@@ -9,7 +9,7 @@ import { Callout } from "fumadocs-ui/components/callout";
钉钉集成由社区维护:每个版本都会随包发布,但不附带官方支持 SLA。遇到问题请提到 [GitHub issues](https://github.com/multica-ai/multica/issues)。
-钉钉走的是**自带应用(bring-your-own-app,BYO)**模式:workspace 管理员创建一个钉钉 app,给它加一个 Stream 模式的机器人,再把它的凭证粘贴进 Multica。每个智能体都有**它自己的**钉钉 app——所以多个智能体可以在同一个组织里各自拥有一个独立、可单独 @ 的 Bot。(这一点和 [Lark](/lark-bot-integration) 不同,Lark 的绑定是扫码安装流程。)
+钉钉走的是**自带应用(bring-your-own-app,BYO)**模式:工作区管理员创建一个钉钉 app,给它加一个 Stream 模式的机器人,再把凭证粘贴进 Multica。设置时选择的智能体是机器人的默认智能体,负责私聊和刚发现的群聊。同一个机器人可以加入多个群,每个群之后都能分别路由到不同智能体。(这一点和 [Lark](/lark-bot-integration) 不同,Lark 的绑定是扫码安装流程。)
整个设置流程在下面,大约五分钟。最后你会得到两个凭证粘贴进 Multica:
@@ -59,11 +59,11 @@ import { Callout } from "fumadocs-ui/components/callout";
4. 智能体显示 **Connected to DingTalk**。Bot 现在通过它自己的 Stream 连接在监听了。
<Callout type="warning">
-这两个凭证必须来自**同一个**钉钉 app,而那个 app 恰好对应**一个**智能体。连接一个已经连到别的智能体或 workspace 的 app 会被拒绝。要把一个 app 挪到另一个智能体,先断开它;用一个**新的** app 重新连接某个智能体,会就地更新那个智能体的 Bot。
+这两个凭证必须来自**同一个**钉钉 app,而且该 app 在一个 Multica 工作区中只安装一次。尝试把它作为第二个安装或连接到其他工作区会被拒绝。安装时选择的智能体仍负责私聊;群路由可直接指向其他智能体,无需重新连接 app。
</Callout>
<Callout type="info">
-要给**多个智能体**做这套设置?每个智能体都把整套流程走一遍——每个智能体都有自己的钉钉 app 和自己的一对 AppKey / AppSecret,它们会在你的组织里显示成各自独立的 Bot。
+想让一个机器人服务**多个智能体**?把它加入各个钉钉群,在每个群里 @ 一次让 Multica 自动发现,然后到 **Settings → Integrations → DingTalk → 群路由** 为每个群选择智能体。只有需要不同机器人身份或不同私聊智能体时,才需要安装多个钉钉 app。
</Callout>
## 这个集成能做什么
@@ -72,7 +72,7 @@ import { Callout } from "fumadocs-ui/components/callout";
|---|---|
| **智能体 → Integrations** | 所有者和管理员能看到 **Connect DingTalk**;连接后它会变成一个 **Connected to DingTalk** 徽标,并带一个 **Disconnect** 操作。 |
| **私聊 Bot** | 工作区成员在单聊里直接给 Bot 发消息。这段对话会成为该智能体的一个 Multica [chat](/chat) 会话;每一条消息都会被读取。 |
-| **群里 @ 它** | 把 Bot 加进群再 @ 它。只有 @ 它的那条消息会被读取——Bot 不会监听整个群。 |
+| **群里 @ 它** | 把 Bot 加进群再 @ 它。第一次 @ 会自动发现该群,并先使用机器人的默认智能体;所有者或管理员可在**群路由**中改成其他智能体。只有 @ 它的消息会被读取——Bot 不会监听整个群。 |
| **发图片** | 单聊里的图片、或群里随 @ 一起发的图片,都会进入对话让智能体看到——支持 PNG、JPEG、GIF、WebP、BMP,每条消息最多 4 张、每张不超过 10 MB。每张图片都会复制进 Multica 存储,所以钉钉的临时链接过期后,它在对话里依然可见。随 `/issue` 一起发送的图片会改为附到新建的 issue 上,而不是这条聊天消息。文件和语音不支持。 |
| **`/issue` 命令** | 以 `/issue <标题>` 开头,会按输入直接、同步地以你的身份创建 Multica 任务,并在原对话中返回任务编号和标题;后续行会作为描述。同一条钉钉消息中的图片会附到新建任务中。这条命令不会出现在 Multica Chat;新建任务是 Multica 中记录的处理结果。 |
| **`/new` 命令** | 以 `/new <你的消息>` 开头,会让这条消息在不带旧上下文的情况下运行。单独发送 `/new` 会把同样的 fresh 意图留给下一条非空消息,不会创建空 turn;已有对话记录保持不变。 |
@@ -101,6 +101,8 @@ import { Callout } from "fumadocs-ui/components/callout";
工作区级别的管理在 **Settings → Integrations**:
- **Connected bots** 列出工作区里每个 Bot 以及它各自绑定的智能体(所有成员都能看到)。
+- **群路由**列出 Bot 已发现的所有群。所有者和管理员可为每个群选择一个固定智能体;所有成员都能查看当前路由。
+- 每次更改路由都会为所选智能体创建一个新的 Chat 会话。将智能体 A → 智能体 B → 智能体 A 不会恢复 A 之前的会话。已分配的智能体归档后,路由会保留,但消息处理会暂停并提示不可用,直到该智能体恢复或群被重新分配。
- **Disconnect** 仅限 **所有者 / 管理员**。它会让 Bot 停止接收钉钉消息并拆掉它的连接;安装记录会保留以便审计,之后你可以重新连接。
## 权限
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 2a8e32556c..f6e4cfa7c8 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -157,10 +157,13 @@ import type {
ListSlackInstallationsResponse,
RegisterSlackBYORequest,
RedeemSlackBindingTokenResponse,
+ DingTalkGroupRoute,
DingTalkInstallation,
+ ListDingTalkGroupRoutesResponse,
ListDingTalkInstallationsResponse,
RegisterDingTalkBYORequest,
RedeemDingTalkBindingTokenResponse,
+ UpdateDingTalkGroupRouteRequest,
WecomInstallation,
ListWecomInstallationsResponse,
RegisterWecomBYORequest,
@@ -280,9 +283,13 @@ import {
BillingCheckoutSessionStatusSchema,
CreateBillingPortalSessionResponseSchema,
DingTalkInstallationSchema,
+ DingTalkGroupRouteSchema,
+ ListDingTalkGroupRoutesResponseSchema,
ListDingTalkInstallationsResponseSchema,
RedeemDingTalkBindingTokenResponseSchema,
EMPTY_DINGTALK_INSTALLATION,
+ EMPTY_DINGTALK_GROUP_ROUTE,
+ EMPTY_LIST_DINGTALK_GROUP_ROUTES_RESPONSE,
EMPTY_LIST_DINGTALK_INSTALLATIONS_RESPONSE,
EMPTY_REDEEM_DINGTALK_BINDING_TOKEN_RESPONSE,
WecomInstallationSchema,
@@ -3567,6 +3574,32 @@ export class ApiClient {
);
}
+ async listDingTalkGroupRoutes(
+ workspaceId: string,
+ ): Promise<ListDingTalkGroupRoutesResponse> {
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/dingtalk/group-routes`);
+ return parseWithFallback(
+ raw,
+ ListDingTalkGroupRoutesResponseSchema,
+ EMPTY_LIST_DINGTALK_GROUP_ROUTES_RESPONSE,
+ { endpoint: "GET /api/workspaces/:id/dingtalk/group-routes" },
+ );
+ }
+
+ async updateDingTalkGroupRoute(
+ workspaceId: string,
+ routeId: string,
+ body: UpdateDingTalkGroupRouteRequest,
+ ): Promise<DingTalkGroupRoute> {
+ const raw = await this.fetch<unknown>(
+ `/api/workspaces/${workspaceId}/dingtalk/group-routes/${routeId}`,
+ { method: "PATCH", body: JSON.stringify(body) },
+ );
+ return parseWithFallback(raw, DingTalkGroupRouteSchema, EMPTY_DINGTALK_GROUP_ROUTE, {
+ endpoint: "PATCH /api/workspaces/:id/dingtalk/group-routes/:routeId",
+ });
+ }
+
// registerDingTalkBYO performs a bring-your-own-app install: the admin pastes
// the AppKey (client id) + AppSecret (client secret) of the DingTalk
// Stream-mode robot they created, and the backend validates + persists it,
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index ac77ecd8de..069b56442b 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -315,6 +315,65 @@ describe("ApiClient schema fallback", () => {
expect(res.installations).toHaveLength(1);
expect(res.configured).toBe(true);
expect(res.install_supported).toBeUndefined();
+ expect(res.group_routing_supported).toBeUndefined();
+ });
+
+ it("parses the new-server group-routing capability", async () => {
+ stubFetchJson({
+ installations: [{ id: "dt-1", status: "active" }],
+ configured: true,
+ install_supported: true,
+ group_routing_supported: true,
+ });
+ const client = new ApiClient("https://api.example.test");
+ const res = await client.listDingTalkInstallations("ws-1");
+ expect(res.group_routing_supported).toBe(true);
+ });
+ });
+
+ describe("listDingTalkGroupRoutes", () => {
+ it("falls back to an empty list when the response is malformed", async () => {
+ stubFetchJson({ routes: "not-an-array" });
+ const client = new ApiClient("https://api.example.test");
+ await expect(client.listDingTalkGroupRoutes("ws-1")).resolves.toEqual({ routes: [] });
+ });
+
+ it("defaults fields missing from an older or partial route row", async () => {
+ stubFetchJson({ routes: [{ id: "route-1", agent_id: "agent-2" }] });
+ const client = new ApiClient("https://api.example.test");
+ const res = await client.listDingTalkGroupRoutes("ws-1");
+ expect(res.routes[0]).toMatchObject({
+ id: "route-1",
+ agent_id: "agent-2",
+ conversation_title: "",
+ installation_id: "",
+ });
+ });
+ });
+
+ describe("updateDingTalkGroupRoute", () => {
+ it("falls back safely on a malformed PATCH response and sends the scoped request", async () => {
+ stubFetchJson({ id: 42, agent_id: { wrong: "shape" } });
+ const client = new ApiClient("https://api.example.test");
+ await expect(
+ client.updateDingTalkGroupRoute("ws-1", "route-1", { agent_id: "agent-2" }),
+ ).resolves.toEqual({
+ id: "",
+ workspace_id: "",
+ installation_id: "",
+ conversation_id: "",
+ conversation_title: "",
+ agent_id: "",
+ discovered_at: "",
+ updated_at: "",
+ });
+ expect(vi.mocked(fetch)).toHaveBeenCalledWith(
+ "https://api.example.test/api/workspaces/ws-1/dingtalk/group-routes/route-1",
+ expect.objectContaining({
+ method: "PATCH",
+ body: JSON.stringify({ agent_id: "agent-2" }),
+ }),
+ );
});
});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 0194432bf7..88d0c3ceaf 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -22,7 +22,9 @@ import type {
CreateBillingCheckoutSessionResponse,
CreateBillingPortalSessionResponse,
CronPreviewResponse,
+ DingTalkGroupRoute,
DingTalkInstallation,
+ ListDingTalkGroupRoutesResponse,
ListDingTalkInstallationsResponse,
RedeemDingTalkBindingTokenResponse,
WecomInstallation,
@@ -2129,6 +2131,7 @@ export const ListDingTalkInstallationsResponseSchema = z.object({
installations: z.array(DingTalkInstallationSchema).default([]),
configured: z.boolean().default(false),
install_supported: z.boolean().optional(),
+ group_routing_supported: z.boolean().optional(),
}).loose();
export const EMPTY_LIST_DINGTALK_INSTALLATIONS_RESPONSE: ListDingTalkInstallationsResponse = {
@@ -2136,6 +2139,36 @@ export const EMPTY_LIST_DINGTALK_INSTALLATIONS_RESPONSE: ListDingTalkInstallatio
configured: false,
};
+export const DingTalkGroupRouteSchema = z.object({
+ id: z.string(),
+ workspace_id: z.string().default(""),
+ installation_id: z.string().default(""),
+ conversation_id: z.string().default(""),
+ conversation_title: z.string().default(""),
+ agent_id: z.string().default(""),
+ discovered_at: z.string().default(""),
+ updated_at: z.string().default(""),
+}).loose();
+
+export const EMPTY_DINGTALK_GROUP_ROUTE: DingTalkGroupRoute = {
+ id: "",
+ workspace_id: "",
+ installation_id: "",
+ conversation_id: "",
+ conversation_title: "",
+ agent_id: "",
+ discovered_at: "",
+ updated_at: "",
+};
+
+export const ListDingTalkGroupRoutesResponseSchema = z.object({
+ routes: z.array(DingTalkGroupRouteSchema).default([]),
+}).loose();
+
+export const EMPTY_LIST_DINGTALK_GROUP_ROUTES_RESPONSE: ListDingTalkGroupRoutesResponse = {
+ routes: [],
+};
+
export const RedeemDingTalkBindingTokenResponseSchema = z.object({
workspace_id: z.string().default(""),
installation_id: z.string().default(""),
diff --git a/packages/core/dingtalk/index.ts b/packages/core/dingtalk/index.ts
index 0df1bec842..834291a51f 100644
--- a/packages/core/dingtalk/index.ts
+++ b/packages/core/dingtalk/index.ts
@@ -1 +1,5 @@
-export { dingtalkKeys, dingtalkInstallationsOptions } from "./queries";
+export {
+ dingtalkKeys,
+ dingtalkInstallationsOptions,
+ dingtalkGroupRoutesOptions,
+} from "./queries";
diff --git a/packages/core/dingtalk/queries.ts b/packages/core/dingtalk/queries.ts
index ddec906cf1..62692e454a 100644
--- a/packages/core/dingtalk/queries.ts
+++ b/packages/core/dingtalk/queries.ts
@@ -8,6 +8,7 @@ import { api } from "../api";
export const dingtalkKeys = {
all: (wsId: string) => ["dingtalk", wsId] as const,
installations: (wsId: string) => [...dingtalkKeys.all(wsId), "installations"] as const,
+ groupRoutes: (wsId: string) => [...dingtalkKeys.all(wsId), "group-routes"] as const,
};
export const dingtalkInstallationsOptions = (wsId: string) =>
@@ -16,3 +17,15 @@ export const dingtalkInstallationsOptions = (wsId: string) =>
queryFn: () => api.listDingTalkInstallations(wsId),
enabled: !!wsId,
});
+
+export const dingtalkGroupRoutesOptions = (wsId: string) =>
+ queryOptions({
+ queryKey: dingtalkKeys.groupRoutes(wsId),
+ queryFn: () => api.listDingTalkGroupRoutes(wsId),
+ enabled: !!wsId,
+ // Group discovery is driven by DingTalk Stream callbacks rather than an
+ // HTTP mutation, so poll lightly while the settings panel is open. Stop
+ // after a failed retry cycle: a persistent server error must require an
+ // explicit user retry instead of producing another request every 5s.
+ refetchInterval: (query) => (query.state.status === "error" ? false : 5_000),
+ });
diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
index 0e12856bad..27f4a96836 100644
--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
@@ -11,6 +11,7 @@ import { issueKeys } from "../issues/queries";
import { chatKeys } from "../chat/queries";
import { workspaceWorkingAgentsKeys } from "../agents/queries";
import { workspaceKeys } from "../workspace/queries";
+import { dingtalkKeys } from "../dingtalk/queries";
import {
markWorkspaceDeletePending,
unmarkWorkspaceDeletePending,
@@ -235,6 +236,22 @@ describe("useRealtimeSync — ws instance change", () => {
queryKey: issueKeys.attachments("issue-1"),
});
});
+
+ it("invalidates DingTalk group routes after a route update event", async () => {
+ const ws = createMockWs();
+ renderHook(() => useRealtimeSync(ws, stores), {
+ wrapper: createWrapper(qc),
+ });
+ const onAny = vi.mocked(ws.onAny).mock.calls[0]?.[0];
+ expect(onAny).toBeDefined();
+
+ onAny!({ type: "dingtalk_group_route:updated", payload: {} } as never);
+ await new Promise((resolve) => setTimeout(resolve, 120));
+
+ expect(invalidateSpy).toHaveBeenCalledWith({
+ queryKey: dingtalkKeys.groupRoutes("ws-1"),
+ });
+ });
});
describe("useRealtimeSync — queued chat promotion", () => {
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 32aea87c4f..4623d9cbcd 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -825,6 +825,10 @@ export function useRealtimeSync(
const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: dingtalkKeys.installations(wsId) });
},
+ dingtalk_group_route: () => {
+ const wsId = getCurrentWsId();
+ if (wsId) qc.invalidateQueries({ queryKey: dingtalkKeys.groupRoutes(wsId) });
+ },
vcs_connection: () => {
const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: ["vcs", wsId] });
diff --git a/packages/core/types/dingtalk.ts b/packages/core/types/dingtalk.ts
index 984d8d3952..3184798ff6 100644
--- a/packages/core/types/dingtalk.ts
+++ b/packages/core/types/dingtalk.ts
@@ -1,4 +1,5 @@
-/** A DingTalk robot installation bound to a single Multica agent.
+/** A DingTalk robot installation with one default Multica agent. Group routes
+ * may target other agents without duplicating the installation.
*
* Wire shape mirrors `DingTalkInstallationResponse` in
* `server/internal/handler/dingtalk.go`. New fields the backend adds in the
@@ -27,6 +28,32 @@ export interface ListDingTalkInstallationsResponse {
* compat; optional so an older desktop build that predates it treats it as
* off. */
install_supported?: boolean;
+ /** Whether this backend exposes DingTalk group routing. Optional and gated
+ * with `=== true` so newer Web/Desktop clients do not call a route that an
+ * older or version-skewed backend does not have. */
+ group_routing_supported?: boolean;
+}
+
+/** A DingTalk group observed by one Stream-mode robot and routed to a fixed
+ * Multica agent. Groups are discovered from inbound callbacks; admins can
+ * reassign the agent without reconnecting or duplicating the robot. */
+export interface DingTalkGroupRoute {
+ id: string;
+ workspace_id: string;
+ installation_id: string;
+ conversation_id: string;
+ conversation_title: string;
+ agent_id: string;
+ discovered_at: string;
+ updated_at: string;
+}
+
+export interface ListDingTalkGroupRoutesResponse {
+ routes: DingTalkGroupRoute[];
+}
+
+export interface UpdateDingTalkGroupRouteRequest {
+ agent_id: string;
}
/** Request body for a bring-your-own-app (BYO) install: the AppKey and
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 67e7ac91ec..0b9608f410 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -192,9 +192,12 @@ export type {
} from "./slack";
export type {
DingTalkInstallation,
+ DingTalkGroupRoute,
ListDingTalkInstallationsResponse,
+ ListDingTalkGroupRoutesResponse,
RegisterDingTalkBYORequest,
RedeemDingTalkBindingTokenResponse,
+ UpdateDingTalkGroupRouteRequest,
} from "./dingtalk";
export type {
WecomInstallation,
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index aef16f3ed3..4e0df1a983 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -689,7 +689,24 @@
},
"dingtalk": {
"section_title": "DingTalk",
- "page_description": "Connect each Multica Agent to its own DingTalk robot. Members can DM the bot, @mention it in a group, and type /issue to spin up a new Multica issue.",
+ "page_description": "Connect a DingTalk robot to Multica. Direct messages use its default Agent; each group can route the same robot to a different Agent.",
+ "group_routes_title": "Group routing",
+ "group_routes_description": "Add this robot to multiple DingTalk groups, then @mention it once in each group. Multica discovers the group automatically and routes future messages to the Agent selected here.",
+ "group_routes_empty_title": "No groups discovered yet",
+ "group_routes_empty_description": "Add the connected robot to a DingTalk group and @mention it once. The group will appear here automatically.",
+ "group_routes_error_title": "Could not load group routes",
+ "group_routes_error_description": "Automatic refresh is paused. Check the server and try again.",
+ "group_routes_retry": "Retry",
+ "group_routes_agents_loading": "Loading Agents for group routing…",
+ "group_routes_agents_empty_title": "No eligible Agents",
+ "group_routes_agents_empty_description": "Create or restore an Agent before reassigning DingTalk groups.",
+ "group_routes_agents_error_title": "Could not load Agents",
+ "group_routes_agents_error_description": "Group reassignment is unavailable until the Agent list loads.",
+ "group_routes_agents_retry": "Retry Agents",
+ "group_routes_agent_label": "Agent for this group",
+ "group_routes_unknown_agent": "Unknown Agent",
+ "group_routes_updated": "Group Agent updated",
+ "group_routes_update_failed": "Could not update the Group Agent",
"not_enabled_title": "DingTalk integration not enabled",
"not_enabled_description_prefix": "Set",
"not_enabled_description_suffix": "on the server to enable DingTalk robot installations.",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 4c4b3c2dd6..0a4e1669ab 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -688,7 +688,24 @@
},
"dingtalk": {
"section_title": "DingTalk",
- "page_description": "各 Multica エージェントを専用の DingTalk ロボットに接続します。メンバーはボットに DM したり、グループで @メンションしたり、/issue と入力して新しい Multica イシューを起こすことができます。",
+ "page_description": "DingTalk ロボットを Multica に接続します。DM はデフォルトのエージェントを使用し、同じロボットでもグループごとに別のエージェントへルーティングできます。",
+ "group_routes_title": "グループルーティング",
+ "group_routes_description": "同じロボットを複数の DingTalk グループに追加し、各グループで一度 @メンションしてください。Multica がグループを自動検出し、以後のメッセージをここで選んだエージェントに送ります。",
+ "group_routes_empty_title": "まだグループが検出されていません",
+ "group_routes_empty_description": "接続済みロボットを DingTalk グループに追加し、一度 @メンションしてください。グループが自動的にここへ表示されます。",
+ "group_routes_error_title": "グループルートを読み込めませんでした",
+ "group_routes_error_description": "自動更新を一時停止しました。サーバーを確認して再試行してください。",
+ "group_routes_retry": "再試行",
+ "group_routes_agents_loading": "グループルーティング用のエージェントを読み込み中…",
+ "group_routes_agents_empty_title": "利用可能なエージェントがありません",
+ "group_routes_agents_empty_description": "DingTalk グループを再割り当てする前に、エージェントを作成または復元してください。",
+ "group_routes_agents_error_title": "エージェントを読み込めませんでした",
+ "group_routes_agents_error_description": "エージェント一覧が読み込まれるまで、グループの再割り当ては利用できません。",
+ "group_routes_agents_retry": "エージェントを再読み込み",
+ "group_routes_agent_label": "このグループのエージェント",
+ "group_routes_unknown_agent": "不明なエージェント",
+ "group_routes_updated": "グループのエージェントを更新しました",
+ "group_routes_update_failed": "グループのエージェントを更新できませんでした",
"not_enabled_title": "DingTalk 連携が有効になっていません",
"not_enabled_description_prefix": "サーバーで",
"not_enabled_description_suffix": "を設定すると DingTalk ロボットのインストールが有効になります。",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index e5fbdc799a..5de7e49a7e 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -793,7 +793,24 @@
},
"dingtalk": {
"section_title": "DingTalk",
- "page_description": "각 Multica 에이전트를 전용 DingTalk 로봇에 연결하세요. 멤버는 봇과 1:1로 대화하거나, 그룹에서 @ 멘션하거나, /issue 를 입력해 새 Multica 이슈를 만들 수 있습니다.",
+ "page_description": "DingTalk 로봇을 Multica에 연결하세요. DM은 기본 에이전트를 사용하고, 같은 로봇이라도 그룹마다 다른 에이전트로 라우팅할 수 있습니다.",
+ "group_routes_title": "그룹 라우팅",
+ "group_routes_description": "같은 로봇을 여러 DingTalk 그룹에 추가하고 각 그룹에서 한 번 @ 멘션하세요. Multica가 그룹을 자동으로 찾고 이후 메시지를 여기에서 선택한 에이전트로 보냅니다.",
+ "group_routes_empty_title": "아직 발견된 그룹이 없어요",
+ "group_routes_empty_description": "연결된 로봇을 DingTalk 그룹에 추가하고 한 번 @ 멘션하세요. 그룹이 여기에 자동으로 표시됩니다.",
+ "group_routes_error_title": "그룹 경로를 불러오지 못했어요",
+ "group_routes_error_description": "자동 새로고침을 일시 중지했어요. 서버를 확인한 후 다시 시도하세요.",
+ "group_routes_retry": "다시 시도",
+ "group_routes_agents_loading": "그룹 라우팅에 사용할 에이전트를 불러오는 중이에요…",
+ "group_routes_agents_empty_title": "사용 가능한 에이전트가 없어요",
+ "group_routes_agents_empty_description": "DingTalk 그룹을 다시 할당하기 전에 에이전트를 만들거나 복원하세요.",
+ "group_routes_agents_error_title": "에이전트를 불러오지 못했어요",
+ "group_routes_agents_error_description": "에이전트 목록을 불러올 때까지 그룹 재할당을 사용할 수 없어요.",
+ "group_routes_agents_retry": "에이전트 다시 불러오기",
+ "group_routes_agent_label": "이 그룹의 에이전트",
+ "group_routes_unknown_agent": "알 수 없는 에이전트",
+ "group_routes_updated": "그룹 에이전트를 업데이트했어요",
+ "group_routes_update_failed": "그룹 에이전트를 업데이트하지 못했어요",
"not_enabled_title": "DingTalk 연동이 활성화되지 않았어요",
"not_enabled_description_prefix": "서버에서",
"not_enabled_description_suffix": "를 설정하면 DingTalk 로봇 설치가 활성화됩니다.",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index ff5892e522..d7ba8c57d4 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -688,7 +688,24 @@
},
"dingtalk": {
"section_title": "钉钉",
- "page_description": "将每个 Multica 智能体连接到专属的钉钉机器人。成员可私聊机器人、在群里 @ 它,或输入 /issue 直接创建 Multica issue。",
+ "page_description": "将钉钉机器人连接到 Multica。私聊使用机器人的默认智能体;同一个机器人在不同群里可分别绑定不同智能体。",
+ "group_routes_title": "群路由",
+ "group_routes_description": "将同一个机器人加入多个钉钉群,并在每个群里 @ 它一次。Multica 会自动发现群聊,后续消息将交给这里选择的智能体。",
+ "group_routes_empty_title": "尚未发现群聊",
+ "group_routes_empty_description": "将已连接的机器人加入钉钉群,并 @ 它一次。该群会自动显示在这里。",
+ "group_routes_error_title": "无法加载群路由",
+ "group_routes_error_description": "自动刷新已暂停。请检查服务器后重试。",
+ "group_routes_retry": "重试",
+ "group_routes_agents_loading": "正在加载群路由可用的智能体…",
+ "group_routes_agents_empty_title": "没有可用的智能体",
+ "group_routes_agents_empty_description": "请先创建或恢复智能体,再重新分配钉钉群。",
+ "group_routes_agents_error_title": "无法加载智能体",
+ "group_routes_agents_error_description": "加载智能体列表前,群路由重新分配不可用。",
+ "group_routes_agents_retry": "重试加载智能体",
+ "group_routes_agent_label": "此群绑定的智能体",
+ "group_routes_unknown_agent": "未知智能体",
+ "group_routes_updated": "已更新群智能体",
+ "group_routes_update_failed": "无法更新群智能体",
"not_enabled_title": "钉钉集成未启用",
"not_enabled_description_prefix": "在服务器上设置",
"not_enabled_description_suffix": "以启用钉钉机器人安装。",
diff --git a/packages/views/settings/components/dingtalk-tab.group-routes-error.test.tsx b/packages/views/settings/components/dingtalk-tab.group-routes-error.test.tsx
new file mode 100644
index 0000000000..fc3f8db3a6
--- /dev/null
+++ b/packages/views/settings/components/dingtalk-tab.group-routes-error.test.tsx
@@ -0,0 +1,403 @@
+// @vitest-environment jsdom
+
+import { type ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { QueryClientProvider } from "@tanstack/react-query";
+import { I18nProvider } from "@multica/core/i18n/react";
+import { createQueryClient } from "@multica/core/query-client";
+import { setApiInstance } from "@multica/core/api";
+import type { ApiClient } from "@multica/core/api/client";
+import { dingtalkKeys } from "@multica/core/dingtalk";
+import enCommon from "../../locales/en/common.json";
+import enSettings from "../../locales/en/settings.json";
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
+
+const agentListQueryFn = vi.hoisted(() => vi.fn());
+const memberListQueryFn = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/workspace/queries", () => ({
+ memberListOptions: () => ({
+ queryKey: ["members", "workspace-1"],
+ queryFn: memberListQueryFn,
+ }),
+ agentListOptions: () => ({
+ queryKey: ["agents", "workspace-1"],
+ queryFn: agentListQueryFn,
+ }),
+}));
+
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({
+ getAgentName: () => "Agent One",
+ getMemberName: () => "Unknown",
+ getSquadName: () => "Unknown Squad",
+ getActorName: () => "Unknown",
+ getActorInitials: () => "??",
+ getActorAvatarUrl: () => null,
+ }),
+}));
+
+vi.mock("@multica/core/auth", () => {
+ const useAuthStore = Object.assign(
+ (select?: (state: { user: { id: string } }) => unknown) =>
+ select ? select({ user: { id: "user-1" } }) : { user: { id: "user-1" } },
+ { getState: () => ({ user: { id: "user-1" } }) },
+ );
+ return { useAuthStore };
+});
+
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: () => <span data-testid="actor-avatar" />,
+}));
+
+vi.mock("../../platform", () => ({ openExternal: vi.fn() }));
+vi.mock("sonner", () => ({
+ toast: { success: vi.fn(), error: vi.fn(), message: vi.fn() },
+}));
+
+import { DingTalkTab } from "./dingtalk-tab";
+
+const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+beforeEach(() => {
+ agentListQueryFn.mockReset();
+ agentListQueryFn.mockResolvedValue([
+ { id: "agent-1", name: "Agent One", archived_at: null },
+ ]);
+ memberListQueryFn.mockReset();
+ memberListQueryFn.mockResolvedValue([{ user_id: "user-1", role: "owner" }]);
+});
+
+function renderUI(children: ReactNode) {
+ return render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ {children}
+ </I18nProvider>,
+ );
+}
+
+const ACTIVE_INSTALLATION_RESPONSE = {
+ configured: true,
+ install_supported: true,
+ group_routing_supported: true,
+ installations: [
+ {
+ id: "installation-1",
+ agent_id: "agent-1",
+ status: "active",
+ installed_at: "2026-08-11T00:00:00Z",
+ },
+ ],
+};
+
+const REVOKED_INSTALLATION_RESPONSE = {
+ configured: true,
+ install_supported: true,
+ group_routing_supported: true,
+ installations: [
+ {
+ id: "installation-1",
+ agent_id: "agent-1",
+ status: "revoked",
+ installed_at: "2026-08-11T00:00:00Z",
+ },
+ ],
+};
+
+const ACTIVE_GROUP_ROUTE_RESPONSE = {
+ routes: [
+ {
+ id: "route-1",
+ installation_id: "installation-1",
+ conversation_id: "cid-platform",
+ conversation_title: "Platform team",
+ agent_id: "agent-1",
+ revision: 1,
+ discovered_at: "2026-08-11T00:00:00Z",
+ updated_at: "2026-08-11T00:00:00Z",
+ },
+ ],
+};
+
+type InstallationResponse = {
+ configured: boolean;
+ install_supported: boolean;
+ group_routing_supported?: boolean;
+ installations: Array<{
+ id: string;
+ agent_id: string;
+ status: string;
+ installed_at: string;
+ }>;
+};
+
+function installApi({
+ installations = ACTIVE_INSTALLATION_RESPONSE,
+ listDingTalkGroupRoutes = vi.fn().mockResolvedValue(ACTIVE_GROUP_ROUTE_RESPONSE),
+}: {
+ installations?: InstallationResponse;
+ listDingTalkGroupRoutes?: ReturnType<typeof vi.fn>;
+} = {}) {
+ const listDingTalkInstallations = vi.fn().mockResolvedValue(installations);
+ setApiInstance({
+ listDingTalkInstallations,
+ listDingTalkGroupRoutes,
+ deleteDingTalkInstallation: vi.fn(),
+ updateDingTalkGroupRoute: vi.fn(),
+ } as unknown as ApiClient);
+ return { listDingTalkInstallations, listDingTalkGroupRoutes };
+}
+
+function renderTab() {
+ const queryClient = createQueryClient();
+ renderUI(
+ <QueryClientProvider client={queryClient}>
+ <DingTalkTab />
+ </QueryClientProvider>,
+ );
+ return queryClient;
+}
+
+describe("DingTalkTab group-route query failures", () => {
+ it("stops five-second polling on persistent failure, hides the empty state, and retries only on demand", async () => {
+ vi.useFakeTimers();
+ const listDingTalkGroupRoutes = vi.fn().mockRejectedValue(new Error("persistent 500"));
+ installApi({ listDingTalkGroupRoutes });
+ const queryClient = renderTab();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(listDingTalkGroupRoutes).toHaveBeenCalledTimes(1);
+
+ // The shared QueryClient permits exactly one automatic retry.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1_001);
+ });
+ expect(listDingTalkGroupRoutes).toHaveBeenCalledTimes(2);
+ expect(screen.getByText("Could not load group routes")).toBeTruthy();
+ expect(screen.queryByText("No groups discovered yet")).toBeNull();
+
+ // Once the query is errored, advancing well beyond repeated five-second
+ // intervals must not issue any background requests.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+ expect(listDingTalkGroupRoutes).toHaveBeenCalledTimes(2);
+
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1_001);
+ });
+ expect(listDingTalkGroupRoutes).toHaveBeenCalledTimes(4);
+
+ queryClient.clear();
+ });
+
+ it("keeps routes visible while Agents load and disables reassignment", async () => {
+ vi.useFakeTimers();
+ agentListQueryFn.mockImplementation(() => new Promise(() => {}));
+ installApi();
+ const queryClient = renderTab();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+
+ expect(screen.getByText("Loading Agents for group routing…")).toBeTruthy();
+ expect(screen.getByText("Platform team")).toBeTruthy();
+ expect(screen.getByText("cid-platform")).toBeTruthy();
+ expect(screen.queryByText("No eligible Agents")).toBeNull();
+ expect(screen.getByRole("combobox", { name: "Agent for this group" })).toBeDisabled();
+ queryClient.clear();
+ });
+
+ it("keeps routes visible on Agent failure and disables reassignment", async () => {
+ vi.useFakeTimers();
+ agentListQueryFn.mockRejectedValue(new Error("agents unavailable"));
+ installApi();
+ const queryClient = renderTab();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1_001);
+ });
+
+ expect(screen.getByText("Could not load Agents")).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Retry Agents" })).toBeTruthy();
+ expect(screen.getByText("Platform team")).toBeTruthy();
+ expect(screen.getByText("cid-platform")).toBeTruthy();
+ expect(screen.queryByText("No eligible Agents")).toBeNull();
+ expect(screen.getByRole("combobox", { name: "Agent for this group" })).toBeDisabled();
+ queryClient.clear();
+ });
+
+ it("keeps routes visible for a successfully-loaded empty Agent list", async () => {
+ vi.useFakeTimers();
+ agentListQueryFn.mockResolvedValue([]);
+ installApi();
+ const queryClient = renderTab();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+
+ expect(screen.getByText("No eligible Agents")).toBeTruthy();
+ expect(screen.getByText("Platform team")).toBeTruthy();
+ expect(screen.getByText("cid-platform")).toBeTruthy();
+ expect(screen.queryByText("Loading Agents for group routing…")).toBeNull();
+ expect(screen.queryByText("Could not load Agents")).toBeNull();
+ expect(screen.getByRole("combobox", { name: "Agent for this group" })).toBeDisabled();
+ queryClient.clear();
+ });
+
+ it("recovers the Agent selector after an explicit retry succeeds", async () => {
+ vi.useFakeTimers();
+ agentListQueryFn
+ .mockRejectedValueOnce(new Error("agents unavailable"))
+ .mockRejectedValueOnce(new Error("agents unavailable"))
+ .mockResolvedValueOnce([
+ { id: "agent-1", name: "Agent One", archived_at: null },
+ ]);
+ installApi();
+ const queryClient = renderTab();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1_001);
+ });
+ expect(screen.getByText("Could not load Agents")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("button", { name: "Retry Agents" }));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+
+ expect(screen.queryByText("Could not load Agents")).toBeNull();
+ expect(screen.getByRole("combobox", { name: "Agent for this group" })).not.toBeDisabled();
+ queryClient.clear();
+ });
+
+ it("keeps a route visible when its assigned Agent is archived", async () => {
+ vi.useFakeTimers();
+ agentListQueryFn.mockResolvedValue([
+ { id: "agent-1", name: "Agent One", archived_at: "2026-08-11T00:00:00Z" },
+ ]);
+ installApi();
+ const queryClient = renderTab();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+
+ expect(screen.getByText("Platform team")).toBeTruthy();
+ expect(screen.getAllByText("Agent One").length).toBeGreaterThan(0);
+ expect(screen.getByText("No eligible Agents")).toBeTruthy();
+ expect(screen.getByRole("combobox", { name: "Agent for this group" })).toBeDisabled();
+ queryClient.clear();
+ });
+
+ it("keeps a route visible for a member who cannot see its assigned private Agent", async () => {
+ vi.useFakeTimers();
+ memberListQueryFn.mockResolvedValue([{ user_id: "user-1", role: "member" }]);
+ agentListQueryFn.mockResolvedValue([]);
+ installApi();
+ const queryClient = renderTab();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+
+ expect(screen.getByText("Platform team")).toBeTruthy();
+ expect(screen.getByText("cid-platform")).toBeTruthy();
+ expect(screen.getByText("Unknown Agent")).toBeTruthy();
+ expect(screen.queryByRole("combobox", { name: "Agent for this group" })).toBeNull();
+ queryClient.clear();
+ });
+
+ it("treats an older backend without the group-routing capability as unsupported", async () => {
+ vi.useFakeTimers();
+ const listDingTalkGroupRoutes = vi.fn().mockRejectedValue(new Error("older backend 404"));
+ installApi({
+ installations: {
+ configured: true,
+ install_supported: true,
+ installations: ACTIVE_INSTALLATION_RESPONSE.installations,
+ },
+ listDingTalkGroupRoutes,
+ });
+ const queryClient = renderTab();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+
+ expect(listDingTalkGroupRoutes).not.toHaveBeenCalled();
+ expect(screen.queryByText("Could not load group routes")).toBeNull();
+ expect(screen.queryByText("No groups discovered yet")).toBeNull();
+ expect(screen.queryByText("Group routing")).toBeNull();
+ queryClient.clear();
+ });
+
+ it("requests group routes when the new backend advertises support", async () => {
+ vi.useFakeTimers();
+ const listDingTalkGroupRoutes = vi.fn().mockResolvedValue(ACTIVE_GROUP_ROUTE_RESPONSE);
+ installApi({ listDingTalkGroupRoutes });
+ const queryClient = renderTab();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+
+ expect(listDingTalkGroupRoutes).toHaveBeenCalledTimes(1);
+ expect(screen.getByText("Platform team")).toBeTruthy();
+ queryClient.clear();
+ });
+
+ it("does not request group routes when every installation is revoked", async () => {
+ vi.useFakeTimers();
+ const listDingTalkGroupRoutes = vi.fn().mockResolvedValue(ACTIVE_GROUP_ROUTE_RESPONSE);
+ installApi({
+ installations: REVOKED_INSTALLATION_RESPONSE,
+ listDingTalkGroupRoutes,
+ });
+ const queryClient = renderTab();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+
+ expect(listDingTalkGroupRoutes).not.toHaveBeenCalled();
+ expect(screen.queryByText("Group routing")).toBeNull();
+ queryClient.clear();
+ });
+
+ it("stops group-route polling when the last active installation is revoked", async () => {
+ vi.useFakeTimers();
+ const listDingTalkGroupRoutes = vi.fn().mockResolvedValue(ACTIVE_GROUP_ROUTE_RESPONSE);
+ installApi({ listDingTalkGroupRoutes });
+ const queryClient = renderTab();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(listDingTalkGroupRoutes).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ queryClient.setQueryData(
+ dingtalkKeys.installations("workspace-1"),
+ REVOKED_INSTALLATION_RESPONSE,
+ );
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+
+ expect(listDingTalkGroupRoutes).toHaveBeenCalledTimes(1);
+ expect(screen.queryByText("Group routing")).toBeNull();
+ queryClient.clear();
+ });
+});
diff --git a/packages/views/settings/components/dingtalk-tab.test.tsx b/packages/views/settings/components/dingtalk-tab.test.tsx
index 967571fdfc..08883fa5a8 100644
--- a/packages/views/settings/components/dingtalk-tab.test.tsx
+++ b/packages/views/settings/components/dingtalk-tab.test.tsx
@@ -18,18 +18,42 @@ const installationsRef = vi.hoisted(() => ({
installations: [] as unknown[],
configured: true,
install_supported: true,
+ group_routing_supported: true,
},
}));
+const agentsRef = vi.hoisted(() => ({
+ current: [
+ { id: "agent-1", name: "Agent One", archived_at: null },
+ { id: "agent-2", name: "Agent Two", archived_at: null },
+ ] as Array<{ id: string; name: string; archived_at: string | null }>,
+}));
+const groupRoutesRef = vi.hoisted(() => ({
+ current: { routes: [] as unknown[] },
+}));
const mockRegisterBYO = vi.hoisted(() => vi.fn());
const mockDeleteInstallation = vi.hoisted(() => vi.fn());
+const mockUpdateGroupRoute = vi.hoisted(() => vi.fn());
const mockOpenExternal = vi.hoisted(() => vi.fn());
const mockInvalidate = vi.hoisted(() => vi.fn());
+const mockToastSuccess = vi.hoisted(() => vi.fn());
+const mockToastError = vi.hoisted(() => vi.fn());
vi.mock("@tanstack/react-query", () => ({
useQuery: (opts: { queryKey: unknown[]; enabled?: boolean }) => {
if (opts.enabled === false) return { data: undefined, isLoading: false };
const key = JSON.stringify(opts.queryKey);
if (key.includes("members")) return { data: membersRef.current, isLoading: false };
+ if (key.includes("agents")) {
+ return {
+ data: agentsRef.current,
+ isLoading: false,
+ isError: false,
+ isFetching: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ };
+ }
+ if (key.includes("group-routes")) return { data: groupRoutesRef.current, isLoading: false };
if (key.includes("installations")) return { data: installationsRef.current, isLoading: false };
return { data: undefined, isLoading: false };
},
@@ -41,6 +65,7 @@ vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
vi.mock("@multica/core/workspace/queries", () => ({
memberListOptions: () => ({ queryKey: ["members"], queryFn: vi.fn() }),
+ agentListOptions: () => ({ queryKey: ["agents"], queryFn: vi.fn() }),
}));
vi.mock("@multica/core/workspace/hooks", () => ({
@@ -65,13 +90,21 @@ vi.mock("@multica/core/dingtalk", () => ({
queryKey: ["dingtalk", "installations"],
queryFn: vi.fn(),
}),
- dingtalkKeys: { installations: (wsId: string) => ["dingtalk", "installations", wsId] },
+ dingtalkGroupRoutesOptions: () => ({
+ queryKey: ["dingtalk", "group-routes"],
+ queryFn: vi.fn(),
+ }),
+ dingtalkKeys: {
+ installations: (wsId: string) => ["dingtalk", "installations", wsId],
+ groupRoutes: (wsId: string) => ["dingtalk", "group-routes", wsId],
+ },
}));
vi.mock("@multica/core/api", () => ({
api: {
registerDingTalkBYO: mockRegisterBYO,
deleteDingTalkInstallation: mockDeleteInstallation,
+ updateDingTalkGroupRoute: mockUpdateGroupRoute,
},
}));
@@ -85,7 +118,7 @@ vi.mock("@multica/core/auth", () => {
});
vi.mock("sonner", () => ({
- toast: { success: vi.fn(), error: vi.fn(), message: vi.fn() },
+ toast: { success: mockToastSuccess, error: mockToastError, message: vi.fn() },
}));
vi.mock("../../platform", () => ({ openExternal: mockOpenExternal }));
@@ -107,7 +140,35 @@ function renderUI(children: ReactNode) {
function resetFixtures() {
vi.clearAllMocks();
membersRef.current = [{ user_id: "user-1", role: "owner" }];
- installationsRef.current = { installations: [], configured: true, install_supported: true };
+ installationsRef.current = {
+ installations: [],
+ configured: true,
+ install_supported: true,
+ group_routing_supported: true,
+ };
+ agentsRef.current = [
+ { id: "agent-1", name: "Agent One", archived_at: null },
+ { id: "agent-2", name: "Agent Two", archived_at: null },
+ ];
+ groupRoutesRef.current = { routes: [] };
+}
+
+function setConnectedGroupRoute() {
+ installationsRef.current = {
+ installations: [{ id: "i1", agent_id: "agent-1", status: "active" }],
+ configured: true,
+ install_supported: true,
+ group_routing_supported: true,
+ };
+ groupRoutesRef.current = {
+ routes: [{
+ id: "route-1",
+ installation_id: "i1",
+ conversation_id: "cid-platform",
+ conversation_title: "Platform team",
+ agent_id: "agent-2",
+ }],
+ };
}
describe("DingTalkAgentBindButton", () => {
@@ -150,6 +211,7 @@ describe("DingTalkAgentBindButton", () => {
installations: [{ id: "i1", agent_id: "agent-1", status: "active" }],
configured: true,
install_supported: true,
+ group_routing_supported: true,
};
renderUI(<DingTalkAgentBindButton agentId="agent-1" />);
expect(screen.getByTestId("dingtalk-agent-bot-connected")).toBeTruthy();
@@ -164,7 +226,12 @@ describe("DingTalkAgentBindButton", () => {
});
it("renders nothing when install is unavailable and the agent is unbound", () => {
- installationsRef.current = { installations: [], configured: true, install_supported: false };
+ installationsRef.current = {
+ installations: [],
+ configured: true,
+ install_supported: false,
+ group_routing_supported: true,
+ };
const { container } = renderUI(<DingTalkAgentBindButton agentId="agent-1" />);
expect(container).toBeEmptyDOMElement();
});
@@ -174,7 +241,12 @@ describe("DingTalkTab", () => {
beforeEach(resetFixtures);
it("surfaces the not-enabled notice when the deployment has no DingTalk key", () => {
- installationsRef.current = { installations: [], configured: false, install_supported: false };
+ installationsRef.current = {
+ installations: [],
+ configured: false,
+ install_supported: false,
+ group_routing_supported: false,
+ };
renderUI(<DingTalkTab />);
expect(screen.getByText(/DingTalk integration not enabled/i)).toBeTruthy();
});
@@ -189,6 +261,7 @@ describe("DingTalkTab", () => {
installations: [{ id: "i1", agent_id: "agent-7", status: "active" }],
configured: true,
install_supported: true,
+ group_routing_supported: true,
};
renderUI(<DingTalkTab />);
expect(screen.getByText("Agent agent-7")).toBeTruthy();
@@ -203,8 +276,109 @@ describe("DingTalkTab", () => {
],
configured: true,
install_supported: true,
+ group_routing_supported: true,
};
renderUI(<DingTalkTab />);
expect(screen.queryByText(/Invalid Date/i)).toBeNull();
});
+
+ it("lists a discovered group with its fixed Agent", () => {
+ setConnectedGroupRoute();
+ renderUI(<DingTalkTab />);
+ expect(screen.getByText("Platform team")).toBeTruthy();
+ expect(screen.getByText("cid-platform")).toBeTruthy();
+ expect(screen.getByText("Agent Two")).toBeTruthy();
+ });
+
+ it("lets an owner reassign a group and invalidates the route query", async () => {
+ setConnectedGroupRoute();
+ mockUpdateGroupRoute.mockResolvedValue({ id: "route-1", agent_id: "agent-1" });
+ const user = userEvent.setup();
+ renderUI(<DingTalkTab />);
+
+ await user.click(screen.getByRole("combobox", { name: "Agent for this group" }));
+ await user.click(await screen.findByRole("option", { name: "Agent One" }));
+
+ await waitFor(() => {
+ expect(mockUpdateGroupRoute).toHaveBeenCalledWith(
+ "workspace-1",
+ "route-1",
+ { agent_id: "agent-1" },
+ );
+ });
+ expect(mockInvalidate).toHaveBeenCalledWith({
+ queryKey: ["dingtalk", "group-routes", "workspace-1"],
+ });
+ expect(mockToastSuccess).toHaveBeenCalled();
+ });
+
+ it("disables every route selector while one route update is pending", async () => {
+ setConnectedGroupRoute();
+ groupRoutesRef.current = {
+ routes: [
+ ...groupRoutesRef.current.routes,
+ {
+ id: "route-2",
+ installation_id: "i1",
+ conversation_id: "cid-security",
+ conversation_title: "Security team",
+ agent_id: "agent-2",
+ },
+ ],
+ };
+ mockUpdateGroupRoute.mockImplementation(() => new Promise(() => {}));
+ const user = userEvent.setup();
+ renderUI(<DingTalkTab />);
+
+ const selectors = screen.getAllByRole("combobox", { name: "Agent for this group" });
+ expect(selectors).toHaveLength(2);
+ await user.click(selectors[0]!);
+ await user.click(await screen.findByRole("option", { name: "Agent One" }));
+
+ await waitFor(() => expect(mockUpdateGroupRoute).toHaveBeenCalledTimes(1));
+ const pendingSelectors = screen.getAllByRole("combobox", { name: "Agent for this group" });
+ expect(pendingSelectors[0]).toBeDisabled();
+ expect(pendingSelectors[1]).toBeDisabled();
+ });
+
+ it("renders group routing read-only for a non-manager", () => {
+ setConnectedGroupRoute();
+ membersRef.current = [{ user_id: "user-1", role: "member" }];
+ renderUI(<DingTalkTab />);
+
+ expect(screen.getByText("Agent Two")).toBeTruthy();
+ expect(
+ screen.queryByRole("combobox", { name: "Agent for this group" }),
+ ).toBeNull();
+ });
+
+ it("keeps the assigned agent name visible while that agent is archived", () => {
+ setConnectedGroupRoute();
+ agentsRef.current = [
+ { id: "agent-1", name: "Agent One", archived_at: null },
+ { id: "agent-2", name: "Agent Two", archived_at: "2026-08-10T00:00:00Z" },
+ ];
+ renderUI(<DingTalkTab />);
+
+ expect(
+ screen.getByRole("combobox", { name: "Agent for this group" }).textContent,
+ ).toContain("Agent Two");
+ });
+
+ it("reports reassignment failures without invalidating successful data", async () => {
+ setConnectedGroupRoute();
+ mockUpdateGroupRoute.mockRejectedValue(new Error("route update failed"));
+ const user = userEvent.setup();
+ renderUI(<DingTalkTab />);
+
+ await user.click(screen.getByRole("combobox", { name: "Agent for this group" }));
+ await user.click(await screen.findByRole("option", { name: "Agent One" }));
+
+ await waitFor(() => {
+ expect(mockToastError).toHaveBeenCalledWith("route update failed");
+ });
+ expect(mockInvalidate).not.toHaveBeenCalledWith({
+ queryKey: ["dingtalk", "group-routes", "workspace-1"],
+ });
+ });
});
diff --git a/packages/views/settings/components/dingtalk-tab.tsx b/packages/views/settings/components/dingtalk-tab.tsx
index 506ab64518..06f0d97f13 100644
--- a/packages/views/settings/components/dingtalk-tab.tsx
+++ b/packages/views/settings/components/dingtalk-tab.tsx
@@ -15,6 +15,13 @@ import {
} from "@multica/ui/components/ui/dialog";
import { Input } from "@multica/ui/components/ui/input";
import { Label } from "@multica/ui/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@multica/ui/components/ui/select";
import {
AlertDialog,
AlertDialogAction,
@@ -27,12 +34,16 @@ import {
} from "@multica/ui/components/ui/alert-dialog";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
-import { memberListOptions } from "@multica/core/workspace/queries";
+import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";
import { DingTalkMark } from "./dingtalk-mark";
import { useActorName } from "@multica/core/workspace/hooks";
-import { dingtalkInstallationsOptions, dingtalkKeys } from "@multica/core/dingtalk";
+import {
+ dingtalkGroupRoutesOptions,
+ dingtalkInstallationsOptions,
+ dingtalkKeys,
+} from "@multica/core/dingtalk";
import { api } from "@multica/core/api";
-import type { DingTalkInstallation } from "@multica/core/types";
+import type { DingTalkGroupRoute, DingTalkInstallation } from "@multica/core/types";
import { ActorAvatar } from "../../common/actor-avatar";
import { openExternal } from "../../platform";
import { useT } from "../../i18n";
@@ -52,9 +63,10 @@ function formatInstalledAt(value: string): string {
// enforces it; the UI hides the button for non-admins to match).
//
// Adding a new installation flows through the Agent detail page: the install
-// path is per-agent (each Multica agent gets exactly one robot — the
-// (workspace_id, agent_id, channel_type) UNIQUE in channel_installation), so
-// asking the user to pick an agent here would re-create that page's picker.
+// path selects the robot's default agent (the installation still owns one
+// Stream connection). Additional group-specific agents are managed below via
+// group routing, so asking the user to pick an installation here would
+// re-create the Agent page's picker.
export function DingTalkTab() {
const { t } = useT("settings");
const wsId = useWorkspaceId();
@@ -62,6 +74,14 @@ export function DingTalkTab() {
const user = useAuthStore((s) => s.user);
const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const {
+ data: agents,
+ isLoading: agentsLoading,
+ isError: agentsError,
+ isFetching: agentsFetching,
+ isSuccess: agentsLoaded,
+ refetch: retryAgents,
+ } = useQuery(agentListOptions(wsId));
const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
const canManage =
currentMember?.role === "owner" || currentMember?.role === "admin";
@@ -71,9 +91,26 @@ export function DingTalkTab() {
});
const installations = data?.installations ?? [];
const configured = data?.configured === true;
+ const groupRoutingSupported = data?.group_routing_supported === true;
+ const hasActiveInstallation = installations.some(
+ (installation) => installation.status === "active",
+ );
+ const {
+ data: groupRouteData,
+ isLoading: routesLoading,
+ isError: routesError,
+ isFetching: routesFetching,
+ refetch: retryGroupRoutes,
+ } = useQuery({
+ ...dingtalkGroupRoutesOptions(wsId),
+ enabled: configured && groupRoutingSupported && hasActiveInstallation && !!wsId,
+ });
+ const groupRoutes = groupRouteData?.routes ?? [];
+ const activeAgents = (agents ?? []).filter((agent) => !agent.archived_at);
const [disconnectTarget, setDisconnectTarget] = useState<string | null>(null);
const [disconnecting, setDisconnecting] = useState(false);
+ const [updatingRouteId, setUpdatingRouteId] = useState<string | null>(null);
async function handleDisconnect() {
if (!disconnectTarget || disconnecting) return;
@@ -92,6 +129,22 @@ export function DingTalkTab() {
}
}
+ async function handleRouteAgentChange(route: DingTalkGroupRoute, agentId: string) {
+ if (!canManage || !agentsLoaded || updatingRouteId || route.agent_id === agentId) return;
+ setUpdatingRouteId(route.id);
+ try {
+ await api.updateDingTalkGroupRoute(wsId, route.id, { agent_id: agentId });
+ await qc.invalidateQueries({ queryKey: dingtalkKeys.groupRoutes(wsId) });
+ toast.success(t(($) => $.dingtalk.group_routes_updated));
+ } catch (e) {
+ toast.error(
+ e instanceof Error ? e.message : t(($) => $.dingtalk.group_routes_update_failed),
+ );
+ } finally {
+ setUpdatingRouteId(null);
+ }
+ }
+
return (
<div className="space-y-8">
{!configured ? (
@@ -145,6 +198,114 @@ export function DingTalkTab() {
</section>
)}
+ {configured && groupRoutingSupported && hasActiveInstallation && (
+ <section className="space-y-3">
+ <div className="space-y-1">
+ <h2 className="text-body font-semibold">
+ {t(($) => $.dingtalk.group_routes_title)}
+ </h2>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.dingtalk.group_routes_description)}
+ </p>
+ </div>
+ {routesLoading ? (
+ <Card>
+ <CardContent>
+ <p className="text-body text-muted-foreground">
+ {t(($) => $.dingtalk.loading)}
+ </p>
+ </CardContent>
+ </Card>
+ ) : routesError ? (
+ <Card>
+ <CardContent className="space-y-3" role="alert">
+ <div className="space-y-1">
+ <p className="text-body font-medium">
+ {t(($) => $.dingtalk.group_routes_error_title)}
+ </p>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.dingtalk.group_routes_error_description)}
+ </p>
+ </div>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={routesFetching}
+ onClick={() => void retryGroupRoutes()}
+ >
+ {t(($) => $.dingtalk.group_routes_retry)}
+ </Button>
+ </CardContent>
+ </Card>
+ ) : groupRoutes.length === 0 ? (
+ <Card>
+ <CardContent className="space-y-1">
+ <p className="text-body font-medium">
+ {t(($) => $.dingtalk.group_routes_empty_title)}
+ </p>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.dingtalk.group_routes_empty_description)}
+ </p>
+ </CardContent>
+ </Card>
+ ) : (
+ <Card>
+ <CardContent className="divide-y">
+ {agentsLoading ? (
+ <div className="pb-3">
+ <p className="text-body text-muted-foreground">
+ {t(($) => $.dingtalk.group_routes_agents_loading)}
+ </p>
+ </div>
+ ) : agentsError ? (
+ <div className="space-y-3 pb-3" role="alert">
+ <div className="space-y-1">
+ <p className="text-body font-medium">
+ {t(($) => $.dingtalk.group_routes_agents_error_title)}
+ </p>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.dingtalk.group_routes_agents_error_description)}
+ </p>
+ </div>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={agentsFetching}
+ onClick={() => void retryAgents()}
+ >
+ {t(($) => $.dingtalk.group_routes_agents_retry)}
+ </Button>
+ </div>
+ ) : agentsLoaded && activeAgents.length === 0 ? (
+ <div className="space-y-1 pb-3">
+ <p className="text-body font-medium">
+ {t(($) => $.dingtalk.group_routes_agents_empty_title)}
+ </p>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.dingtalk.group_routes_agents_empty_description)}
+ </p>
+ </div>
+ ) : null}
+ {groupRoutes.map((route) => (
+ <GroupRouteRow
+ key={route.id}
+ route={route}
+ agents={activeAgents}
+ selectedAgentName={agents?.find((agent) => agent.id === route.agent_id)?.name}
+ canManage={canManage}
+ selectorAvailable={agentsLoaded && activeAgents.length > 0}
+ updating={updatingRouteId !== null}
+ onAgentChange={(agentId) => handleRouteAgentChange(route, agentId)}
+ />
+ ))}
+ </CardContent>
+ </Card>
+ )}
+ </section>
+ )}
+
<AlertDialog
open={!!disconnectTarget}
onOpenChange={(v) => {
@@ -176,6 +337,70 @@ export function DingTalkTab() {
);
}
+function GroupRouteRow({
+ route,
+ agents,
+ selectedAgentName,
+ canManage,
+ selectorAvailable,
+ updating,
+ onAgentChange,
+}: {
+ route: DingTalkGroupRoute;
+ agents: Array<{ id: string; name: string }>;
+ selectedAgentName?: string;
+ canManage: boolean;
+ selectorAvailable: boolean;
+ updating: boolean;
+ onAgentChange: (agentId: string) => void;
+}) {
+ const { t } = useT("settings");
+ const title = route.conversation_title || route.conversation_id;
+ const selectedAgent = agents.find((agent) => agent.id === route.agent_id);
+ const selectedLabel =
+ selectedAgentName ??
+ selectedAgent?.name ??
+ t(($) => $.dingtalk.group_routes_unknown_agent);
+
+ return (
+ <div className="flex flex-col gap-3 py-3 first:pt-0 last:pb-0 sm:flex-row sm:items-center sm:justify-between">
+ <div className="min-w-0 space-y-1">
+ <p className="truncate text-body font-medium">{title}</p>
+ <p className="truncate font-mono text-micro text-muted-foreground">
+ {route.conversation_id}
+ </p>
+ </div>
+ {canManage ? (
+ <Select
+ items={agents.map((agent) => ({ value: agent.id, label: agent.name }))}
+ value={route.agent_id}
+ onValueChange={(agentId) => {
+ if (agentId) onAgentChange(agentId);
+ }}
+ disabled={!selectorAvailable || updating}
+ >
+ <SelectTrigger className="w-full sm:w-56" aria-label={t(($) => $.dingtalk.group_routes_agent_label)}>
+ <SelectValue>
+ {selectedLabel}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {agents.map((agent) => (
+ <SelectItem key={agent.id} value={agent.id}>
+ {agent.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : (
+ <p className="text-caption text-muted-foreground">
+ {selectedLabel}
+ </p>
+ )}
+ </div>
+ );
+}
+
function InstallationRow({
installation,
canManage,
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 72bc57f6c6..d5d6325903 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -75,31 +75,34 @@ type preMigrationHook func(ctx context.Context, pool *pgxpool.Pool) error
// records the migration as applied, and the queries that need the index silently
// stay on a full scan — the exact regression these migrations exist to fix.
var concurrentIndexCleanups = map[string]string{
- "257_agent_task_queue_channel_media_pending_unique_v2": "idx_one_pending_task_per_issue_agent_v2",
- "261_agent_task_queue_terminal_completed_at_v2": "idx_agent_task_queue_terminal_completed_at_v2",
- "273_agent_task_queue_runtime_id_index": "idx_agent_task_queue_runtime_id",
- "274_task_token_workspace_id_index": "idx_task_token_workspace_id",
- "275_task_token_agent_id_index": "idx_task_token_agent_id",
- "276_chat_draft_restore_task_id_index": "idx_chat_draft_restore_task_id",
- "277_autopilot_run_task_id_index": "idx_autopilot_run_task_id",
- "278_agent_task_queue_agent_id_keyset_index": "idx_agent_task_queue_agent_id_keyset",
- "279_agent_task_queue_issue_id_keyset_index": "idx_agent_task_queue_issue_id_keyset",
- "281_agent_workspace_id_keyset_index": "idx_agent_workspace_id_keyset",
- "282_issue_workspace_id_keyset_index": "idx_issue_workspace_id_keyset",
- "283_agent_runtime_workspace_id_keyset_index": "idx_agent_runtime_workspace_id_keyset",
- "286_plugin_identity_key_index": "idx_plugin_identity_key",
- "287_plugin_release_version_index": "idx_plugin_release_version",
- "288_plugin_installation_workspace_plugin_index": "idx_plugin_installation_workspace_plugin_active",
- "289_plugin_contribution_key_index": "idx_plugin_contribution_release_key",
- "290_plugin_contribution_ordinal_index": "idx_plugin_contribution_release_ordinal",
- "291_plugin_grant_revision_index": "idx_plugin_grant_revision",
- "292_plugin_binding_revision_index": "idx_plugin_binding_revision",
- "293_plugin_installation_workspace_index": "idx_plugin_installation_workspace",
- "295_plugin_artifact_file_index": "idx_plugin_artifact_file_release_path",
- "296_plugin_snapshot_revision_index": "idx_plugin_snapshot_workspace_revision",
- "297_plugin_execution_task_index": "idx_plugin_execution_manifest_task",
- "298_plugin_health_index": "idx_plugin_health_installation_observed",
- "299_agent_task_plugin_manifest_index": "idx_agent_task_plugin_execution_manifest",
+ "257_agent_task_queue_channel_media_pending_unique_v2": "idx_one_pending_task_per_issue_agent_v2",
+ "261_agent_task_queue_terminal_completed_at_v2": "idx_agent_task_queue_terminal_completed_at_v2",
+ "273_agent_task_queue_runtime_id_index": "idx_agent_task_queue_runtime_id",
+ "274_task_token_workspace_id_index": "idx_task_token_workspace_id",
+ "275_task_token_agent_id_index": "idx_task_token_agent_id",
+ "276_chat_draft_restore_task_id_index": "idx_chat_draft_restore_task_id",
+ "277_autopilot_run_task_id_index": "idx_autopilot_run_task_id",
+ "278_agent_task_queue_agent_id_keyset_index": "idx_agent_task_queue_agent_id_keyset",
+ "279_agent_task_queue_issue_id_keyset_index": "idx_agent_task_queue_issue_id_keyset",
+ "281_agent_workspace_id_keyset_index": "idx_agent_workspace_id_keyset",
+ "282_issue_workspace_id_keyset_index": "idx_issue_workspace_id_keyset",
+ "283_agent_runtime_workspace_id_keyset_index": "idx_agent_runtime_workspace_id_keyset",
+ "286_plugin_identity_key_index": "idx_plugin_identity_key",
+ "287_plugin_release_version_index": "idx_plugin_release_version",
+ "288_plugin_installation_workspace_plugin_index": "idx_plugin_installation_workspace_plugin_active",
+ "289_plugin_contribution_key_index": "idx_plugin_contribution_release_key",
+ "290_plugin_contribution_ordinal_index": "idx_plugin_contribution_release_ordinal",
+ "291_plugin_grant_revision_index": "idx_plugin_grant_revision",
+ "292_plugin_binding_revision_index": "idx_plugin_binding_revision",
+ "293_plugin_installation_workspace_index": "idx_plugin_installation_workspace",
+ "295_plugin_artifact_file_index": "idx_plugin_artifact_file_release_path",
+ "296_plugin_snapshot_revision_index": "idx_plugin_snapshot_workspace_revision",
+ "297_plugin_execution_task_index": "idx_plugin_execution_manifest_task",
+ "298_plugin_health_index": "idx_plugin_health_installation_observed",
+ "299_agent_task_plugin_manifest_index": "idx_agent_task_plugin_execution_manifest",
+ "305_dingtalk_group_route_installation_conversation_unique": "idx_dingtalk_group_route_installation_conversation",
+ "306_dingtalk_group_route_workspace_index": "idx_dingtalk_group_route_workspace",
+ "307_dingtalk_group_route_id_unique": "idx_dingtalk_group_route_id_unique",
}
// concurrentDownIndexCleanups covers every migration whose down direction
diff --git a/server/cmd/migrate/migrate_invalid_index_test.go b/server/cmd/migrate/migrate_invalid_index_test.go
index caae84f0a9..1f58ac971e 100644
--- a/server/cmd/migrate/migrate_invalid_index_test.go
+++ b/server/cmd/migrate/migrate_invalid_index_test.go
@@ -96,6 +96,149 @@ func TestRunMigrationsRepairsInvalidConcurrentIndexBeforeRetry(t *testing.T) {
}
}
+func TestRunMigrationsRepairsDingTalkGroupRouteIndexesBeforeRetry(t *testing.T) {
+ pool := openTestPool(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ tests := []struct {
+ version string
+ index string
+ columns string
+ wantUnique bool
+ }{
+ {
+ version: "305_dingtalk_group_route_installation_conversation_unique",
+ index: "idx_dingtalk_group_route_installation_conversation",
+ columns: "installation_id, conversation_id",
+ wantUnique: true,
+ },
+ {
+ version: "306_dingtalk_group_route_workspace_index",
+ index: "idx_dingtalk_group_route_workspace",
+ columns: "workspace_id",
+ },
+ {
+ version: "307_dingtalk_group_route_id_unique",
+ index: "idx_dingtalk_group_route_id_unique",
+ columns: "id",
+ wantUnique: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.version, func(t *testing.T) {
+ if preMigrationHooks[tt.version] == nil {
+ t.Fatalf("production hook is not registered for %s", tt.version)
+ }
+
+ suffix := fmt.Sprintf("%d_%d", time.Now().UnixNano(), rand.Uint32())
+ schema := "migrate_dingtalk_idx_" + suffix
+ schemaIdent := pgx.Identifier{schema}.Sanitize()
+ if _, err := pool.Exec(ctx, "CREATE SCHEMA "+schemaIdent); err != nil {
+ t.Fatalf("create schema: %v", err)
+ }
+ t.Cleanup(func() {
+ cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cleanupCancel()
+ if _, err := pool.Exec(cleanupCtx, "DROP SCHEMA IF EXISTS "+schemaIdent+" CASCADE"); err != nil {
+ t.Logf("drop schema %s: %v", schema, err)
+ }
+ })
+
+ tableName := pgx.Identifier{schema, "dingtalk_group_route"}.Sanitize()
+ indexName := pgx.Identifier{tt.index}.Sanitize()
+ indexRegclass := pgx.Identifier{schema, tt.index}.Sanitize()
+ if _, err := pool.Exec(ctx, "CREATE TABLE "+tableName+` (
+ id TEXT NOT NULL,
+ workspace_id TEXT NOT NULL,
+ installation_id TEXT NOT NULL,
+ conversation_id TEXT NOT NULL
+ )`); err != nil {
+ t.Fatalf("create DingTalk route table: %v", err)
+ }
+ if _, err := pool.Exec(ctx, "INSERT INTO "+tableName+` (
+ id, workspace_id, installation_id, conversation_id
+ ) VALUES
+ ('route-1', 'workspace-1', 'installation-1', 'conversation-1'),
+ ('route-1', 'workspace-1', 'installation-1', 'conversation-1')`); err != nil {
+ t.Fatalf("seed duplicate DingTalk routes: %v", err)
+ }
+
+ // Duplicate keys make the concurrent UNIQUE build fail after Postgres
+ // has registered the index relation, reproducing the INVALID leftover
+ // an interrupted production build leaves behind. For the workspace
+ // index the retry intentionally rebuilds the intended non-unique form.
+ if _, err := pool.Exec(ctx, "CREATE UNIQUE INDEX CONCURRENTLY "+indexName+" ON "+tableName+" ("+tt.columns+")"); err == nil {
+ t.Fatal("failure injection unexpectedly built the index")
+ }
+ assertIndexReadyAndValid(t, pool, schema, tt.index, false)
+
+ if _, err := pool.Exec(ctx, "DELETE FROM "+tableName+" WHERE ctid = (SELECT max(ctid) FROM "+tableName+")"); err != nil {
+ t.Fatalf("remove duplicate route before retry: %v", err)
+ }
+
+ unique := ""
+ if tt.wantUnique {
+ unique = "UNIQUE "
+ }
+ migrationSQL := "CREATE " + unique + "INDEX CONCURRENTLY IF NOT EXISTS " + indexName +
+ " ON " + tableName + " (" + tt.columns + ");\n"
+ migrationPath := filepath.Join(t.TempDir(), tt.version+".up.sql")
+ if err := os.WriteFile(migrationPath, []byte(migrationSQL), 0o600); err != nil {
+ t.Fatalf("write retry migration: %v", err)
+ }
+
+ opts := runOptions{
+ Direction: "up",
+ Files: []string{migrationPath},
+ SchemaMigrationsTable: schema + ".schema_migrations",
+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,
+ Hooks: map[string]preMigrationHook{
+ tt.version: cleanupInvalidConcurrentIndexHook(indexRegclass),
+ },
+ }
+ if err := runMigrations(ctx, pool, opts); err != nil {
+ t.Fatalf("retry migration with invalid-index cleanup: %v", err)
+ }
+
+ assertIndexReadyAndValid(t, pool, schema, tt.index, true)
+ var recorded bool
+ migrationsTable := pgx.Identifier{schema, "schema_migrations"}.Sanitize()
+ if err := pool.QueryRow(ctx,
+ "SELECT EXISTS (SELECT 1 FROM "+migrationsTable+" WHERE version = $1)",
+ tt.version,
+ ).Scan(&recorded); err != nil {
+ t.Fatalf("read migration version: %v", err)
+ }
+ if !recorded {
+ t.Fatal("repaired migration was not recorded")
+ }
+
+ // Reproduce the other non-transactional boundary: CREATE INDEX
+ // CONCURRENTLY committed, then the process exited before recording the
+ // version. A valid leftover must be a safe no-op on the next run, and
+ // the retry must still record the migration.
+ if _, err := pool.Exec(ctx, "DELETE FROM "+migrationsTable+" WHERE version = $1", tt.version); err != nil {
+ t.Fatalf("simulate missing migration record: %v", err)
+ }
+ if err := runMigrations(ctx, pool, opts); err != nil {
+ t.Fatalf("retry migration with valid index already present: %v", err)
+ }
+ assertIndexReadyAndValid(t, pool, schema, tt.index, true)
+ if err := pool.QueryRow(ctx,
+ "SELECT EXISTS (SELECT 1 FROM "+migrationsTable+" WHERE version = $1)",
+ tt.version,
+ ).Scan(&recorded); err != nil {
+ t.Fatalf("read retried migration version: %v", err)
+ }
+ if !recorded {
+ t.Fatal("valid-index retry did not record the migration")
+ }
+ })
+ }
+}
+
// TestRunMigrationsRepairsInvalidConcurrentIndexDuringRollback proves that
// direction-specific hooks also protect CREATE INDEX CONCURRENTLY in down
// migrations. Without the hook, an interrupted rollback leaves an INVALID
@@ -399,3 +542,30 @@ func assertIndexValidity(t *testing.T, pool interface {
t.Fatalf("index %s.%s validity = %v, want %v", schema, index, valid, want)
}
}
+
+func assertIndexReadyAndValid(t *testing.T, pool interface {
+ QueryRow(context.Context, string, ...any) pgx.Row
+}, schema, index string, want bool) {
+ t.Helper()
+ var ready, valid bool
+ if err := pool.QueryRow(context.Background(), `
+ SELECT i.indisready, i.indisvalid
+ FROM pg_index i
+ JOIN pg_class c ON c.oid = i.indexrelid
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = $1 AND c.relname = $2
+ `, schema, index).Scan(&ready, &valid); err != nil {
+ t.Fatalf("read readiness/validity for %s.%s: %v", schema, index, err)
+ }
+ if ready != want || valid != want {
+ t.Fatalf(
+ "index %s.%s readiness/validity = %v/%v, want %v/%v",
+ schema,
+ index,
+ ready,
+ valid,
+ want,
+ want,
+ )
+ }
+}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 619a93ccf8..4697cafbd7 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1247,11 +1247,13 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Group(func(r chi.Router) {
r.Use(middleware.RequireWorkspaceMemberFromURL(queries, "id"))
r.Get("/dingtalk/installations", h.ListDingTalkInstallations)
+ r.Get("/dingtalk/group-routes", h.ListDingTalkGroupRoutes)
})
r.Group(func(r chi.Router) {
r.Use(middleware.RequireWorkspaceRoleFromURL(queries, "id", "owner", "admin"))
r.Delete("/dingtalk/installations/{installationId}", h.RevokeDingTalkInstallation)
r.Post("/dingtalk/install/byo", h.RegisterDingTalkBYO)
+ r.Patch("/dingtalk/group-routes/{routeId}", h.UpdateDingTalkGroupRoute)
})
})
})
diff --git a/server/internal/handler/dingtalk.go b/server/internal/handler/dingtalk.go
index a6f1c82991..f732f96c34 100644
--- a/server/internal/handler/dingtalk.go
+++ b/server/internal/handler/dingtalk.go
@@ -8,6 +8,7 @@ import (
"time"
"github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
"github.com/multica-ai/multica/server/internal/integrations/dingtalk"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -29,6 +30,21 @@ type DingTalkInstallationResponse struct {
UpdatedAt string `json:"updated_at"`
}
+// DingTalkGroupRouteResponse is one group discovered from a Stream callback.
+// The conversation id is returned for diagnostics, but clients should use the
+// stable route id for updates. Credentials and callback payloads are never
+// exposed.
+type DingTalkGroupRouteResponse struct {
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ InstallationID string `json:"installation_id"`
+ ConversationID string `json:"conversation_id"`
+ ConversationTitle string `json:"conversation_title"`
+ AgentID string `json:"agent_id"`
+ DiscoveredAt string `json:"discovered_at"`
+ UpdatedAt string `json:"updated_at"`
+}
+
func dingtalkInstallationToResponse(row db.ChannelInstallation) DingTalkInstallationResponse {
return DingTalkInstallationResponse{
ID: uuidToString(row.ID),
@@ -42,18 +58,177 @@ func dingtalkInstallationToResponse(row db.ChannelInstallation) DingTalkInstalla
}
}
+func dingtalkGroupRouteToResponse(row db.DingtalkGroupRoute) DingTalkGroupRouteResponse {
+ return DingTalkGroupRouteResponse{
+ ID: uuidToString(row.ID),
+ WorkspaceID: uuidToString(row.WorkspaceID),
+ InstallationID: uuidToString(row.InstallationID),
+ ConversationID: row.ConversationID,
+ ConversationTitle: row.ConversationTitle,
+ AgentID: uuidToString(row.AgentID),
+ DiscoveredAt: row.DiscoveredAt.Time.UTC().Format(time.RFC3339),
+ UpdatedAt: row.UpdatedAt.Time.UTC().Format(time.RFC3339),
+ }
+}
+
+// ListDingTalkGroupRoutes (GET /api/workspaces/{id}/dingtalk/group-routes)
+// lists groups the robot has observed. It is member-visible like installation
+// listing; only owner/admin callers may reassign a route.
+func (h *Handler) ListDingTalkGroupRoutes(w http.ResponseWriter, r *http.Request) {
+ if h.DingTalkInstall == nil {
+ writeJSON(w, http.StatusOK, map[string]any{"routes": []DingTalkGroupRouteResponse{}})
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ rows, err := h.Queries.ListDingTalkGroupRoutesByWorkspace(r.Context(), wsUUID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list dingtalk group routes")
+ return
+ }
+ out := make([]DingTalkGroupRouteResponse, 0, len(rows))
+ for _, row := range rows {
+ out = append(out, dingtalkGroupRouteToResponse(row))
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"routes": out})
+}
+
+// UpdateDingTalkGroupRouteRequest selects the one agent that handles messages
+// from a discovered DingTalk group.
+type UpdateDingTalkGroupRouteRequest struct {
+ AgentID string `json:"agent_id"`
+}
+
+// UpdateDingTalkGroupRoute (PATCH
+// /api/workspaces/{id}/dingtalk/group-routes/{routeId}) reassigns a discovered
+// group. The query atomically removes the old chat binding when the agent
+// changes, preventing the new agent from inheriting the old transcript.
+func (h *Handler) UpdateDingTalkGroupRoute(w http.ResponseWriter, r *http.Request) {
+ if h.DingTalkInstall == nil {
+ writeError(w, http.StatusServiceUnavailable, "dingtalk integration not configured")
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ routeUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "routeId"), "route id")
+ if !ok {
+ return
+ }
+ var body UpdateDingTalkGroupRouteRequest
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ agentUUID, ok := parseUUIDOrBadRequest(w, strings.TrimSpace(body.AgentID), "agent_id")
+ if !ok {
+ return
+ }
+ // Fail closed before agent diagnosis so a retained route behind a revoked
+ // installation is always an absent PATCH resource. The reassignment query
+ // repeats this check under an installation lock to close the revoke race.
+ if _, err := h.Queries.GetDingTalkGroupRouteInWorkspace(r.Context(), db.GetDingTalkGroupRouteInWorkspaceParams{
+ ID: routeUUID, WorkspaceID: wsUUID,
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "dingtalk group route not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to load dingtalk group route")
+ return
+ }
+ // Load without a kind filter so the explicit non-user validation below is
+ // reachable. Keep the workspace boundary fail-closed in the handler: an
+ // Agent from another workspace remains indistinguishable from a missing ID.
+ agent, err := h.Queries.GetAgent(r.Context(), agentUUID)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "agent not found in this workspace")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to load agent")
+ return
+ }
+ if agent.WorkspaceID != wsUUID {
+ writeError(w, http.StatusNotFound, "agent not found in this workspace")
+ return
+ }
+ if agent.Kind != "user" {
+ writeError(w, http.StatusBadRequest, "only user agents can handle a DingTalk group")
+ return
+ }
+ if agent.ArchivedAt.Valid {
+ writeError(w, http.StatusConflict, "an archived agent cannot handle a DingTalk group")
+ return
+ }
+ row, err := h.Queries.ReassignDingTalkGroupRoute(r.Context(), db.ReassignDingTalkGroupRouteParams{
+ ID: routeUUID, WorkspaceID: wsUUID, AgentID: agentUUID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ // Diagnose the route boundary first. Revoke-first makes the locked
+ // reassignment return no rows; the retained route must still look
+ // absent and must not be mislabeled as an agent lifecycle conflict.
+ if _, routeErr := h.Queries.GetDingTalkGroupRouteInWorkspace(r.Context(), db.GetDingTalkGroupRouteInWorkspaceParams{
+ ID: routeUUID, WorkspaceID: wsUUID,
+ }); errors.Is(routeErr, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "dingtalk group route not found")
+ return
+ } else if routeErr != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load dingtalk group route")
+ return
+ }
+ // The query re-checks and locks the target agent so a concurrent
+ // archive cannot land an assignment from a stale active snapshot.
+ // Distinguish that lifecycle conflict from a genuinely missing route.
+ currentAgent, agentErr := h.Queries.GetAgent(r.Context(), agentUUID)
+ if agentErr == nil && currentAgent.WorkspaceID == wsUUID && currentAgent.Kind == "user" && currentAgent.ArchivedAt.Valid {
+ writeError(w, http.StatusConflict, "an archived agent cannot handle a DingTalk group")
+ return
+ }
+ if agentErr != nil && !errors.Is(agentErr, pgx.ErrNoRows) {
+ writeError(w, http.StatusInternalServerError, "failed to load agent")
+ return
+ }
+ writeError(w, http.StatusConflict, "the selected agent is no longer available")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to update dingtalk group route")
+ return
+ }
+ h.publish(protocol.EventDingTalkGroupRouteUpdated, uuidToString(wsUUID), "user", userID, map[string]any{
+ "id": uuidToString(row.ID),
+ })
+ writeJSON(w, http.StatusOK, dingtalkGroupRouteToResponse(db.DingtalkGroupRoute{
+ ID: row.ID, WorkspaceID: row.WorkspaceID, InstallationID: row.InstallationID,
+ ConversationID: row.ConversationID, ConversationTitle: row.ConversationTitle,
+ AgentID: row.AgentID, DiscoveredAt: row.DiscoveredAt, UpdatedAt: row.UpdatedAt,
+ }))
+}
+
// ListDingTalkInstallations (GET /api/workspaces/{id}/dingtalk/installations) is
// member-visible so the Integrations tab renders for non-admins. Response flags
// mirror Slack:
// - configured: at-rest encryption key is set (DingTalkInstall != nil).
// - install_supported: kept for the management UI; true whenever configured,
// since a BYO install needs only the at-rest key.
+// - group_routing_supported: explicit capability gate for version-skewed
+// Web/Desktop clients. Older backends omit it, so newer clients must require
+// an exact true before calling the group-routes endpoints.
func (h *Handler) ListDingTalkInstallations(w http.ResponseWriter, r *http.Request) {
if h.DingTalkInstall == nil {
writeJSON(w, http.StatusOK, map[string]any{
- "installations": []DingTalkInstallationResponse{},
- "configured": false,
- "install_supported": false,
+ "installations": []DingTalkInstallationResponse{},
+ "configured": false,
+ "install_supported": false,
+ "group_routing_supported": false,
})
return
}
@@ -71,9 +246,10 @@ func (h *Handler) ListDingTalkInstallations(w http.ResponseWriter, r *http.Reque
out = append(out, dingtalkInstallationToResponse(row))
}
writeJSON(w, http.StatusOK, map[string]any{
- "installations": out,
- "configured": true,
- "install_supported": true,
+ "installations": out,
+ "configured": true,
+ "install_supported": true,
+ "group_routing_supported": true,
})
}
diff --git a/server/internal/handler/dingtalk_group_routes_test.go b/server/internal/handler/dingtalk_group_routes_test.go
new file mode 100644
index 0000000000..5dabbe56e4
--- /dev/null
+++ b/server/internal/handler/dingtalk_group_routes_test.go
@@ -0,0 +1,658 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+
+ dingtalkintegration "github.com/multica-ai/multica/server/internal/integrations/dingtalk"
+ "github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type dingtalkGroupRouteHandlerFixture struct {
+ installationID string
+ routeID string
+ defaultAgentID string
+ targetAgentID string
+}
+
+func newDingTalkGroupRouteHandlerFixture(t *testing.T) dingtalkGroupRouteHandlerFixture {
+ t.Helper()
+ var migrated bool
+ if err := testPool.QueryRow(context.Background(), `SELECT to_regclass('public.dingtalk_group_route') IS NOT NULL`).Scan(&migrated); err != nil || !migrated {
+ t.Skip("dingtalk group route table not present (database not migrated)")
+ }
+
+ previousInstall := testHandler.DingTalkInstall
+ testHandler.DingTalkInstall = &dingtalkintegration.InstallService{}
+ t.Cleanup(func() { testHandler.DingTalkInstall = previousInstall })
+
+ defaultAgentID := createHandlerTestAgent(t, "DingTalk Route Default Agent", nil)
+ targetAgentID := createHandlerTestAgent(t, "DingTalk Route Target Agent", nil)
+ var installationID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO channel_installation (
+ workspace_id, agent_id, channel_type, config, installer_user_id
+ ) VALUES ($1, $2, 'dingtalk', jsonb_build_object('app_id', $3::text), $4)
+ RETURNING id
+ `, testWorkspaceID, defaultAgentID, "handler-dingtalk-group-routes", testUserID).Scan(&installationID); err != nil {
+ t.Fatalf("create DingTalk route installation: %v", err)
+ }
+ var routeID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO dingtalk_group_route (
+ workspace_id, installation_id, conversation_id, conversation_title, agent_id
+ ) VALUES ($1, $2, 'cid-handler-routes', 'Handler routes', $3)
+ RETURNING id
+ `, testWorkspaceID, installationID, defaultAgentID).Scan(&routeID); err != nil {
+ t.Fatalf("create DingTalk group route: %v", err)
+ }
+
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE installation_id = $1`, installationID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM dingtalk_group_route WHERE installation_id = $1`, installationID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)
+ })
+ return dingtalkGroupRouteHandlerFixture{
+ installationID: installationID,
+ routeID: routeID,
+ defaultAgentID: defaultAgentID,
+ targetAgentID: targetAgentID,
+ }
+}
+
+func requestWithRouteParams(req *http.Request, workspaceID, routeID string) *http.Request {
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("id", workspaceID)
+ if routeID != "" {
+ rctx.URLParams.Add("routeId", routeID)
+ }
+ return req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+}
+
+func patchDingTalkGroupRoute(t *testing.T, routeID, agentID string) *httptest.ResponseRecorder {
+ t.Helper()
+ req := requestWithRouteParams(
+ newRequest(
+ http.MethodPatch,
+ "/api/workspaces/"+testWorkspaceID+"/dingtalk/group-routes/"+routeID,
+ UpdateDingTalkGroupRouteRequest{AgentID: agentID},
+ ),
+ testWorkspaceID,
+ routeID,
+ )
+ rec := httptest.NewRecorder()
+ testHandler.UpdateDingTalkGroupRoute(rec, req)
+ return rec
+}
+
+func seedDingTalkGroupRouteBinding(t *testing.T, fx dingtalkGroupRouteHandlerFixture) (string, int64) {
+ t.Helper()
+ sessionID := createHandlerTestChatSession(t, fx.defaultAgentID)
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO channel_chat_session_binding (
+ chat_session_id, installation_id, channel_type,
+ channel_chat_id, chat_type, config
+ ) VALUES ($1, $2, 'dingtalk', 'cid-handler-routes', 'group',
+ jsonb_build_object('agent_id', $3::text))
+ `, sessionID, fx.installationID, fx.defaultAgentID); err != nil {
+ t.Fatalf("seed DingTalk route chat binding: %v", err)
+ }
+ var revision int64
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT revision FROM dingtalk_group_route WHERE id = $1
+ `, fx.routeID).Scan(&revision); err != nil {
+ t.Fatalf("read initial DingTalk route revision: %v", err)
+ }
+ return sessionID, revision
+}
+
+func assertDingTalkGroupRouteBindingUnchanged(
+ t *testing.T,
+ fx dingtalkGroupRouteHandlerFixture,
+ sessionID string,
+ revision int64,
+) {
+ t.Helper()
+ var agentID string
+ var durableRevision int64
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT agent_id, revision FROM dingtalk_group_route WHERE id = $1
+ `, fx.routeID).Scan(&agentID, &durableRevision); err != nil {
+ t.Fatalf("read durable DingTalk route: %v", err)
+ }
+ if agentID != fx.defaultAgentID || durableRevision != revision {
+ t.Fatalf(
+ "durable route = agent %s revision %d, want agent %s revision %d",
+ agentID,
+ durableRevision,
+ fx.defaultAgentID,
+ revision,
+ )
+ }
+ var durableSessionID string
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT chat_session_id
+ FROM channel_chat_session_binding
+ WHERE installation_id = $1
+ AND channel_type = 'dingtalk'
+ AND channel_chat_id = 'cid-handler-routes'
+ `, fx.installationID).Scan(&durableSessionID); err != nil {
+ t.Fatalf("read durable DingTalk route binding: %v", err)
+ }
+ if durableSessionID != sessionID {
+ t.Fatalf("durable route binding = %s, want %s", durableSessionID, sessionID)
+ }
+}
+
+func assertDingTalkRouteNotFoundWithoutMetadata(t *testing.T, rec *httptest.ResponseRecorder) {
+ t.Helper()
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("PATCH revoked route status = %d, want 404: %s", rec.Code, rec.Body.String())
+ }
+ for _, secret := range []string{"Handler routes", "cid-handler-routes"} {
+ if strings.Contains(rec.Body.String(), secret) {
+ t.Fatalf("PATCH revoked route leaked %q: %s", secret, rec.Body.String())
+ }
+ }
+}
+
+func TestDingTalkGroupRoutePatchRejectsDisabledDeployment(t *testing.T) {
+ req := requestWithRouteParams(
+ httptest.NewRequest(http.MethodPatch, "/api/workspaces/disabled/dingtalk/group-routes/disabled", nil),
+ "disabled",
+ "disabled",
+ )
+ rec := httptest.NewRecorder()
+ (&Handler{}).UpdateDingTalkGroupRoute(rec, req)
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("disabled PATCH status = %d, want 503: %s", rec.Code, rec.Body.String())
+ }
+}
+
+func TestDingTalkGroupRoutePatchRejectsRevokedInstallation(t *testing.T) {
+ fx := newDingTalkGroupRouteHandlerFixture(t)
+ sessionID, revision := seedDingTalkGroupRouteBinding(t, fx)
+ if _, err := testPool.Exec(context.Background(), `
+ UPDATE channel_installation SET status = 'revoked' WHERE id = $1
+ `, fx.installationID); err != nil {
+ t.Fatalf("revoke DingTalk installation before PATCH: %v", err)
+ }
+
+ rec := patchDingTalkGroupRoute(t, fx.routeID, fx.targetAgentID)
+ assertDingTalkRouteNotFoundWithoutMetadata(t, rec)
+ assertDingTalkGroupRouteBindingUnchanged(t, fx, sessionID, revision)
+}
+
+func TestDingTalkGroupRoutePatchSerializesWithRevoke(t *testing.T) {
+ fx := newDingTalkGroupRouteHandlerFixture(t)
+ sessionID, revision := seedDingTalkGroupRouteBinding(t, fx)
+ ctx := context.Background()
+
+ revokeTx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin controlled DingTalk revoke: %v", err)
+ }
+ t.Cleanup(func() { _ = revokeTx.Rollback(context.Background()) })
+ var revokePID int32
+ if err := revokeTx.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&revokePID); err != nil {
+ t.Fatalf("read controlled revoke backend pid: %v", err)
+ }
+ if _, err := revokeTx.Exec(ctx, `
+ UPDATE channel_installation SET status = 'revoked' WHERE id = $1
+ `, fx.installationID); err != nil {
+ t.Fatalf("lock installation for controlled revoke: %v", err)
+ }
+
+ patchDone := make(chan *httptest.ResponseRecorder, 1)
+ go func() {
+ patchDone <- patchDingTalkGroupRoute(t, fx.routeID, fx.targetAgentID)
+ }()
+
+ deadline := time.Now().Add(5 * time.Second)
+ blocked := false
+ for time.Now().Before(deadline) {
+ if err := testPool.QueryRow(ctx, `
+ SELECT EXISTS (
+ SELECT 1
+ FROM pg_stat_activity a
+ WHERE $1 = ANY(pg_blocking_pids(a.pid))
+ )
+ `, revokePID).Scan(&blocked); err != nil {
+ _ = revokeTx.Rollback(ctx)
+ t.Fatalf("inspect controlled revoke lock wait: %v", err)
+ }
+ if blocked {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if !blocked {
+ _ = revokeTx.Rollback(ctx)
+ rec := <-patchDone
+ t.Fatalf("PATCH never waited for revoke; status = %d: %s", rec.Code, rec.Body.String())
+ }
+ if err := revokeTx.Commit(ctx); err != nil {
+ t.Fatalf("commit controlled DingTalk revoke: %v", err)
+ }
+
+ select {
+ case rec := <-patchDone:
+ assertDingTalkRouteNotFoundWithoutMetadata(t, rec)
+ case <-time.After(5 * time.Second):
+ t.Fatal("PATCH did not resume after controlled revoke committed")
+ }
+ assertDingTalkGroupRouteBindingUnchanged(t, fx, sessionID, revision)
+}
+
+func TestDingTalkGroupRoutePatchDiagnosesConcurrentAgentArchive(t *testing.T) {
+ fx := newDingTalkGroupRouteHandlerFixture(t)
+ sessionID, revision := seedDingTalkGroupRouteBinding(t, fx)
+ ctx := context.Background()
+
+ archiveTx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin controlled Agent archive: %v", err)
+ }
+ t.Cleanup(func() { _ = archiveTx.Rollback(context.Background()) })
+ var archivePID int32
+ if err := archiveTx.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&archivePID); err != nil {
+ t.Fatalf("read controlled Agent archive backend pid: %v", err)
+ }
+ if _, err := archiveTx.Exec(ctx, `
+ UPDATE agent SET archived_at = now(), archived_by = $2 WHERE id = $1
+ `, fx.targetAgentID, testUserID); err != nil {
+ t.Fatalf("lock target Agent for controlled archive: %v", err)
+ }
+
+ patchDone := make(chan *httptest.ResponseRecorder, 1)
+ go func() {
+ patchDone <- patchDingTalkGroupRoute(t, fx.routeID, fx.targetAgentID)
+ }()
+
+ deadline := time.Now().Add(5 * time.Second)
+ blocked := false
+ for time.Now().Before(deadline) {
+ if err := testPool.QueryRow(ctx, `
+ SELECT EXISTS (
+ SELECT 1
+ FROM pg_stat_activity a
+ WHERE $1 = ANY(pg_blocking_pids(a.pid))
+ )
+ `, archivePID).Scan(&blocked); err != nil {
+ _ = archiveTx.Rollback(ctx)
+ t.Fatalf("inspect controlled Agent archive lock wait: %v", err)
+ }
+ if blocked {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if !blocked {
+ _ = archiveTx.Rollback(ctx)
+ rec := <-patchDone
+ t.Fatalf("PATCH never waited for Agent archive; status = %d: %s", rec.Code, rec.Body.String())
+ }
+ if err := archiveTx.Commit(ctx); err != nil {
+ t.Fatalf("commit controlled Agent archive: %v", err)
+ }
+
+ select {
+ case rec := <-patchDone:
+ if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), "archived") {
+ t.Fatalf("PATCH after Agent archive status = %d, want archived 409: %s", rec.Code, rec.Body.String())
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("PATCH did not resume after controlled Agent archive committed")
+ }
+ assertDingTalkGroupRouteBindingUnchanged(t, fx, sessionID, revision)
+}
+
+func TestListDingTalkInstallationsAdvertisesGroupRoutingCapability(t *testing.T) {
+ t.Run("disabled deployment", func(t *testing.T) {
+ rec := httptest.NewRecorder()
+ (&Handler{}).ListDingTalkInstallations(rec, httptest.NewRequest(http.MethodGet, "/", nil))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("disabled installations status = %d, want 200: %s", rec.Code, rec.Body.String())
+ }
+ var body struct {
+ GroupRoutingSupported bool `json:"group_routing_supported"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode disabled installations response: %v", err)
+ }
+ if body.GroupRoutingSupported {
+ t.Fatal("disabled deployment advertised group routing")
+ }
+ })
+
+ t.Run("configured deployment", func(t *testing.T) {
+ _ = newDingTalkGroupRouteHandlerFixture(t)
+ box, err := secretbox.New(make([]byte, secretbox.KeySize))
+ if err != nil {
+ t.Fatalf("create DingTalk test secret box: %v", err)
+ }
+ service, err := dingtalkintegration.NewInstallService(db.New(testPool), testPool, box, nil)
+ if err != nil {
+ t.Fatalf("create DingTalk install service: %v", err)
+ }
+ testHandler.DingTalkInstall = service
+
+ req := requestWithRouteParams(
+ httptest.NewRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/dingtalk/installations", nil),
+ testWorkspaceID,
+ "",
+ )
+ rec := httptest.NewRecorder()
+ testHandler.ListDingTalkInstallations(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("configured installations status = %d, want 200: %s", rec.Code, rec.Body.String())
+ }
+ var body struct {
+ GroupRoutingSupported bool `json:"group_routing_supported"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode configured installations response: %v", err)
+ }
+ if !body.GroupRoutingSupported {
+ t.Fatal("configured deployment did not advertise group routing")
+ }
+ })
+}
+
+func TestDingTalkGroupRouteHandlersValidationAndErrors(t *testing.T) {
+ fx := newDingTalkGroupRouteHandlerFixture(t)
+
+ t.Run("GET returns workspace routes", func(t *testing.T) {
+ req := requestWithRouteParams(newRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/dingtalk/group-routes", nil), testWorkspaceID, "")
+ rec := httptest.NewRecorder()
+ testHandler.ListDingTalkGroupRoutes(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("GET routes status = %d: %s", rec.Code, rec.Body.String())
+ }
+ var body struct {
+ Routes []DingTalkGroupRouteResponse `json:"routes"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
+ t.Fatal(err)
+ }
+ if len(body.Routes) != 1 || body.Routes[0].ID != fx.routeID || body.Routes[0].AgentID != fx.defaultAgentID {
+ t.Fatalf("GET routes body = %+v", body)
+ }
+ })
+
+ t.Run("GET validates workspace id", func(t *testing.T) {
+ req := requestWithRouteParams(newRequest(http.MethodGet, "/api/workspaces/not-a-uuid/dingtalk/group-routes", nil), "not-a-uuid", "")
+ rec := httptest.NewRecorder()
+ testHandler.ListDingTalkGroupRoutes(rec, req)
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("invalid workspace status = %d: %s", rec.Code, rec.Body.String())
+ }
+ })
+
+ t.Run("GET reports query errors", func(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ req := newRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/dingtalk/group-routes", nil).WithContext(ctx)
+ req = requestWithRouteParams(req, testWorkspaceID, "")
+ rec := httptest.NewRecorder()
+ testHandler.ListDingTalkGroupRoutes(rec, req)
+ if rec.Code != http.StatusInternalServerError {
+ t.Fatalf("cancelled GET status = %d: %s", rec.Code, rec.Body.String())
+ }
+ })
+
+ patch := func(t *testing.T, workspaceID, routeID string, body any) *httptest.ResponseRecorder {
+ t.Helper()
+ req := requestWithRouteParams(newRequest(http.MethodPatch, "/api/workspaces/"+workspaceID+"/dingtalk/group-routes/"+routeID, body), workspaceID, routeID)
+ rec := httptest.NewRecorder()
+ testHandler.UpdateDingTalkGroupRoute(rec, req)
+ return rec
+ }
+
+ t.Run("PATCH requires a user", func(t *testing.T) {
+ raw, _ := json.Marshal(UpdateDingTalkGroupRouteRequest{AgentID: fx.targetAgentID})
+ req := requestWithRouteParams(httptest.NewRequest(http.MethodPatch, "/api/workspaces/"+testWorkspaceID+"/dingtalk/group-routes/"+fx.routeID, bytes.NewReader(raw)), testWorkspaceID, fx.routeID)
+ rec := httptest.NewRecorder()
+ testHandler.UpdateDingTalkGroupRoute(rec, req)
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("anonymous PATCH status = %d: %s", rec.Code, rec.Body.String())
+ }
+ })
+
+ for _, tc := range []struct {
+ name string
+ workspaceID string
+ routeID string
+ body any
+ want int
+ }{
+ {name: "invalid workspace id", workspaceID: "bad-workspace", routeID: fx.routeID, body: UpdateDingTalkGroupRouteRequest{AgentID: fx.targetAgentID}, want: http.StatusBadRequest},
+ {name: "invalid route id", workspaceID: testWorkspaceID, routeID: "bad-route", body: UpdateDingTalkGroupRouteRequest{AgentID: fx.targetAgentID}, want: http.StatusBadRequest},
+ {name: "invalid agent id", workspaceID: testWorkspaceID, routeID: fx.routeID, body: UpdateDingTalkGroupRouteRequest{AgentID: "bad-agent"}, want: http.StatusBadRequest},
+ {name: "route not found", workspaceID: testWorkspaceID, routeID: "d2770000-0000-4000-8000-000000000002", body: UpdateDingTalkGroupRouteRequest{AgentID: fx.targetAgentID}, want: http.StatusNotFound},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ rec := patch(t, tc.workspaceID, tc.routeID, tc.body)
+ if rec.Code != tc.want {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, tc.want, rec.Body.String())
+ }
+ })
+ }
+
+ t.Run("PATCH rejects existing agent outside workspace", func(t *testing.T) {
+ ctx := context.Background()
+ var foreignWorkspaceID string
+ suffix := fmt.Sprintf("%d", time.Now().UnixNano())
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO workspace (name, slug, description, issue_prefix)
+ VALUES ($1, $2, 'DingTalk cross-workspace target test', 'DTX')
+ RETURNING id
+ `, "DingTalk Foreign Workspace "+suffix, "dingtalk-foreign-"+suffix).Scan(&foreignWorkspaceID); err != nil {
+ t.Fatalf("create foreign workspace: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, foreignWorkspaceID)
+ })
+ var foreignAgentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent (
+ workspace_id, name, description, runtime_mode, runtime_config,
+ visibility, max_concurrent_tasks, owner_id
+ ) VALUES ($1, $2, '', 'cloud', '{}'::jsonb, 'workspace', 1, $3)
+ RETURNING id
+ `, foreignWorkspaceID, "DingTalk Foreign Agent "+suffix, testUserID).Scan(&foreignAgentID); err != nil {
+ t.Fatalf("create foreign Agent: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, foreignAgentID)
+ })
+
+ rec := patch(t, testWorkspaceID, fx.routeID, UpdateDingTalkGroupRouteRequest{AgentID: foreignAgentID})
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("cross-workspace target status = %d, want 404: %s", rec.Code, rec.Body.String())
+ }
+ var durableAgentID string
+ if err := testPool.QueryRow(ctx, `SELECT agent_id FROM dingtalk_group_route WHERE id = $1`, fx.routeID).Scan(&durableAgentID); err != nil {
+ t.Fatal(err)
+ }
+ if durableAgentID != fx.defaultAgentID {
+ t.Fatalf("cross-workspace PATCH changed route to %s, want %s", durableAgentID, fx.defaultAgentID)
+ }
+ })
+
+ t.Run("PATCH rejects malformed JSON", func(t *testing.T) {
+ req := requestWithRouteParams(newRequest(http.MethodPatch, "/api/workspaces/"+testWorkspaceID+"/dingtalk/group-routes/"+fx.routeID, nil), testWorkspaceID, fx.routeID)
+ req.Body = http.NoBody
+ rec := httptest.NewRecorder()
+ testHandler.UpdateDingTalkGroupRoute(rec, req)
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("empty PATCH status = %d: %s", rec.Code, rec.Body.String())
+ }
+ })
+
+ t.Run("PATCH rejects archived target", func(t *testing.T) {
+ if _, err := testPool.Exec(context.Background(), `UPDATE agent SET archived_at = now() WHERE id = $1`, fx.targetAgentID); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `UPDATE agent SET archived_at = NULL, archived_by = NULL WHERE id = $1`, fx.targetAgentID)
+ })
+ rec := patch(t, testWorkspaceID, fx.routeID, UpdateDingTalkGroupRouteRequest{AgentID: fx.targetAgentID})
+ if rec.Code != http.StatusConflict {
+ t.Fatalf("archived target status = %d: %s", rec.Code, rec.Body.String())
+ }
+ if _, err := testPool.Exec(context.Background(), `UPDATE agent SET archived_at = NULL, archived_by = NULL WHERE id = $1`, fx.targetAgentID); err != nil {
+ t.Fatal(err)
+ }
+ })
+
+ t.Run("PATCH rejects non-user target", func(t *testing.T) {
+ if _, err := testPool.Exec(context.Background(), `
+ UPDATE agent
+ SET kind = 'system', system_key = $2
+ WHERE id = $1
+ `, fx.targetAgentID, "dingtalk_route_non_user_"+fx.targetAgentID); err != nil {
+ t.Fatal(err)
+ }
+ defer func() {
+ _, _ = testPool.Exec(context.Background(), `
+ UPDATE agent SET kind = 'user', system_key = NULL WHERE id = $1
+ `, fx.targetAgentID)
+ }()
+
+ rec := patch(t, testWorkspaceID, fx.routeID, UpdateDingTalkGroupRouteRequest{AgentID: fx.targetAgentID})
+ if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "only user agents") {
+ t.Fatalf("non-user target status = %d, want 400: %s", rec.Code, rec.Body.String())
+ }
+ var durableAgentID string
+ if err := testPool.QueryRow(context.Background(), `SELECT agent_id FROM dingtalk_group_route WHERE id = $1`, fx.routeID).Scan(&durableAgentID); err != nil {
+ t.Fatal(err)
+ }
+ if durableAgentID != fx.defaultAgentID {
+ t.Fatalf("non-user PATCH changed route to %s, want %s", durableAgentID, fx.defaultAgentID)
+ }
+ })
+
+ t.Run("PATCH reports query errors", func(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ req := newRequest(http.MethodPatch, "/api/workspaces/"+testWorkspaceID+"/dingtalk/group-routes/"+fx.routeID, UpdateDingTalkGroupRouteRequest{AgentID: fx.targetAgentID}).WithContext(ctx)
+ req = requestWithRouteParams(req, testWorkspaceID, fx.routeID)
+ rec := httptest.NewRecorder()
+ testHandler.UpdateDingTalkGroupRoute(rec, req)
+ if rec.Code != http.StatusInternalServerError {
+ t.Fatalf("cancelled PATCH status = %d: %s", rec.Code, rec.Body.String())
+ }
+ })
+
+ t.Run("PATCH reassigns route", func(t *testing.T) {
+ rec := patch(t, testWorkspaceID, fx.routeID, UpdateDingTalkGroupRouteRequest{AgentID: fx.targetAgentID})
+ if rec.Code != http.StatusOK {
+ t.Fatalf("successful PATCH status = %d: %s", rec.Code, rec.Body.String())
+ }
+ var body DingTalkGroupRouteResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
+ t.Fatal(err)
+ }
+ if body.ID != fx.routeID || body.AgentID != fx.targetAgentID {
+ t.Fatalf("successful PATCH body = %+v", body)
+ }
+ })
+}
+
+func TestDingTalkGroupRouteAuthorizationWiring(t *testing.T) {
+ fx := newDingTalkGroupRouteHandlerFixture(t)
+ ctx := context.Background()
+
+ createUser := func(label string) string {
+ t.Helper()
+ var id string
+ if err := testPool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`, "DingTalk "+label, fmt.Sprintf("dingtalk-route-%[email protected]", label)).Scan(&id); err != nil {
+ t.Fatalf("create %s user: %v", label, err)
+ }
+ return id
+ }
+ memberID := createUser("member")
+ outsiderID := createUser("outsider")
+ if _, err := testPool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`, testWorkspaceID, memberID); err != nil {
+ t.Fatalf("create member: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, memberID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id IN ($1, $2)`, memberID, outsiderID)
+ })
+
+ router := chi.NewRouter()
+ router.Route("/api/workspaces/{id}", func(r chi.Router) {
+ r.Group(func(r chi.Router) {
+ r.Use(middleware.RequireWorkspaceMemberFromURL(testHandler.Queries, "id"))
+ r.Get("/dingtalk/group-routes", testHandler.ListDingTalkGroupRoutes)
+ })
+ r.Group(func(r chi.Router) {
+ r.Use(middleware.RequireWorkspaceRoleFromURL(testHandler.Queries, "id", "owner", "admin"))
+ r.Patch("/dingtalk/group-routes/{routeId}", testHandler.UpdateDingTalkGroupRoute)
+ })
+ })
+
+ exercise := func(method, path, userID string, body any) *httptest.ResponseRecorder {
+ var buf bytes.Buffer
+ if body != nil {
+ _ = json.NewEncoder(&buf).Encode(body)
+ }
+ req := httptest.NewRequest(method, path, &buf)
+ if userID != "" {
+ req.Header.Set("X-User-ID", userID)
+ }
+ rec := httptest.NewRecorder()
+ router.ServeHTTP(rec, req)
+ return rec
+ }
+
+ base := "/api/workspaces/" + testWorkspaceID + "/dingtalk/group-routes"
+ if rec := exercise(http.MethodGet, base, memberID, nil); rec.Code != http.StatusOK {
+ t.Errorf("member GET status = %d: %s", rec.Code, rec.Body.String())
+ }
+ if _, err := testPool.Exec(ctx, `UPDATE channel_installation SET status = 'revoked' WHERE id = $1`, fx.installationID); err != nil {
+ t.Fatalf("revoke DingTalk installation before member GET: %v", err)
+ }
+ revokedGET := exercise(http.MethodGet, base, memberID, nil)
+ if revokedGET.Code != http.StatusOK {
+ t.Fatalf("member GET after revoke status = %d: %s", revokedGET.Code, revokedGET.Body.String())
+ }
+ var revokedBody struct {
+ Routes []DingTalkGroupRouteResponse `json:"routes"`
+ }
+ if err := json.Unmarshal(revokedGET.Body.Bytes(), &revokedBody); err != nil {
+ t.Fatalf("decode member GET after revoke: %v", err)
+ }
+ if len(revokedBody.Routes) != 0 || strings.Contains(revokedGET.Body.String(), "Handler routes") || strings.Contains(revokedGET.Body.String(), "cid-handler-routes") {
+ t.Fatalf("member GET leaked revoked route metadata: %s", revokedGET.Body.String())
+ }
+ if _, err := testPool.Exec(ctx, `UPDATE channel_installation SET status = 'active' WHERE id = $1`, fx.installationID); err != nil {
+ t.Fatalf("restore DingTalk installation after member GET regression: %v", err)
+ }
+ if rec := exercise(http.MethodGet, base, outsiderID, nil); rec.Code != http.StatusNotFound {
+ t.Errorf("outsider GET status = %d: %s", rec.Code, rec.Body.String())
+ }
+ if rec := exercise(http.MethodGet, base, "", nil); rec.Code != http.StatusUnauthorized {
+ t.Errorf("anonymous GET status = %d: %s", rec.Code, rec.Body.String())
+ }
+ patchBody := UpdateDingTalkGroupRouteRequest{AgentID: fx.targetAgentID}
+ if rec := exercise(http.MethodPatch, base+"/"+fx.routeID, memberID, patchBody); rec.Code != http.StatusForbidden {
+ t.Errorf("member PATCH status = %d: %s", rec.Code, rec.Body.String())
+ }
+ if rec := exercise(http.MethodPatch, base+"/"+fx.routeID, testUserID, patchBody); rec.Code != http.StatusOK {
+ t.Errorf("owner PATCH status = %d: %s", rec.Code, rec.Body.String())
+ }
+}
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 1951d9e9fa..42eb91c93d 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -52,6 +52,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"contact_sales_inquiry": workspaceDeleteKeep,
"daemon_connection": workspaceDelete,
"daemon_token": workspaceDelete,
+ "dingtalk_group_route": workspaceDelete,
"feedback": workspaceDeleteDetach,
"github_installation": workspaceDelete,
"github_pending_check_suite": workspaceDelete,
diff --git a/server/internal/integrations/channel/engine/resolvers.go b/server/internal/integrations/channel/engine/resolvers.go
index e2bade266c..729bdf0395 100644
--- a/server/internal/integrations/channel/engine/resolvers.go
+++ b/server/internal/integrations/channel/engine/resolvers.go
@@ -78,9 +78,12 @@ type Result struct {
// opaquely so the set's other ports (binder, replier, typing) reuse it without
// a re-fetch; the Router never reads Platform.
type ResolvedInstallation struct {
- ID pgtype.UUID
- WorkspaceID pgtype.UUID
- AgentID pgtype.UUID
+ ID pgtype.UUID
+ WorkspaceID pgtype.UUID
+ AgentID pgtype.UUID
+ // RouteRevision is an adapter-owned optimistic fence for platforms that
+ // route one installation to multiple agents. Zero means no such fence.
+ RouteRevision int64
InstallerUserID pgtype.UUID
Active bool
Platform any
@@ -110,6 +113,8 @@ type AppendParams struct {
SessionID pgtype.UUID
Sender pgtype.UUID
InstallationID pgtype.UUID
+ AgentID pgtype.UUID
+ RouteRevision int64
Message channel.InboundMessage
ClaimToken pgtype.UUID
MediaPendingSeconds float64
@@ -164,6 +169,15 @@ var (
// ErrSenderNotMember: the sender is bound but not a workspace member →
// non_workspace_member drop.
ErrSenderNotMember = errors.New("engine: sender not a workspace member")
+ // ErrTargetAgentArchived: a platform-specific route resolves to an archived
+ // agent. The route remains intact so restoring the agent restores delivery;
+ // the Router returns the normal archived-agent product outcome without
+ // creating a session or enqueueing work while the target is unavailable.
+ ErrTargetAgentArchived = errors.New("engine: routed agent is archived")
+ // ErrRouteChanged asks the Router to resolve the platform route again and
+ // retry the same claimed message. The durable append must return this before
+ // writing when an administrator changed the route revision concurrently.
+ ErrRouteChanged = errors.New("engine: route changed")
// ErrDuplicate: Claim found the message already processed / in flight →
// duplicate drop.
ErrDuplicate = errors.New("engine: duplicate message")
@@ -187,6 +201,15 @@ type IdentityResolver interface {
ResolveSender(ctx context.Context, inst ResolvedInstallation, msg channel.InboundMessage) (ResolvedIdentity, error)
}
+// ValidatedInboundResolver runs only after the group-addressing and sender
+// identity/membership gates have passed. Platforms use this optional seam for
+// durable discovery that must never be triggered by rejected callbacks. It may
+// also finalize routing fields on the installation returned to the remaining
+// pipeline.
+type ValidatedInboundResolver interface {
+ ResolveValidatedInbound(ctx context.Context, inst ResolvedInstallation, identity ResolvedIdentity, msg channel.InboundMessage) (ResolvedInstallation, error)
+}
+
// Deduper is the two-phase idempotency seam. Claim mints an owner-fence token
// (ErrDuplicate when already processed / in flight); Mark/Release are fenced on
// the token (a no-op on token mismatch is not an error).
@@ -315,6 +338,7 @@ type TypingNotifier interface {
type ResolverSet struct {
Installation InstallationResolver
Identity IdentityResolver
+ Validated ValidatedInboundResolver
Dedup Deduper
Session SessionBinder
Media MediaResolver
diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.go
index af53f354d6..4e31ffb763 100644
--- a/server/internal/integrations/channel/engine/router.go
+++ b/server/internal/integrations/channel/engine/router.go
@@ -114,6 +114,13 @@ func NewRouter(issues IssueCreator, tasks TaskEnqueuer, reader SessionReader, cf
// delay dwarfs every pipeline budget.
const DefaultMediaTimeout = 45 * time.Second
+// Dedup finalization is a short durability step after the claimed pipeline has
+// selected a terminal outcome. The request context may already be cancelled
+// (notably after repeated route conflicts), so preserve its values while giving
+// Mark/Release a bounded opportunity to commit instead of stranding a claim
+// until stale reclaim.
+const dedupFinalizeTimeout = time.Second
+
type mediaQueueEntry struct {
tail chan struct{}
}
@@ -273,8 +280,10 @@ func (r *Router) dispatch(ctx context.Context, set ResolverSet, msg channel.Inbo
res, finalize, err := r.processClaimed(ctx, set, msg, inst, claimToken, bareFresh)
- if claimed {
- r.applyFinalize(ctx, set, inst.ID, msg.MessageID, claimToken, finalize)
+ if claimed && finalize != finalizeNone {
+ finalizeCtx, finalizeCancel := context.WithTimeout(context.WithoutCancel(ctx), dedupFinalizeTimeout)
+ r.applyFinalize(finalizeCtx, set, inst.ID, msg.MessageID, claimToken, finalize)
+ finalizeCancel()
}
// ErrClaimLost: another worker holds the claim. Surface as duplicate.
@@ -322,37 +331,52 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
}
}
- // 5. Resolve the chat_session. Group sessions are created by the INSTALLER
- // (stable workspace identity that won't churn with group membership);
- // p2p sessions by the sole human sender.
+ // Platform discovery that exposes a conversation to workspace members must
+ // run only after both the @bot gate and sender membership validation. The
+ // resolver may also finalize a platform-specific target selected by that
+ // newly discovered route.
+ if set.Validated != nil {
+ inst, err = set.Validated.ResolveValidatedInbound(ctx, inst, identity, msg)
+ if err != nil {
+ if errors.Is(err, ErrTargetAgentArchived) {
+ return Result{
+ Outcome: OutcomeAgentArchived,
+ InstallationID: inst.ID,
+ Sender: msg.Source.SenderID,
+ }, finalizeMark, nil
+ }
+ return Result{}, finalizeRelease, fmt.Errorf("resolve validated inbound route: %w", err)
+ }
+ }
+
+ // 5-6. Resolve the chat_session, then append the message and dedup Mark as
+ // the durable transition point. A platform route fence may reject the append
+ // when a concurrent reassignment committed first. Resolve the latest route
+ // and retry this same claimed message in-process: DingTalk has already ACKed
+ // the callback and will not redeliver it.
sessionCreator := identity.UserID
if msg.Source.ChatType == channel.ChatTypeGroup {
sessionCreator = inst.InstallerUserID
}
- sessionID, err := set.Session.EnsureSession(ctx, EnsureSessionParams{
- Installation: inst,
- Sender: sessionCreator,
- Message: msg,
- })
- if err != nil {
- // Single tx; an error rolled it back, nothing landed. Release.
- return Result{}, finalizeRelease, fmt.Errorf("ensure chat session: %w", err)
- }
- if bareFresh {
- // ForceFresh is a task-dispatch property. A bare command has no useful
- // task to dispatch, so remember the intent and apply it to the next real
- // message instead of writing or running an empty turn.
- if err := set.Session.MarkPendingFresh(ctx, sessionID); err != nil {
- return Result{}, finalizeRelease, fmt.Errorf("persist fresh command: %w", err)
+ refreshChangedRoute := func() (Result, bool, error) {
+ if set.Validated == nil {
+ return Result{}, false, ErrRouteChanged
}
- return Result{
- Outcome: OutcomeFreshPending,
- InstallationID: inst.ID,
- ChatSessionID: sessionID,
- Sender: msg.Source.SenderID,
- }, finalizeMark, nil
- }
- // 6. Append message + in-tx dedup Mark — the durable transition point.
+ var routeErr error
+ inst, routeErr = set.Validated.ResolveValidatedInbound(ctx, inst, identity, msg)
+ if errors.Is(routeErr, ErrTargetAgentArchived) {
+ return Result{
+ Outcome: OutcomeAgentArchived,
+ InstallationID: inst.ID,
+ Sender: msg.Source.SenderID,
+ }, true, nil
+ }
+ if routeErr != nil {
+ return Result{}, false, fmt.Errorf("refresh validated inbound route: %w", routeErr)
+ }
+ return Result{}, false, nil
+ }
+
// The media budget is persisted only when the message actually carries
// media: a plain text message must never wait behind the media semaphore
// or fall back to the 45s deadline after a crash. It is a relative
@@ -377,19 +401,70 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
if resolveMedia {
mediaPendingSeconds = r.mediaTimeout.Seconds()
}
- appendRes, err := set.Session.AppendMessage(ctx, AppendParams{
- SessionID: sessionID,
- Sender: identity.UserID,
- InstallationID: inst.ID,
- Message: msg,
- ClaimToken: claimToken,
- MediaPendingSeconds: mediaPendingSeconds,
- })
- if err != nil {
- if errors.Is(err, ErrClaimLost) {
- return Result{}, finalizeNone, err
+
+ var sessionID pgtype.UUID
+ var appendRes AppendResult
+ for {
+ if ctxErr := ctx.Err(); ctxErr != nil {
+ return Result{}, finalizeRelease, ctxErr
+ }
+ sessionID, err = set.Session.EnsureSession(ctx, EnsureSessionParams{
+ Installation: inst,
+ Sender: sessionCreator,
+ Message: msg,
+ })
+ if errors.Is(err, ErrRouteChanged) {
+ if result, done, refreshErr := refreshChangedRoute(); refreshErr != nil {
+ return Result{}, finalizeRelease, refreshErr
+ } else if done {
+ return result, finalizeMark, nil
+ }
+ continue
+ }
+ if err != nil {
+ // Single tx; an error rolled it back, nothing landed. Release.
+ return Result{}, finalizeRelease, fmt.Errorf("ensure chat session: %w", err)
+ }
+ if bareFresh {
+ // ForceFresh is a task-dispatch property. A bare command has no useful
+ // task to dispatch, so remember the intent and apply it to the next real
+ // message instead of writing or running an empty turn.
+ if err := set.Session.MarkPendingFresh(ctx, sessionID); err != nil {
+ return Result{}, finalizeRelease, fmt.Errorf("persist fresh command: %w", err)
+ }
+ return Result{
+ Outcome: OutcomeFreshPending,
+ InstallationID: inst.ID,
+ ChatSessionID: sessionID,
+ Sender: msg.Source.SenderID,
+ }, finalizeMark, nil
+ }
+
+ appendRes, err = set.Session.AppendMessage(ctx, AppendParams{
+ SessionID: sessionID,
+ Sender: identity.UserID,
+ InstallationID: inst.ID,
+ AgentID: inst.AgentID,
+ RouteRevision: inst.RouteRevision,
+ Message: msg,
+ ClaimToken: claimToken,
+ MediaPendingSeconds: mediaPendingSeconds,
+ })
+ if errors.Is(err, ErrRouteChanged) {
+ if result, done, refreshErr := refreshChangedRoute(); refreshErr != nil {
+ return Result{}, finalizeRelease, refreshErr
+ } else if done {
+ return result, finalizeMark, nil
+ }
+ continue
+ }
+ if err != nil {
+ if errors.Is(err, ErrClaimLost) {
+ return Result{}, finalizeNone, err
+ }
+ return Result{}, finalizeRelease, fmt.Errorf("append user message: %w", err)
}
- return Result{}, finalizeRelease, fmt.Errorf("append user message: %w", err)
+ break
}
// Post-append paths must NOT Release (chat_message + Mark already
diff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.go
index 7fd5661f04..3f7c05e66d 100644
--- a/server/internal/integrations/channel/engine/router_test.go
+++ b/server/internal/integrations/channel/engine/router_test.go
@@ -37,10 +37,45 @@ func (f *fakeIdentity) ResolveSender(_ context.Context, _ ResolvedInstallation,
return f.id, f.err
}
+type fakeValidatedInbound struct {
+ mu sync.Mutex
+ inst ResolvedInstallation
+ insts []ResolvedInstallation
+ err error
+ errs []error
+ callsN int
+}
+
+func (f *fakeValidatedInbound) ResolveValidatedInbound(_ context.Context, inst ResolvedInstallation, _ ResolvedIdentity, _ channel.InboundMessage) (ResolvedInstallation, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.callsN++
+ call := f.callsN - 1
+ resolveErr := f.err
+ if call < len(f.errs) {
+ resolveErr = f.errs[call]
+ }
+ if len(f.insts) >= f.callsN {
+ return f.insts[call], resolveErr
+ }
+ if f.inst.ID.Valid || f.inst.AgentID.Valid {
+ inst = f.inst
+ }
+ return inst, resolveErr
+}
+
+func (f *fakeValidatedInbound) calls() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.callsN
+}
+
type fakeDedup struct {
mu sync.Mutex
token pgtype.UUID
claimErr error
+ respectCtx bool
+ releaseErr error
markCalls int
relCalls int
claimCalls int
@@ -55,28 +90,48 @@ func (f *fakeDedup) Claim(_ context.Context, _ pgtype.UUID, _ string) (pgtype.UU
}
return f.token, nil
}
-func (f *fakeDedup) Mark(_ context.Context, _ pgtype.UUID, _ string, _ pgtype.UUID) error {
+func (f *fakeDedup) Mark(ctx context.Context, _ pgtype.UUID, _ string, _ pgtype.UUID) error {
f.mu.Lock()
defer f.mu.Unlock()
+ if f.respectCtx && ctx.Err() != nil {
+ return ctx.Err()
+ }
f.markCalls++
return nil
}
-func (f *fakeDedup) Release(_ context.Context, _ pgtype.UUID, _ string, _ pgtype.UUID) error {
+func (f *fakeDedup) Release(ctx context.Context, _ pgtype.UUID, _ string, _ pgtype.UUID) error {
f.mu.Lock()
defer f.mu.Unlock()
+ if f.respectCtx && ctx.Err() != nil {
+ f.releaseErr = ctx.Err()
+ return ctx.Err()
+ }
f.relCalls++
return nil
}
func (f *fakeDedup) marks() int { f.mu.Lock(); defer f.mu.Unlock(); return f.markCalls }
func (f *fakeDedup) releases() int { f.mu.Lock(); defer f.mu.Unlock(); return f.relCalls }
+func (f *fakeDedup) releaseError() error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.releaseErr
+}
type fakeBinder struct {
mu sync.Mutex
ensureID pgtype.UUID
ensureErr error
+ ensureErrs []error
+ ensureCalls int
+ ensureParams []EnsureSessionParams
+ ensureHook func(int)
appendResult AppendResult
parseIssue bool
appendErr error
+ appendErrs []error
+ appendCalls int
+ appended []AppendParams
+ appendHook func(int)
appendDelay time.Duration
bindErr error
lastEnsure EnsureSessionParams
@@ -87,8 +142,21 @@ type fakeBinder struct {
}
func (f *fakeBinder) EnsureSession(_ context.Context, p EnsureSessionParams) (pgtype.UUID, error) {
+ f.mu.Lock()
f.lastEnsure = p
- return f.ensureID, f.ensureErr
+ f.ensureCalls++
+ f.ensureParams = append(f.ensureParams, p)
+ err := f.ensureErr
+ if len(f.ensureErrs) > 0 {
+ err = f.ensureErrs[0]
+ f.ensureErrs = f.ensureErrs[1:]
+ }
+ call, hook := f.ensureCalls, f.ensureHook
+ f.mu.Unlock()
+ if hook != nil {
+ hook(call)
+ }
+ return f.ensureID, err
}
func (f *fakeBinder) MarkPendingFresh(_ context.Context, _ pgtype.UUID) error {
f.mu.Lock()
@@ -100,7 +168,12 @@ func (f *fakeBinder) AppendMessage(_ context.Context, p AppendParams) (AppendRes
f.mu.Lock()
delay := f.appendDelay
f.lastAppend = p
+ f.appendCalls++
res, err := f.appendResult, f.appendErr
+ if len(f.appendErrs) > 0 {
+ err = f.appendErrs[0]
+ f.appendErrs = f.appendErrs[1:]
+ }
if f.parseIssue {
commandSource := p.Message.CommandText
if commandSource == "" {
@@ -108,12 +181,40 @@ func (f *fakeBinder) AppendMessage(_ context.Context, p AppendParams) (AppendRes
}
res.IssueCommand, _ = ParseIssueCommand(commandSource)
}
+ if err == nil {
+ f.appended = append(f.appended, p)
+ }
+ call, hook := f.appendCalls, f.appendHook
f.mu.Unlock()
+ if hook != nil {
+ hook(call)
+ }
if delay > 0 {
time.Sleep(delay)
}
return res, err
}
+
+func (f *fakeBinder) appends() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.appendCalls
+}
+func (f *fakeBinder) ensures() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.ensureCalls
+}
+func (f *fakeBinder) ensureAttempts() []EnsureSessionParams {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]EnsureSessionParams(nil), f.ensureParams...)
+}
+func (f *fakeBinder) successfulAppends() []AppendParams {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]AppendParams(nil), f.appended...)
+}
func (f *fakeBinder) BindMedia(_ context.Context, p BindMediaParams) error {
f.mu.Lock()
defer f.mu.Unlock()
@@ -366,26 +467,28 @@ func p2pMessage(t *testing.T) channel.InboundMessage {
}
type harness struct {
- router *Router
- inst *fakeInstaller
- ident *fakeIdentity
- dedup *fakeDedup
- binder *fakeBinder
- audit *fakeAuditor
- replier *fakeReplier
- typing *fakeTyping
- media *fakeMedia
- issues *fakeIssues
- tasks *fakeTasks
- reader *fakeReader
+ router *Router
+ inst *fakeInstaller
+ ident *fakeIdentity
+ validated *fakeValidatedInbound
+ dedup *fakeDedup
+ binder *fakeBinder
+ audit *fakeAuditor
+ replier *fakeReplier
+ typing *fakeTyping
+ media *fakeMedia
+ issues *fakeIssues
+ tasks *fakeTasks
+ reader *fakeReader
}
func newHarness(t *testing.T) *harness {
t.Helper()
h := &harness{
- inst: &fakeInstaller{inst: activeResolved(t)},
- ident: &fakeIdentity{id: ResolvedIdentity{UserID: uuidFromString(t, "44444444-4444-4444-4444-444444444444")}},
- dedup: &fakeDedup{token: uuidFromString(t, "55555555-5555-5555-5555-555555555555")},
+ inst: &fakeInstaller{inst: activeResolved(t)},
+ ident: &fakeIdentity{id: ResolvedIdentity{UserID: uuidFromString(t, "44444444-4444-4444-4444-444444444444")}},
+ validated: &fakeValidatedInbound{},
+ dedup: &fakeDedup{token: uuidFromString(t, "55555555-5555-5555-5555-555555555555")},
binder: &fakeBinder{
ensureID: uuidFromString(t, "66666666-6666-6666-6666-666666666666"),
appendResult: AppendResult{
@@ -402,9 +505,15 @@ func newHarness(t *testing.T) *harness {
reader: &fakeReader{ws: db.Workspace{IssuePrefix: "MUL"}},
}
h.router = NewRouter(h.issues, h.tasks, h.reader, RouterConfig{Logger: discardLogger()})
+ h.register(h.validated)
+ return h
+}
+
+func (h *harness) register(validated ValidatedInboundResolver) {
h.router.Register(channel.TypeFeishu, ResolverSet{
Installation: h.inst,
Identity: h.ident,
+ Validated: validated,
Dedup: h.dedup,
Session: h.binder,
Audit: h.audit,
@@ -413,7 +522,6 @@ func newHarness(t *testing.T) *harness {
Media: h.media,
OriginType: "lark_chat",
})
- return h
}
func TestRouter_NoResolverSet_ReturnsError(t *testing.T) {
@@ -484,6 +592,9 @@ func TestRouter_GroupNotAddressed_Drops(t *testing.T) {
if h.media.calls() != 0 {
t.Fatal("unaddressed group message must not resolve media")
}
+ if h.validated.calls() != 0 {
+ t.Fatal("unaddressed group message must not run validated discovery")
+ }
}
func TestRouter_UnboundSender_NeedsBinding(t *testing.T) {
@@ -501,6 +612,9 @@ func TestRouter_UnboundSender_NeedsBinding(t *testing.T) {
if h.media.calls() != 0 {
t.Fatal("unbound sender must not resolve media")
}
+ if h.validated.calls() != 0 {
+ t.Fatal("unbound sender must not run validated discovery")
+ }
if !waitFor(time.Second, func() bool {
for _, r := range h.replier.calls() {
if r.Outcome == OutcomeNeedsBinding && r.Sender == "ou_user_a" {
@@ -525,6 +639,256 @@ func TestRouter_NonMember_Drops(t *testing.T) {
if h.media.calls() != 0 {
t.Fatal("non-member sender must not resolve media")
}
+ if h.validated.calls() != 0 {
+ t.Fatal("non-member sender must not run validated discovery")
+ }
+}
+
+func TestRouter_ArchivedValidatedRouteRepliesWithoutCreatingSession(t *testing.T) {
+ h := newHarness(t)
+ h.validated.err = ErrTargetAgentArchived
+ msg := p2pMessage(t)
+ msg.Source.ChatType = channel.ChatTypeGroup
+ msg.AddressedToBot = true
+
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("archived route must be a product outcome, got %v", err)
+ }
+ if h.validated.calls() != 1 {
+ t.Fatalf("validated discovery calls = %d, want 1", h.validated.calls())
+ }
+ if h.binder.lastEnsure.Installation.ID.Valid {
+ t.Fatal("archived route must not create or reuse a chat session")
+ }
+ if h.dedup.marks() != 1 {
+ t.Fatalf("archived route must finalize dedup, got %d marks", h.dedup.marks())
+ }
+ if !waitFor(time.Second, func() bool {
+ for _, result := range h.replier.calls() {
+ if result.Outcome == OutcomeAgentArchived {
+ return true
+ }
+ }
+ return false
+ }) {
+ t.Fatal("archived route did not emit the standard archived-agent reply")
+ }
+}
+
+func TestRouter_RouteFenceConflictRefreshesAndRetriesSameClaim(t *testing.T) {
+ h := newHarness(t)
+ oldRoute := activeResolved(t)
+ oldRoute.RouteRevision = 1
+ newRoute := oldRoute
+ newRoute.AgentID = uuidFromString(t, "77777777-7777-4777-8777-777777777777")
+ newRoute.RouteRevision = 2
+ h.inst.inst = oldRoute
+ h.validated.insts = []ResolvedInstallation{oldRoute, newRoute}
+ h.binder.appendErrs = []error{ErrRouteChanged, nil}
+
+ msg := p2pMessage(t)
+ msg.Source.ChatType = channel.ChatTypeGroup
+ msg.AddressedToBot = true
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("route fence retry: %v", err)
+ }
+ if h.validated.calls() != 2 {
+ t.Fatalf("validated route resolutions = %d, want initial + refresh", h.validated.calls())
+ }
+ if h.binder.appends() != 2 {
+ t.Fatalf("append attempts = %d, want conflict + retry", h.binder.appends())
+ }
+ if h.binder.lastAppend.AgentID != newRoute.AgentID || h.binder.lastAppend.RouteRevision != 2 {
+ t.Fatalf("retry append route = agent %v revision %d, want agent %v revision 2", h.binder.lastAppend.AgentID, h.binder.lastAppend.RouteRevision, newRoute.AgentID)
+ }
+ appended := h.binder.successfulAppends()
+ if len(appended) != 1 || appended[0].AgentID != newRoute.AgentID || appended[0].ClaimToken != h.dedup.token {
+ t.Fatalf("durable appends = %+v, want one append on the new route with the original claim", appended)
+ }
+ if h.dedup.marks() != 0 || h.dedup.releases() != 0 {
+ t.Fatalf("successful in-tx retry finalization = marks %d releases %d, want 0/0", h.dedup.marks(), h.dedup.releases())
+ }
+}
+
+func TestRouter_EnsureSessionConflictRefreshesAndRetriesSameClaim(t *testing.T) {
+ h := newHarness(t)
+ oldRoute := activeResolved(t)
+ oldRoute.RouteRevision = 1
+ newRoute := oldRoute
+ newRoute.AgentID = uuidFromString(t, "77777777-7777-4777-8777-777777777777")
+ newRoute.RouteRevision = 2
+ h.inst.inst = oldRoute
+ h.validated.insts = []ResolvedInstallation{oldRoute, newRoute}
+ h.binder.ensureErrs = []error{ErrRouteChanged, nil}
+
+ msg := p2pMessage(t)
+ msg.Source.ChatType = channel.ChatTypeGroup
+ msg.AddressedToBot = true
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("ensure-session route retry: %v", err)
+ }
+
+ ensures := h.binder.ensureAttempts()
+ if len(ensures) != 2 || ensures[0].Installation.AgentID != oldRoute.AgentID || ensures[1].Installation.AgentID != newRoute.AgentID {
+ t.Fatalf("ensure attempts = %+v, want old route then new route", ensures)
+ }
+ appended := h.binder.successfulAppends()
+ if len(appended) != 1 || appended[0].AgentID != newRoute.AgentID || appended[0].ClaimToken != h.dedup.token {
+ t.Fatalf("durable appends = %+v, want one append on the new route with the original claim", appended)
+ }
+ if h.dedup.marks() != 0 || h.dedup.releases() != 0 {
+ t.Fatalf("successful in-tx retry finalization = marks %d releases %d, want 0/0", h.dedup.marks(), h.dedup.releases())
+ }
+}
+
+func TestRouter_RouteConflictRefreshTerminalPaths(t *testing.T) {
+ refreshInfraErr := errors.New("route refresh database unavailable")
+ for _, tc := range []struct {
+ name string
+ phase string
+ refreshErr error
+ wantError bool
+ wantMarks int
+ wantRelease int
+ }{
+ {name: "ensure conflict archived target", phase: "ensure", refreshErr: ErrTargetAgentArchived, wantMarks: 1},
+ {name: "ensure conflict refresh infrastructure error", phase: "ensure", refreshErr: refreshInfraErr, wantError: true, wantRelease: 1},
+ {name: "append conflict archived target", phase: "append", refreshErr: ErrTargetAgentArchived, wantMarks: 1},
+ {name: "append conflict refresh infrastructure error", phase: "append", refreshErr: refreshInfraErr, wantError: true, wantRelease: 1},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ h := newHarness(t)
+ h.dedup.respectCtx = true
+ oldRoute := activeResolved(t)
+ oldRoute.RouteRevision = 1
+ refreshedRoute := oldRoute
+ refreshedRoute.AgentID = uuidFromString(t, "77777777-7777-4777-8777-777777777777")
+ refreshedRoute.RouteRevision = 2
+ h.inst.inst = oldRoute
+ h.validated.insts = []ResolvedInstallation{oldRoute, refreshedRoute}
+ h.validated.errs = []error{nil, tc.refreshErr}
+ if tc.phase == "ensure" {
+ h.binder.ensureErr = ErrRouteChanged
+ } else {
+ h.binder.appendErr = ErrRouteChanged
+ }
+
+ msg := p2pMessage(t)
+ msg.Source.ChatType = channel.ChatTypeGroup
+ msg.AddressedToBot = true
+ err := h.router.Handle(context.Background(), msg)
+ if (err != nil) != tc.wantError {
+ t.Fatalf("Handle error = %v, wantError %v", err, tc.wantError)
+ }
+ if tc.wantError && !errors.Is(err, tc.refreshErr) {
+ t.Fatalf("Handle error = %v, want wrapped refresh error %v", err, tc.refreshErr)
+ }
+ if h.validated.calls() != 2 {
+ t.Fatalf("validated route resolutions = %d, want initial + refresh", h.validated.calls())
+ }
+ if got := len(h.binder.successfulAppends()); got != 0 {
+ t.Fatalf("old route received %d successful appends, want 0", got)
+ }
+ if h.dedup.marks() != tc.wantMarks || h.dedup.releases() != tc.wantRelease {
+ t.Fatalf("claim finalization = marks %d releases %d, want %d/%d", h.dedup.marks(), h.dedup.releases(), tc.wantMarks, tc.wantRelease)
+ }
+ if errors.Is(tc.refreshErr, ErrTargetAgentArchived) && !waitFor(time.Second, func() bool {
+ for _, result := range h.replier.calls() {
+ if result.Outcome == OutcomeAgentArchived {
+ return true
+ }
+ }
+ return false
+ }) {
+ t.Fatal("archived refresh did not emit the archived-agent outcome")
+ }
+ })
+ }
+}
+
+func TestRouter_RouteConflictWithoutValidatedResolverReleasesClaim(t *testing.T) {
+ h := newHarness(t)
+ h.register(nil)
+ h.binder.ensureErr = ErrRouteChanged
+
+ err := h.router.Handle(context.Background(), p2pMessage(t))
+ if !errors.Is(err, ErrRouteChanged) {
+ t.Fatalf("missing validated resolver error = %v, want route changed", err)
+ }
+ if h.dedup.marks() != 0 || h.dedup.releases() != 1 {
+ t.Fatalf("claim finalization = marks %d releases %d, want 0/1", h.dedup.marks(), h.dedup.releases())
+ }
+ if got := len(h.binder.successfulAppends()); got != 0 {
+ t.Fatalf("old route received %d successful appends, want 0", got)
+ }
+}
+
+func TestRouter_SessionAppendLockFailureReleasesClaimWithoutAppending(t *testing.T) {
+ h := newHarness(t)
+ oldRoute := activeResolved(t)
+ oldRoute.RouteRevision = 1
+ h.inst.inst = oldRoute
+ h.validated.inst = oldRoute
+ h.binder.appendErr = errors.New("append route lock unavailable")
+
+ msg := p2pMessage(t)
+ msg.Source.ChatType = channel.ChatTypeGroup
+ msg.AddressedToBot = true
+ if err := h.router.Handle(context.Background(), msg); err == nil {
+ t.Fatal("append-lock infrastructure error must surface")
+ }
+ if h.dedup.marks() != 0 || h.dedup.releases() != 1 {
+ t.Fatalf("claim finalization = marks %d releases %d, want 0/1", h.dedup.marks(), h.dedup.releases())
+ }
+ if got := len(h.binder.successfulAppends()); got != 0 {
+ t.Fatalf("failed append lock recorded %d successful appends, want 0", got)
+ }
+}
+
+func TestRouter_RepeatedRouteConflictsTerminateOnContextCancellation(t *testing.T) {
+ for _, phase := range []string{"ensure", "append"} {
+ t.Run(phase, func(t *testing.T) {
+ h := newHarness(t)
+ h.dedup.respectCtx = true
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ if phase == "ensure" {
+ h.binder.ensureErr = ErrRouteChanged
+ h.binder.ensureHook = func(call int) {
+ if call == 3 {
+ cancel()
+ }
+ }
+ } else {
+ h.binder.appendErr = ErrRouteChanged
+ h.binder.appendHook = func(call int) {
+ if call == 3 {
+ cancel()
+ }
+ }
+ }
+
+ err := h.router.Handle(ctx, p2pMessage(t))
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("repeated %s conflicts error = %v, want context cancellation", phase, err)
+ }
+ if h.dedup.marks() != 0 || h.dedup.releases() != 1 {
+ t.Fatalf("claim finalization = marks %d releases %d, want 0/1", h.dedup.marks(), h.dedup.releases())
+ }
+ if err := h.dedup.releaseError(); err != nil {
+ t.Fatalf("dedup Release inherited cancelled request context: %v", err)
+ }
+ if got := len(h.binder.successfulAppends()); got != 0 {
+ t.Fatalf("old route received %d successful appends, want 0", got)
+ }
+ if phase == "ensure" && h.binder.ensures() != 3 {
+ t.Fatalf("ensure conflicts = %d, want 3 before cancellation", h.binder.ensures())
+ }
+ if phase == "append" && h.binder.appends() != 3 {
+ t.Fatalf("append conflicts = %d, want 3 before cancellation", h.binder.appends())
+ }
+ })
+ }
}
func TestRouter_EnsureSessionError_Releases(t *testing.T) {
diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.go
index ab7a66a214..e34d0290ff 100644
--- a/server/internal/integrations/channel/engine/session.go
+++ b/server/internal/integrations/channel/engine/session.go
@@ -46,6 +46,7 @@ type SessionQueries interface {
LockWorkspaceForChatSessionCreate(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error)
CreateChatSession(ctx context.Context, arg db.CreateChatSessionParams) (db.ChatSession, error)
CreateChannelChatSessionBinding(ctx context.Context, arg db.CreateChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error)
+ LockChatSessionForAppend(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error)
CreateChatMessage(ctx context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error)
ClearChatMessageChannelMediaPending(ctx context.Context, arg db.ClearChatMessageChannelMediaPendingParams) error
LockIssueForChannelMediaBind(ctx context.Context, arg db.LockIssueForChannelMediaBindParams) (pgtype.UUID, error)
@@ -80,6 +81,9 @@ func (a dbSessionQueries) CreateChatSession(ctx context.Context, arg db.CreateCh
func (a dbSessionQueries) CreateChannelChatSessionBinding(ctx context.Context, arg db.CreateChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error) {
return a.q.CreateChannelChatSessionBinding(ctx, arg)
}
+func (a dbSessionQueries) LockChatSessionForAppend(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {
+ return a.q.LockChatSessionForAppend(ctx, id)
+}
func (a dbSessionQueries) CreateChatMessage(ctx context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error) {
return a.q.CreateChatMessage(ctx, arg)
}
@@ -284,6 +288,10 @@ type AppendInput struct {
ClaimToken pgtype.UUID
MediaPendingSeconds float64
ForceFresh bool
+ // BeforeWrite runs inside the append transaction before any durable write.
+ // Adapters use it to acquire a route fence that is held through the message
+ // insert and in-transaction dedup mark.
+ BeforeWrite func(context.Context, pgx.Tx) error
}
// BindMediaInput links already-uploaded media to either an /issue target or a
@@ -322,6 +330,17 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Ap
}
defer tx.Rollback(ctx)
qtx := s.q.WithTx(tx)
+ // Keep the repo-wide teardown order: chat_session before any adapter-owned
+ // route fence. FOR KEY SHARE is sufficient to serialize deletion without
+ // blocking normal non-key session updates or debounced task enqueueing.
+ if _, err := qtx.LockChatSessionForAppend(ctx, in.SessionID); err != nil {
+ return AppendResult{}, fmt.Errorf("lock chat session for append: %w", err)
+ }
+ if in.BeforeWrite != nil {
+ if err := in.BeforeWrite(ctx, tx); err != nil {
+ return AppendResult{}, err
+ }
+ }
commandSource := in.CommandText
if commandSource == "" {
diff --git a/server/internal/integrations/channel/engine/session_test.go b/server/internal/integrations/channel/engine/session_test.go
index 1cb0dbca66..26dfb1ca02 100644
--- a/server/internal/integrations/channel/engine/session_test.go
+++ b/server/internal/integrations/channel/engine/session_test.go
@@ -101,6 +101,10 @@ func (f *fakeSessionQueries) CreateChannelChatSessionBinding(_ context.Context,
return db.ChannelChatSessionBinding{ChatSessionID: arg.ChatSessionID}, nil
}
+func (f *fakeSessionQueries) LockChatSessionForAppend(_ context.Context, id pgtype.UUID) (pgtype.UUID, error) {
+ return id, nil
+}
+
func (f *fakeSessionQueries) CreateChatMessage(_ context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error) {
f.messages = append(f.messages, arg.Content)
f.lastCreate = arg
@@ -298,6 +302,26 @@ func TestAppendUserMessage_PlainText(t *testing.T) {
}
}
+func TestAppendUserMessage_BeforeWriteFenceRejectsWithoutDurableWrites(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ guardCalls := 0
+ _, err := s.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1),
+ Body: "must be rerouted",
+ BeforeWrite: func(_ context.Context, _ pgx.Tx) error {
+ guardCalls++
+ return ErrRouteChanged
+ },
+ })
+ if !errors.Is(err, ErrRouteChanged) {
+ t.Fatalf("append fence error = %v, want route changed", err)
+ }
+ if guardCalls != 1 || len(f.messages) != 0 || f.touched != 0 {
+ t.Fatalf("rejected append guard=%d messages=%d touches=%d, want 1/0/0", guardCalls, len(f.messages), f.touched)
+ }
+}
+
func TestAppendUserMessage_NoReplyTargetWithoutMessageID(t *testing.T) {
f := newFake()
s := newTestSession(f)
diff --git a/server/internal/integrations/dingtalk/byo_install.go b/server/internal/integrations/dingtalk/byo_install.go
index 266cb0a40a..06ac2998fd 100644
--- a/server/internal/integrations/dingtalk/byo_install.go
+++ b/server/internal/integrations/dingtalk/byo_install.go
@@ -38,7 +38,7 @@ type RegisterBYOParams struct {
}
// RegisterBYO installs a user-supplied ("bring your own") DingTalk robot for an
-// agent. The user creates their own DingTalk Stream-mode robot and pastes its
+// default agent. The user creates their own DingTalk Stream-mode robot and pastes its
// AppKey (client id) + AppSecret (client secret). There is NO OAuth code
// exchange: we validate the credentials live by minting an access_token (which
// proves the AppKey/AppSecret pair is valid), encrypt the AppSecret at rest, and
@@ -86,7 +86,9 @@ func (s *InstallService) RegisterBYO(ctx context.Context, p RegisterBYOParams) (
return db.ChannelInstallation{}, fmt.Errorf("encode dingtalk installation config: %w", err)
}
- // Persist one bot per agent (the row is keyed by workspace + agent). The
+ // Persist one installation per default agent (the row is keyed by workspace
+ // + agent). Group routes can target other agents without another Stream
+ // connection. The
// stored config carries the AppKey for inbound routing; persistInstall
// reclaims a DEAD prior owner of that AppKey so the robot can move to this
// agent, and refuses a LIVE owner with an accurate conflict sentinel.
diff --git a/server/internal/integrations/dingtalk/group_route_cleanup_db_test.go b/server/internal/integrations/dingtalk/group_route_cleanup_db_test.go
new file mode 100644
index 0000000000..6b54246b13
--- /dev/null
+++ b/server/internal/integrations/dingtalk/group_route_cleanup_db_test.go
@@ -0,0 +1,238 @@
+package dingtalk
+
+import (
+ "context"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type dingtalkRouteCleanupOwner struct {
+ workspaceID string
+ runtimeID string
+ agentID string
+ installationID string
+ routeID string
+ appID string
+}
+
+func seedDingTalkRouteCleanupOwner(
+ t *testing.T,
+ ctx context.Context,
+ pool *pgxpool.Pool,
+ kind string,
+ status string,
+) dingtalkRouteCleanupOwner {
+ t.Helper()
+ owner := dingtalkRouteCleanupOwner{
+ workspaceID: uuid.NewString(),
+ runtimeID: uuid.NewString(),
+ }
+ slug := "dingtalk-route-cleanup-" + uuid.NewString()
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO workspace (id, name, slug, description)
+ VALUES ($1, 'DingTalk route cleanup', $2, '')
+ `, owner.workspaceID, slug); err != nil {
+ t.Fatalf("seed cleanup workspace: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO agent_runtime (id, workspace_id, name, runtime_mode, provider)
+ VALUES ($1, $2, 'DingTalk cleanup runtime', 'local', 'multica_daemon')
+ `, owner.runtimeID, owner.workspaceID); err != nil {
+ t.Fatalf("seed cleanup runtime: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM dingtalk_group_route WHERE workspace_id = $1`, owner.workspaceID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_installation WHERE workspace_id = $1`, owner.workspaceID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, owner.workspaceID)
+ })
+ return seedDingTalkRouteCleanupAgent(t, ctx, pool, owner, kind, status)
+}
+
+func seedDingTalkRouteCleanupAgent(
+ t *testing.T,
+ ctx context.Context,
+ pool *pgxpool.Pool,
+ owner dingtalkRouteCleanupOwner,
+ kind string,
+ status string,
+) dingtalkRouteCleanupOwner {
+ t.Helper()
+ owner.agentID = uuid.NewString()
+ owner.installationID = uuid.NewString()
+ owner.routeID = uuid.NewString()
+ owner.appID = "dingtalk-route-cleanup-" + uuid.NewString()
+ systemKey := ""
+ if kind == "system" {
+ systemKey = "dingtalk_cleanup_" + uuid.NewString()
+ }
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO agent (
+ id, workspace_id, name, runtime_mode, runtime_id, kind, system_key
+ ) VALUES ($1, $2, $6, 'local', $3, $4, NULLIF($5, ''))
+ `, owner.agentID, owner.workspaceID, owner.runtimeID, kind, systemKey, "DingTalk cleanup "+owner.agentID); err != nil {
+ t.Fatalf("seed cleanup agent: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO channel_installation (
+ id, workspace_id, agent_id, channel_type, config, installer_user_id, status
+ ) VALUES (
+ $1, $2, $3, 'dingtalk', jsonb_build_object('app_id', $4::text), $5, $6
+ )
+ `, owner.installationID, owner.workspaceID, owner.agentID, owner.appID, uuid.NewString(), status); err != nil {
+ t.Fatalf("seed cleanup installation: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO dingtalk_group_route (
+ id, workspace_id, installation_id, conversation_id, conversation_title, agent_id
+ ) VALUES ($1, $2, $3, $4, 'DingTalk cleanup group', $5)
+ `, owner.routeID, owner.workspaceID, owner.installationID, "cid-"+owner.routeID, owner.agentID); err != nil {
+ t.Fatalf("seed cleanup group route: %v", err)
+ }
+ return owner
+}
+
+func assertDingTalkRouteCleanupState(
+ t *testing.T,
+ ctx context.Context,
+ pool *pgxpool.Pool,
+ owner dingtalkRouteCleanupOwner,
+ want int,
+) {
+ t.Helper()
+ var routes, installations int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM dingtalk_group_route WHERE id = $1`, owner.routeID).Scan(&routes); err != nil {
+ t.Fatalf("count cleanup routes: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM channel_installation WHERE id = $1`, owner.installationID).Scan(&installations); err != nil {
+ t.Fatalf("count cleanup installations: %v", err)
+ }
+ if routes != want || installations != want {
+ t.Fatalf(
+ "cleanup owner route/installation rows = %d/%d, want %d/%d",
+ routes,
+ installations,
+ want,
+ want,
+ )
+ }
+}
+
+func assertDingTalkRouteCount(
+ t *testing.T,
+ ctx context.Context,
+ pool *pgxpool.Pool,
+ owner dingtalkRouteCleanupOwner,
+ want int,
+) {
+ t.Helper()
+ var routes int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM dingtalk_group_route WHERE id = $1`, owner.routeID).Scan(&routes); err != nil {
+ t.Fatalf("count cleanup routes: %v", err)
+ }
+ if routes != want {
+ t.Fatalf("cleanup owner route rows = %d, want %d", routes, want)
+ }
+}
+
+func requireDingTalkRouteCleanupSchema(t *testing.T, pool *pgxpool.Pool) {
+ t.Helper()
+ var present bool
+ if err := pool.QueryRow(context.Background(), `SELECT to_regclass('public.dingtalk_group_route') IS NOT NULL`).Scan(&present); err != nil || !present {
+ t.Skip("dingtalk_group_route not present (database not migrated)")
+ }
+}
+
+func TestDeleteDingTalkInstallationForReplacementCleansOnlyTargetRoutes(t *testing.T) {
+ pool := dingtalkInstallTestDB(t)
+ requireDingTalkRouteCleanupSchema(t, pool)
+ ctx := context.Background()
+ target := seedDingTalkRouteCleanupOwner(t, ctx, pool, "user", "active")
+ unrelated := seedDingTalkRouteCleanupOwner(t, ctx, pool, "user", "active")
+
+ if _, err := db.New(pool).DeleteDingTalkInstallationForReplacement(ctx, db.DeleteDingTalkInstallationForReplacementParams{
+ InstallationID: util.MustParseUUID(target.installationID),
+ WorkspaceID: util.MustParseUUID(target.workspaceID),
+ AgentID: util.MustParseUUID(target.agentID),
+ }); err != nil {
+ t.Fatalf("DeleteDingTalkInstallationForReplacement: %v", err)
+ }
+
+ assertDingTalkRouteCleanupState(t, ctx, pool, target, 0)
+ assertDingTalkRouteCleanupState(t, ctx, pool, unrelated, 1)
+}
+
+func TestReclaimDeadChannelInstallationByAppIDCleansOnlyDeadRoutes(t *testing.T) {
+ pool := dingtalkInstallTestDB(t)
+ requireDingTalkRouteCleanupSchema(t, pool)
+ ctx := context.Background()
+ dead := seedDingTalkRouteCleanupOwner(t, ctx, pool, "user", "revoked")
+ live := seedDingTalkRouteCleanupOwner(t, ctx, pool, "user", "active")
+
+ if _, err := db.New(pool).ReclaimDeadChannelInstallationByAppID(ctx, db.ReclaimDeadChannelInstallationByAppIDParams{
+ ChannelType: "dingtalk",
+ AppID: dead.appID,
+ WorkspaceID: util.MustParseUUID(live.workspaceID),
+ AgentID: util.MustParseUUID(live.agentID),
+ }); err != nil {
+ t.Fatalf("ReclaimDeadChannelInstallationByAppID: %v", err)
+ }
+
+ assertDingTalkRouteCleanupState(t, ctx, pool, dead, 0)
+ assertDingTalkRouteCleanupState(t, ctx, pool, live, 1)
+}
+
+func TestDeleteChannelInstallationsBySystemRuntimeAgentsCleansOnlySystemRoutes(t *testing.T) {
+ pool := dingtalkInstallTestDB(t)
+ requireDingTalkRouteCleanupSchema(t, pool)
+ ctx := context.Background()
+ systemOwner := seedDingTalkRouteCleanupOwner(t, ctx, pool, "system", "active")
+ userOwner := seedDingTalkRouteCleanupAgent(t, ctx, pool, systemOwner, "user", "active")
+
+ if err := db.New(pool).DeleteChannelInstallationsBySystemRuntimeAgents(
+ ctx,
+ util.MustParseUUID(systemOwner.runtimeID),
+ ); err != nil {
+ t.Fatalf("DeleteChannelInstallationsBySystemRuntimeAgents: %v", err)
+ }
+
+ assertDingTalkRouteCleanupState(t, ctx, pool, systemOwner, 0)
+ assertDingTalkRouteCleanupState(t, ctx, pool, userOwner, 1)
+}
+
+func TestDeleteWorkspaceCleansOnlyWorkspaceDingTalkRoutes(t *testing.T) {
+ pool := dingtalkInstallTestDB(t)
+ requireDingTalkRouteCleanupSchema(t, pool)
+ ctx := context.Background()
+ target := seedDingTalkRouteCleanupOwner(t, ctx, pool, "user", "active")
+ unrelated := seedDingTalkRouteCleanupOwner(t, ctx, pool, "user", "active")
+
+ if err := db.New(pool).DeleteWorkspace(ctx, util.MustParseUUID(target.workspaceID)); err != nil {
+ t.Fatalf("DeleteWorkspace: %v", err)
+ }
+
+ assertDingTalkRouteCleanupState(t, ctx, pool, target, 0)
+ assertDingTalkRouteCleanupState(t, ctx, pool, unrelated, 1)
+}
+
+func TestDeleteWorkspaceLeafDataCleansOnlyWorkspaceDingTalkRoutes(t *testing.T) {
+ pool := dingtalkInstallTestDB(t)
+ requireDingTalkRouteCleanupSchema(t, pool)
+ ctx := context.Background()
+ target := seedDingTalkRouteCleanupOwner(t, ctx, pool, "user", "active")
+ unrelated := seedDingTalkRouteCleanupOwner(t, ctx, pool, "user", "active")
+
+ if err := db.New(pool).DeleteWorkspaceLeafData(ctx, util.MustParseUUID(target.workspaceID)); err != nil {
+ t.Fatalf("DeleteWorkspaceLeafData: %v", err)
+ }
+
+ // This is the handler's first-stage route cleanup. Installations are
+ // deliberately removed by later teardown steps, so only the target route is
+ // expected to be gone at this point.
+ assertDingTalkRouteCount(t, ctx, pool, target, 0)
+ assertDingTalkRouteCleanupState(t, ctx, pool, unrelated, 1)
+}
diff --git a/server/internal/integrations/dingtalk/group_route_db_test.go b/server/internal/integrations/dingtalk/group_route_db_test.go
new file mode 100644
index 0000000000..3cfe1ac22a
--- /dev/null
+++ b/server/internal/integrations/dingtalk/group_route_db_test.go
@@ -0,0 +1,553 @@
+package dingtalk
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestDingTalkGroupRoute_DiscoverReassignAndFenceStaleSessionDB(t *testing.T) {
+ pool := dingtalkInstallTestDB(t)
+ ctx := context.Background()
+ var migrated bool
+ if err := pool.QueryRow(ctx, `SELECT to_regclass('public.dingtalk_group_route') IS NOT NULL`).Scan(&migrated); err != nil || !migrated {
+ t.Skip("dingtalk group route table not present (database not migrated)")
+ }
+ observerConn, connectErr := pgx.ConnectConfig(ctx, pool.Config().ConnConfig.Copy())
+ if connectErr != nil {
+ t.Fatalf("connect PostgreSQL lock observer: %v", connectErr)
+ }
+ t.Cleanup(func() { _ = observerConn.Close(context.Background()) })
+
+ const (
+ workspaceID = "d2480000-0000-4000-8000-000000000001"
+ runtimeID = "d2480000-0000-4000-8000-000000000002"
+ defaultAgent = "d2480000-0000-4000-8000-000000000003"
+ routedAgent = "d2480000-0000-4000-8000-000000000004"
+ installerID = "d2480000-0000-4000-8000-000000000005"
+ installation = "d2480000-0000-4000-8000-000000000006"
+ chatSessionID = "d2480000-0000-4000-8000-000000000007"
+ chatSessionB = "d2480000-0000-4000-8000-000000000008"
+ conversation = "cid-dingtalk-multi-agent-group"
+ appKey = "dingtalk_multi_agent_group_app"
+ )
+
+ clean := func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_outbound_card_message WHERE chat_session_id IN ($1, $2)`, chatSessionID, chatSessionB)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE chat_session_id IN ($1, $2)`, chatSessionID, chatSessionB)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM dingtalk_group_route WHERE installation_id = $1`, installation)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_inbound_message_dedup WHERE installation_id = $1`, installation)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installation)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, workspaceID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, installerID)
+ }
+ clean()
+ t.Cleanup(clean)
+
+ exec := func(query string, args ...any) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, query, args...); err != nil {
+ t.Fatalf("seed group route fixture: %v", err)
+ }
+ }
+ exec(`INSERT INTO "user" (id, name, email) VALUES ($1, 'DingTalk route owner', '[email protected]')`, installerID)
+ exec(`INSERT INTO workspace (id, name, slug, description) VALUES ($1, 'DingTalk routes', 'dingtalk-routes-db', '')`, workspaceID)
+ exec(`INSERT INTO agent_runtime (id, workspace_id, name, runtime_mode, provider) VALUES ($1, $2, 'DingTalk route runtime', 'local', 'multica_daemon')`, runtimeID, workspaceID)
+ for _, agent := range []string{defaultAgent, routedAgent} {
+ exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode, runtime_id) VALUES ($1, $2, $3, 'local', $4)`, agent, workspaceID, "DingTalk route "+agent, runtimeID)
+ }
+ exec(`INSERT INTO chat_session (id, workspace_id, agent_id, creator_id, title) VALUES ($1, $2, $3, $4, 'DingTalk route A')`, chatSessionID, workspaceID, defaultAgent, installerID)
+ exec(`INSERT INTO chat_session (id, workspace_id, agent_id, creator_id, title) VALUES ($1, $2, $3, $4, 'DingTalk route B')`, chatSessionB, workspaceID, routedAgent, installerID)
+ exec(`INSERT INTO channel_installation (id, workspace_id, agent_id, channel_type, config, installer_user_id) VALUES ($1, $2, $3, 'dingtalk', jsonb_build_object('app_id', $4::text), $5)`, installation, workspaceID, defaultAgent, appKey, installerID)
+
+ queries := db.New(pool)
+ // Revocation is a query-level fail-closed boundary, not only a Router gate:
+ // a callback that reaches discovery after revoke must neither create a route
+ // nor expose anything through the workspace list.
+ exec(`UPDATE channel_installation SET status = 'revoked' WHERE id = $1`, installation)
+ _, err := queries.DiscoverDingTalkGroupRoute(ctx, db.DiscoverDingTalkGroupRouteParams{
+ InstallationID: util.MustParseUUID(installation), WorkspaceID: util.MustParseUUID(workspaceID),
+ ConversationID: "cid-revoked-before-discovery", ConversationTitle: "Revoked secret group",
+ })
+ if !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("discover route after revoke error = %v, want no rows", err)
+ }
+ var revokedDiscoveryCount int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM dingtalk_group_route WHERE installation_id = $1`, installation).Scan(&revokedDiscoveryCount); err != nil || revokedDiscoveryCount != 0 {
+ t.Fatalf("routes created after pre-discovery revoke = %d, err=%v", revokedDiscoveryCount, err)
+ }
+ revokedRoutes, err := queries.ListDingTalkGroupRoutesByWorkspace(ctx, util.MustParseUUID(workspaceID))
+ if err != nil || len(revokedRoutes) != 0 {
+ t.Fatalf("routes listed after pre-discovery revoke = %+v, err=%v", revokedRoutes, err)
+ }
+ exec(`UPDATE channel_installation SET status = 'active' WHERE id = $1`, installation)
+
+ // Controlled revoke-wins interleaving: discovery starts from an active
+ // snapshot but must block on the installation row, re-check status after the
+ // revoke commits, and return no rows without persisting the group metadata.
+ revokeTx, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin controlled pre-discovery revoke: %v", err)
+ }
+ defer revokeTx.Rollback(context.Background())
+ if _, err := revokeTx.Exec(ctx, `UPDATE channel_installation SET status = 'revoked' WHERE id = $1`, installation); err != nil {
+ t.Fatalf("lock installation for controlled revoke: %v", err)
+ }
+ discoveryConn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire controlled discovery connection: %v", err)
+ }
+ defer discoveryConn.Release()
+ var discoveryPID int32
+ if err := discoveryConn.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&discoveryPID); err != nil {
+ t.Fatalf("read controlled discovery backend pid: %v", err)
+ }
+ discoveryDone := make(chan error, 1)
+ go func() {
+ _, discoverErr := db.New(discoveryConn).DiscoverDingTalkGroupRoute(context.Background(), db.DiscoverDingTalkGroupRouteParams{
+ InstallationID: util.MustParseUUID(installation), WorkspaceID: util.MustParseUUID(workspaceID),
+ ConversationID: "cid-revoke-race", ConversationTitle: "Revoke race secret group",
+ })
+ discoveryDone <- discoverErr
+ }()
+ waitForDingTalkBackendBlocked(t, observerConn, discoveryPID)
+ if err := revokeTx.Commit(ctx); err != nil {
+ t.Fatalf("commit controlled pre-discovery revoke: %v", err)
+ }
+ select {
+ case discoverErr := <-discoveryDone:
+ if !errors.Is(discoverErr, pgx.ErrNoRows) {
+ t.Fatalf("revoke-wins discovery error = %v, want no rows", discoverErr)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("discovery did not resume after revoke committed")
+ }
+ discoveryConn.Release()
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM dingtalk_group_route WHERE installation_id = $1`, installation).Scan(&revokedDiscoveryCount); err != nil || revokedDiscoveryCount != 0 {
+ t.Fatalf("revoke-wins discovery persisted %d routes, err=%v", revokedDiscoveryCount, err)
+ }
+ exec(`UPDATE channel_installation SET status = 'active' WHERE id = $1`, installation)
+
+ resolved, err := queries.DiscoverDingTalkGroupRoute(ctx, db.DiscoverDingTalkGroupRouteParams{
+ InstallationID: util.MustParseUUID(installation), WorkspaceID: util.MustParseUUID(workspaceID),
+ ConversationID: conversation, ConversationTitle: "Platform team",
+ })
+ if err != nil {
+ t.Fatalf("discover group: %v", err)
+ }
+ if resolved.AgentID != util.MustParseUUID(defaultAgent) || !resolved.AgentActive {
+ t.Fatalf("new group route = %+v, want active installation default", resolved)
+ }
+ routes, err := queries.ListDingTalkGroupRoutesByWorkspace(ctx, util.MustParseUUID(workspaceID))
+ if err != nil || len(routes) != 1 {
+ t.Fatalf("list discovered routes = %d, err=%v", len(routes), err)
+ }
+
+ // Upgrade regression: pre-routing DingTalk group bindings have no agent_id
+ // stamp. They must survive when the effective route still equals the
+ // installation's default agent.
+ exec(`INSERT INTO channel_chat_session_binding (chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, config) VALUES ($1, $2, 'dingtalk', $3, 'group', '{}'::jsonb)`, chatSessionID, installation, conversation)
+ exec(`INSERT INTO channel_outbound_card_message (chat_session_id, channel_type, channel_chat_id, channel_card_message_id) VALUES ($1, 'dingtalk', $2, 'old-agent-reply')`, chatSessionID, conversation)
+ preserved, err := queries.DeleteDingTalkStaleGroupChatBinding(ctx, db.DeleteDingTalkStaleGroupChatBindingParams{
+ InstallationID: util.MustParseUUID(installation), ConversationID: conversation, AgentID: util.MustParseUUID(defaultAgent),
+ })
+ if err != nil || preserved != 0 {
+ t.Fatalf("legacy binding guard cleared %d bindings, err=%v; want preserve", preserved, err)
+ }
+ if _, err := queries.GetChannelChatSessionBinding(ctx, db.GetChannelChatSessionBindingParams{
+ InstallationID: util.MustParseUUID(installation), ChannelChatID: conversation,
+ }); err != nil {
+ t.Fatalf("legacy default-agent binding was not preserved: %v", err)
+ }
+
+ updated, err := queries.ReassignDingTalkGroupRoute(ctx, db.ReassignDingTalkGroupRouteParams{
+ ID: routes[0].ID, WorkspaceID: util.MustParseUUID(workspaceID), AgentID: util.MustParseUUID(routedAgent),
+ })
+ if err != nil {
+ t.Fatalf("reassign group: %v", err)
+ }
+ if updated.AgentID != util.MustParseUUID(routedAgent) {
+ t.Fatalf("updated group agent = %s", util.UUIDToString(updated.AgentID))
+ }
+ if _, err := queries.GetChannelChatSessionBinding(ctx, db.GetChannelChatSessionBindingParams{
+ InstallationID: util.MustParseUUID(installation), ChannelChatID: conversation,
+ }); !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("old group binding survived reassignment: %v", err)
+ }
+
+ // Simulate an old-agent inbound turn that resolved just before the update
+ // and created its binding just after it. The next routed turn must retire it.
+ exec(`INSERT INTO channel_chat_session_binding (chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, config) VALUES ($1, $2, 'dingtalk', $3, 'group', jsonb_build_object('agent_id', $4::text))`, chatSessionID, installation, conversation, defaultAgent)
+ cleared, err := queries.DeleteDingTalkStaleGroupChatBinding(ctx, db.DeleteDingTalkStaleGroupChatBindingParams{
+ InstallationID: util.MustParseUUID(installation), ConversationID: conversation, AgentID: util.MustParseUUID(routedAgent),
+ })
+ if err != nil {
+ t.Fatalf("fence stale group binding: %v", err)
+ }
+ if cleared != 1 {
+ t.Fatalf("cleared stale group bindings = %d, want 1", cleared)
+ }
+ if _, err := queries.GetChannelChatSessionBinding(ctx, db.GetChannelChatSessionBindingParams{
+ InstallationID: util.MustParseUUID(installation), ChannelChatID: conversation,
+ }); !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("late old-agent binding survived guard: %v", err)
+ }
+
+ resolved, err = queries.DiscoverDingTalkGroupRoute(ctx, db.DiscoverDingTalkGroupRouteParams{
+ InstallationID: util.MustParseUUID(installation), WorkspaceID: util.MustParseUUID(workspaceID),
+ ConversationID: conversation, ConversationTitle: "Platform team renamed",
+ })
+ if err != nil || resolved.AgentID != util.MustParseUUID(routedAgent) || !resolved.AgentActive {
+ t.Fatalf("re-resolve group route = %+v, err=%v", resolved, err)
+ }
+
+ // Product decision: every route change starts a fresh session, including
+ // A -> B -> A. Returning to A must remove B's active binding rather than
+ // resuming A's earlier binding/transcript.
+ exec(`INSERT INTO channel_chat_session_binding (chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, config) VALUES ($1, $2, 'dingtalk', $3, 'group', jsonb_build_object('agent_id', $4::text))`, chatSessionB, installation, conversation, routedAgent)
+ returnedToDefault, err := queries.ReassignDingTalkGroupRoute(ctx, db.ReassignDingTalkGroupRouteParams{
+ ID: routes[0].ID, WorkspaceID: util.MustParseUUID(workspaceID), AgentID: util.MustParseUUID(defaultAgent),
+ })
+ if err != nil || returnedToDefault.AgentID != util.MustParseUUID(defaultAgent) {
+ t.Fatalf("return route B -> A = %+v, err=%v", returnedToDefault, err)
+ }
+ if _, err := queries.GetChannelChatSessionBinding(ctx, db.GetChannelChatSessionBindingParams{
+ InstallationID: util.MustParseUUID(installation), ChannelChatID: conversation,
+ }); !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("B binding survived route return to A: %v", err)
+ }
+ routes, err = queries.ListDingTalkGroupRoutesByWorkspace(ctx, util.MustParseUUID(workspaceID))
+ if err != nil || len(routes) != 1 || routes[0].ID != returnedToDefault.ID {
+ t.Fatalf("A -> B -> A changed stable route identity: routes=%+v err=%v", routes, err)
+ }
+
+ // PATCH-wins cutover: an append carrying the pre-PATCH revision cannot
+ // acquire the durable fence, so the Router can refresh and retry that same
+ // already-ACKed message on the new route without writing to A.
+ staleRevision := returnedToDefault.Revision
+ assignmentWon, err := queries.ReassignDingTalkGroupRoute(ctx, db.ReassignDingTalkGroupRouteParams{
+ ID: routes[0].ID, WorkspaceID: util.MustParseUUID(workspaceID), AgentID: util.MustParseUUID(routedAgent),
+ })
+ if err != nil || assignmentWon.Revision <= staleRevision {
+ t.Fatalf("assignment-wins fence update = %+v, err=%v", assignmentWon, err)
+ }
+ staleAppendTx, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin stale append fence: %v", err)
+ }
+ _, staleFenceErr := queries.WithTx(staleAppendTx).LockDingTalkGroupRouteForAppend(ctx, db.LockDingTalkGroupRouteForAppendParams{
+ InstallationID: util.MustParseUUID(installation), ConversationID: conversation,
+ AgentID: util.MustParseUUID(defaultAgent), RouteRevision: staleRevision,
+ })
+ _ = staleAppendTx.Rollback(ctx)
+ if !errors.Is(staleFenceErr, pgx.ErrNoRows) {
+ t.Fatalf("stale append fence error = %v, want no rows", staleFenceErr)
+ }
+ returnedForAppendFence, err := queries.ReassignDingTalkGroupRoute(ctx, db.ReassignDingTalkGroupRouteParams{
+ ID: routes[0].ID, WorkspaceID: util.MustParseUUID(workspaceID), AgentID: util.MustParseUUID(defaultAgent),
+ })
+ if err != nil {
+ t.Fatalf("restore A before append-wins fence: %v", err)
+ }
+
+ // Append-wins cutover: exercise the real message transaction. It locks the
+ // chat session first, then this route revision, and keeps both locks through
+ // the durable message commit. PATCH must be visibly blocked in PostgreSQL.
+ appendService := engine.NewChatSession(queries, pool, TypeDingTalk, engine.SessionTitles{Group: "DingTalk group"})
+ appendClaim, err := queries.ClaimChannelInboundDedup(ctx, db.ClaimChannelInboundDedupParams{
+ InstallationID: util.MustParseUUID(installation), MessageID: "msg-append-before-cutover",
+ })
+ if err != nil {
+ t.Fatalf("claim append-wins message: %v", err)
+ }
+ appendFenceAcquired := make(chan struct{})
+ allowAppendCommit := make(chan struct{})
+ appendDone := make(chan error, 1)
+ go func() {
+ _, appendErr := appendService.AppendUserMessage(context.Background(), engine.AppendInput{
+ SessionID: util.MustParseUUID(chatSessionID), InstallationID: util.MustParseUUID(installation),
+ Body: "append before route cutover", MessageID: "msg-append-before-cutover", ClaimToken: appendClaim.ClaimToken,
+ BeforeWrite: func(lockCtx context.Context, tx pgx.Tx) error {
+ if _, lockErr := queries.WithTx(tx).LockDingTalkGroupRouteForAppend(lockCtx, db.LockDingTalkGroupRouteForAppendParams{
+ InstallationID: util.MustParseUUID(installation), ConversationID: conversation,
+ AgentID: util.MustParseUUID(defaultAgent), RouteRevision: returnedForAppendFence.Revision,
+ }); lockErr != nil {
+ return lockErr
+ }
+ close(appendFenceAcquired)
+ select {
+ case <-allowAppendCommit:
+ return nil
+ case <-lockCtx.Done():
+ return lockCtx.Err()
+ }
+ },
+ })
+ appendDone <- appendErr
+ }()
+ select {
+ case <-appendFenceAcquired:
+ case appendErr := <-appendDone:
+ t.Fatalf("append failed before acquiring route fence: %v", appendErr)
+ case <-time.After(5 * time.Second):
+ t.Fatal("append did not acquire route fence")
+ }
+ reassignConn, err := pool.Acquire(ctx)
+ if err != nil {
+ close(allowAppendCommit)
+ t.Fatalf("acquire controlled PATCH connection: %v", err)
+ }
+ defer reassignConn.Release()
+ var reassignPID int32
+ if err := reassignConn.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&reassignPID); err != nil {
+ close(allowAppendCommit)
+ t.Fatalf("read controlled PATCH backend pid: %v", err)
+ }
+ appendWinsReassign := make(chan error, 1)
+ go func() {
+ _, reassignErr := db.New(reassignConn).ReassignDingTalkGroupRoute(context.Background(), db.ReassignDingTalkGroupRouteParams{
+ ID: routes[0].ID, WorkspaceID: util.MustParseUUID(workspaceID), AgentID: util.MustParseUUID(routedAgent),
+ })
+ appendWinsReassign <- reassignErr
+ }()
+ waitForDingTalkBackendBlocked(t, observerConn, reassignPID)
+ close(allowAppendCommit)
+ select {
+ case appendErr := <-appendDone:
+ if appendErr != nil {
+ t.Fatalf("commit append-wins message: %v", appendErr)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("append did not commit after test released its fence")
+ }
+ select {
+ case reassignErr := <-appendWinsReassign:
+ if reassignErr != nil {
+ t.Fatalf("PATCH after append fence: %v", reassignErr)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("PATCH did not resume after append transaction committed")
+ }
+ var appendedMessages int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM chat_message WHERE chat_session_id = $1 AND content = 'append before route cutover'`, chatSessionID).Scan(&appendedMessages); err != nil || appendedMessages != 1 {
+ t.Fatalf("append-wins durable messages = %d, err=%v, want 1", appendedMessages, err)
+ }
+ var appendDedupProcessed bool
+ if err := pool.QueryRow(ctx, `SELECT processed_at IS NOT NULL FROM channel_inbound_message_dedup WHERE installation_id = $1 AND message_id = 'msg-append-before-cutover'`, installation).Scan(&appendDedupProcessed); err != nil || !appendDedupProcessed {
+ t.Fatalf("append-wins dedup processed = %t, err=%v", appendDedupProcessed, err)
+ }
+ routeForWorkspaceFence, err := queries.ReassignDingTalkGroupRoute(ctx, db.ReassignDingTalkGroupRouteParams{
+ ID: routes[0].ID, WorkspaceID: util.MustParseUUID(workspaceID), AgentID: util.MustParseUUID(defaultAgent),
+ })
+ if err != nil {
+ t.Fatalf("restore A after append-wins fence: %v", err)
+ }
+
+ // Workspace teardown takes workspace -> chat_session -> route. The real
+ // append path must take chat_session before its route fence, so teardown can
+ // wait at the session without already holding the route append needs.
+ workspaceClaim, err := queries.ClaimChannelInboundDedup(ctx, db.ClaimChannelInboundDedupParams{
+ InstallationID: util.MustParseUUID(installation), MessageID: "msg-append-during-workspace-delete",
+ })
+ if err != nil {
+ t.Fatalf("claim workspace-delete append: %v", err)
+ }
+ workspaceFenceAcquired := make(chan struct{})
+ allowWorkspaceAppend := make(chan struct{})
+ workspaceAppendDone := make(chan error, 1)
+ go func() {
+ _, appendErr := appendService.AppendUserMessage(context.Background(), engine.AppendInput{
+ SessionID: util.MustParseUUID(chatSessionID), InstallationID: util.MustParseUUID(installation),
+ Body: "append during workspace delete", MessageID: "msg-append-during-workspace-delete", ClaimToken: workspaceClaim.ClaimToken,
+ BeforeWrite: func(lockCtx context.Context, tx pgx.Tx) error {
+ if _, lockErr := queries.WithTx(tx).LockDingTalkGroupRouteForAppend(lockCtx, db.LockDingTalkGroupRouteForAppendParams{
+ InstallationID: util.MustParseUUID(installation), ConversationID: conversation,
+ AgentID: util.MustParseUUID(defaultAgent), RouteRevision: routeForWorkspaceFence.Revision,
+ }); lockErr != nil {
+ return lockErr
+ }
+ close(workspaceFenceAcquired)
+ select {
+ case <-allowWorkspaceAppend:
+ return nil
+ case <-lockCtx.Done():
+ return lockCtx.Err()
+ }
+ },
+ })
+ workspaceAppendDone <- appendErr
+ }()
+ select {
+ case <-workspaceFenceAcquired:
+ case appendErr := <-workspaceAppendDone:
+ t.Fatalf("workspace-delete append failed before fence: %v", appendErr)
+ case <-time.After(5 * time.Second):
+ t.Fatal("workspace-delete append did not acquire its route fence")
+ }
+ deleteConn, err := pool.Acquire(ctx)
+ if err != nil {
+ close(allowWorkspaceAppend)
+ t.Fatalf("acquire controlled workspace-delete connection: %v", err)
+ }
+ defer deleteConn.Release()
+ var deletePID int32
+ if err := deleteConn.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&deletePID); err != nil {
+ close(allowWorkspaceAppend)
+ t.Fatalf("read workspace-delete backend pid: %v", err)
+ }
+ workspaceDeleteDone := make(chan error, 1)
+ go func() {
+ deleteErr := func() error {
+ deleteTx, beginErr := deleteConn.Begin(context.Background())
+ if beginErr != nil {
+ return beginErr
+ }
+ defer deleteTx.Rollback(context.Background())
+ deleteQueries := db.New(deleteTx)
+ if _, lockErr := deleteQueries.LockWorkspaceForDelete(context.Background(), util.MustParseUUID(workspaceID)); lockErr != nil {
+ return lockErr
+ }
+ if _, lockErr := deleteQueries.LockChatSessionsByWorkspace(context.Background(), util.MustParseUUID(workspaceID)); lockErr != nil {
+ return lockErr
+ }
+ _, deleteRouteErr := deleteTx.Exec(context.Background(), `DELETE FROM dingtalk_group_route WHERE workspace_id = $1`, workspaceID)
+ return deleteRouteErr
+ }()
+ workspaceDeleteDone <- deleteErr
+ }()
+ waitForDingTalkBackendBlocked(t, observerConn, deletePID)
+ close(allowWorkspaceAppend)
+ select {
+ case appendErr := <-workspaceAppendDone:
+ if appendErr != nil {
+ t.Fatalf("append during workspace deletion: %v", appendErr)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("append remained blocked during workspace deletion")
+ }
+ select {
+ case deleteErr := <-workspaceDeleteDone:
+ if deleteErr != nil {
+ t.Fatalf("workspace deletion lock protocol after append: %v", deleteErr)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("workspace deletion did not resume after append committed")
+ }
+ deleteConn.Release()
+ var workspaceAppendProcessed bool
+ if err := pool.QueryRow(ctx, `SELECT processed_at IS NOT NULL FROM channel_inbound_message_dedup WHERE installation_id = $1 AND message_id = 'msg-append-during-workspace-delete'`, installation).Scan(&workspaceAppendProcessed); err != nil || !workspaceAppendProcessed {
+ t.Fatalf("workspace-delete append dedup processed = %t, err=%v", workspaceAppendProcessed, err)
+ }
+
+ // Archive/restore semantics preserve the selected route. While archived,
+ // runtime validation rejects work before session creation; restoring the
+ // agent makes the same route active again without silent reassignment.
+ exec(`UPDATE agent SET archived_at = now() WHERE id = $1`, defaultAgent)
+ archivedRoute, err := queries.DiscoverDingTalkGroupRoute(ctx, db.DiscoverDingTalkGroupRouteParams{
+ InstallationID: util.MustParseUUID(installation), WorkspaceID: util.MustParseUUID(workspaceID),
+ ConversationID: conversation, ConversationTitle: "Platform team archived",
+ })
+ if err != nil || archivedRoute.AgentID != util.MustParseUUID(defaultAgent) || archivedRoute.AgentActive {
+ t.Fatalf("archived route lifecycle = %+v, err=%v", archivedRoute, err)
+ }
+ matches, err := queries.DingTalkGroupRouteMatchesAgent(ctx, db.DingTalkGroupRouteMatchesAgentParams{
+ InstallationID: util.MustParseUUID(installation), ConversationID: conversation,
+ AgentID: util.MustParseUUID(defaultAgent), RouteRevision: archivedRoute.Revision,
+ })
+ if err != nil || matches {
+ t.Fatalf("archived route matched active session guard: matches=%t err=%v", matches, err)
+ }
+ exec(`UPDATE agent SET archived_at = NULL, archived_by = NULL WHERE id = $1`, defaultAgent)
+ restoredRoute, err := queries.DiscoverDingTalkGroupRoute(ctx, db.DiscoverDingTalkGroupRouteParams{
+ InstallationID: util.MustParseUUID(installation), WorkspaceID: util.MustParseUUID(workspaceID),
+ ConversationID: conversation, ConversationTitle: "Platform team restored",
+ })
+ if err != nil || restoredRoute.AgentID != util.MustParseUUID(defaultAgent) || !restoredRoute.AgentActive {
+ t.Fatalf("restored route lifecycle = %+v, err=%v", restoredRoute, err)
+ }
+
+ // Controlled archive-wins interleaving: Reassign takes a shared lock on the
+ // target agent and must re-check archived_at after a concurrent archiver's
+ // row lock commits. It cannot install a target from a stale active snapshot.
+ archiveTx, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin controlled archive: %v", err)
+ }
+ if _, err := archiveTx.Exec(ctx, `SELECT id FROM agent WHERE id = $1 FOR UPDATE`, routedAgent); err != nil {
+ _ = archiveTx.Rollback(ctx)
+ t.Fatalf("lock route target for archive: %v", err)
+ }
+ reassignDone := make(chan error, 1)
+ go func() {
+ _, reassignErr := db.New(reassignConn).ReassignDingTalkGroupRoute(context.Background(), db.ReassignDingTalkGroupRouteParams{
+ ID: routes[0].ID, WorkspaceID: util.MustParseUUID(workspaceID), AgentID: util.MustParseUUID(routedAgent),
+ })
+ reassignDone <- reassignErr
+ }()
+ waitForDingTalkBackendBlocked(t, observerConn, reassignPID)
+ if _, err := archiveTx.Exec(ctx, `UPDATE agent SET archived_at = now() WHERE id = $1`, routedAgent); err != nil {
+ _ = archiveTx.Rollback(ctx)
+ t.Fatalf("archive controlled route target: %v", err)
+ }
+ if err := archiveTx.Commit(ctx); err != nil {
+ t.Fatalf("commit controlled archive: %v", err)
+ }
+ select {
+ case reassignErr := <-reassignDone:
+ if !errors.Is(reassignErr, pgx.ErrNoRows) {
+ t.Fatalf("archive-wins reassignment error = %v, want no rows", reassignErr)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("reassignment did not resume after archive commit")
+ }
+ reassignConn.Release()
+
+ // Assignment-wins ordering is also defined: a later archive preserves the
+ // selected B route, inbound validation reports it unavailable, and restore
+ // reactivates that same route.
+ exec(`UPDATE agent SET archived_at = NULL, archived_by = NULL WHERE id = $1`, routedAgent)
+ if _, err := queries.ReassignDingTalkGroupRoute(ctx, db.ReassignDingTalkGroupRouteParams{
+ ID: routes[0].ID, WorkspaceID: util.MustParseUUID(workspaceID), AgentID: util.MustParseUUID(routedAgent),
+ }); err != nil {
+ t.Fatalf("assignment-wins route update: %v", err)
+ }
+ exec(`UPDATE agent SET archived_at = now() WHERE id = $1`, routedAgent)
+ assignmentThenArchive, err := queries.DiscoverDingTalkGroupRoute(ctx, db.DiscoverDingTalkGroupRouteParams{
+ InstallationID: util.MustParseUUID(installation), WorkspaceID: util.MustParseUUID(workspaceID),
+ ConversationID: conversation, ConversationTitle: "Platform team B archived",
+ })
+ if err != nil || assignmentThenArchive.AgentID != util.MustParseUUID(routedAgent) || assignmentThenArchive.AgentActive {
+ t.Fatalf("assignment-then-archive lifecycle = %+v, err=%v", assignmentThenArchive, err)
+ }
+ exec(`UPDATE agent SET archived_at = NULL, archived_by = NULL WHERE id = $1`, routedAgent)
+ restoredAssignedRoute, err := queries.DiscoverDingTalkGroupRoute(ctx, db.DiscoverDingTalkGroupRouteParams{
+ InstallationID: util.MustParseUUID(installation), WorkspaceID: util.MustParseUUID(workspaceID),
+ ConversationID: conversation, ConversationTitle: "Platform team B restored",
+ })
+ if err != nil || restoredAssignedRoute.AgentID != util.MustParseUUID(routedAgent) || !restoredAssignedRoute.AgentActive {
+ t.Fatalf("restored assigned route = %+v, err=%v", restoredAssignedRoute, err)
+ }
+}
+
+func waitForDingTalkBackendBlocked(t *testing.T, observer *pgx.Conn, pid int32) {
+ t.Helper()
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) {
+ var blocked bool
+ if err := observer.QueryRow(context.Background(), `SELECT cardinality(pg_blocking_pids($1)) > 0`, pid).Scan(&blocked); err != nil {
+ t.Fatalf("inspect PostgreSQL lock wait for backend %d: %v", pid, err)
+ }
+ if blocked {
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Fatalf("backend %d never entered a PostgreSQL lock wait", pid)
+}
diff --git a/server/internal/integrations/dingtalk/group_route_pipeline_db_test.go b/server/internal/integrations/dingtalk/group_route_pipeline_db_test.go
new file mode 100644
index 0000000000..ad1ff0f417
--- /dev/null
+++ b/server/internal/integrations/dingtalk/group_route_pipeline_db_test.go
@@ -0,0 +1,108 @@
+package dingtalk
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestDingTalkRejectedGroupCallbacksDoNotDiscoverRoutesDB(t *testing.T) {
+ pool := dingtalkInstallTestDB(t)
+ ctx := context.Background()
+ var migrated bool
+ if err := pool.QueryRow(ctx, `SELECT to_regclass('public.dingtalk_group_route') IS NOT NULL`).Scan(&migrated); err != nil || !migrated {
+ t.Skip("dingtalk group route table not present (database not migrated)")
+ }
+
+ const (
+ workspaceID = "d2760000-0000-4000-8000-000000000001"
+ runtimeID = "d2760000-0000-4000-8000-000000000002"
+ agentID = "d2760000-0000-4000-8000-000000000003"
+ installerID = "d2760000-0000-4000-8000-000000000004"
+ installation = "d2760000-0000-4000-8000-000000000005"
+ boundUserID = "d2760000-0000-4000-8000-000000000006"
+ appKey = "dingtalk_rejected_group_pipeline_app"
+ staffID = "staff-rejected-group-pipeline"
+ )
+
+ clean := func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_inbound_audit WHERE installation_id = $1`, installation)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_inbound_message_dedup WHERE installation_id = $1`, installation)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_user_binding WHERE installation_id = $1`, installation)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM dingtalk_group_route WHERE installation_id = $1`, installation)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installation)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, workspaceID)
+ }
+ clean()
+ t.Cleanup(clean)
+
+ exec := func(query string, args ...any) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, query, args...); err != nil {
+ t.Fatalf("seed rejected callback fixture: %v", err)
+ }
+ }
+ exec(`INSERT INTO workspace (id, name, slug, description) VALUES ($1, 'DingTalk rejected routes', 'dingtalk-rejected-routes-db', '')`, workspaceID)
+ exec(`INSERT INTO agent_runtime (id, workspace_id, name, runtime_mode, provider) VALUES ($1, $2, 'DingTalk rejected route runtime', 'local', 'multica_daemon')`, runtimeID, workspaceID)
+ exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode, runtime_id) VALUES ($1, $2, 'DingTalk rejected route agent', 'local', $3)`, agentID, workspaceID, runtimeID)
+ exec(`INSERT INTO channel_installation (id, workspace_id, agent_id, channel_type, config, installer_user_id) VALUES ($1, $2, $3, 'dingtalk', jsonb_build_object('app_id', $4::text), $5)`, installation, workspaceID, agentID, appKey, installerID)
+
+ queries := db.New(pool)
+ router := engine.NewRouter(nil, nil, nil, engine.RouterConfig{
+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ })
+ router.Register(TypeDingTalk, NewDingTalkResolverSet(queries, pool, nil, nil, nil))
+ raw, err := json.Marshal(dingtalkRawEvent{AppID: appKey, ConversationTitle: "Rejected group"})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ message := func(messageID, conversationID string, addressed bool) channel.InboundMessage {
+ return channel.InboundMessage{
+ EventID: "event-" + messageID,
+ MessageID: messageID,
+ Type: channel.MsgTypeText,
+ Text: "hello",
+ AddressedToBot: addressed,
+ Raw: raw,
+ Source: channel.Source{
+ ChannelType: TypeDingTalk,
+ ChatID: conversationID,
+ ChatType: channel.ChatTypeGroup,
+ SenderID: staffID,
+ },
+ }
+ }
+ assertNoRoutes := func(label string) {
+ t.Helper()
+ var count int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM dingtalk_group_route WHERE installation_id = $1`, installation).Scan(&count); err != nil {
+ t.Fatalf("%s: count routes: %v", label, err)
+ }
+ if count != 0 {
+ t.Fatalf("%s persisted %d rejected group route(s)", label, count)
+ }
+ }
+
+ if err := router.Handle(ctx, message("unmentioned", "cid-unmentioned", false)); err != nil {
+ t.Fatalf("unmentioned callback: %v", err)
+ }
+ assertNoRoutes("unmentioned callback")
+
+ if err := router.Handle(ctx, message("unbound", "cid-unbound", true)); err != nil {
+ t.Fatalf("unbound callback: %v", err)
+ }
+ assertNoRoutes("unbound callback")
+
+ exec(`INSERT INTO channel_user_binding (workspace_id, multica_user_id, installation_id, channel_type, channel_user_id) VALUES ($1, $2, $3, 'dingtalk', $4)`, workspaceID, boundUserID, installation, staffID)
+ if err := router.Handle(ctx, message("nonmember", "cid-nonmember", true)); err != nil {
+ t.Fatalf("non-member callback: %v", err)
+ }
+ assertNoRoutes("non-member callback")
+}
diff --git a/server/internal/integrations/dingtalk/inbound.go b/server/internal/integrations/dingtalk/inbound.go
index fd66dc2973..ec8db6fd81 100644
--- a/server/internal/integrations/dingtalk/inbound.go
+++ b/server/internal/integrations/dingtalk/inbound.go
@@ -20,13 +20,14 @@ import (
// reads; DingTalk sends more, which we ignore. Replaces the vendor SDK's
// chatbot.BotCallbackDataModel.
type botCallbackData struct {
- ConversationId string `json:"conversationId"`
- ConversationType string `json:"conversationType"`
- SenderStaffId string `json:"senderStaffId"`
- MsgId string `json:"msgId"`
- Msgtype string `json:"msgtype"`
- IsInAtList bool `json:"isInAtList"`
- Text botCallbackText `json:"text"`
+ ConversationId string `json:"conversationId"`
+ ConversationTitle string `json:"conversationTitle"`
+ ConversationType string `json:"conversationType"`
+ SenderStaffId string `json:"senderStaffId"`
+ MsgId string `json:"msgId"`
+ Msgtype string `json:"msgtype"`
+ IsInAtList bool `json:"isInAtList"`
+ Text botCallbackText `json:"text"`
// Content is the msgtype-discriminated payload of non-text messages
// (picture / richText). Decoded lazily per msgtype; absent on over-quota
// callbacks (errorCode 20001 strips text/content entirely).
@@ -72,8 +73,9 @@ func refAlt(downloadCode, pictureDownloadCode string) (ref, alt string) {
// envelope does not. AppID is stamped by the receiving connection (it is the
// installation's routing key) and read back only inside the resolvers.
type dingtalkRawEvent struct {
- AppID string `json:"app_id"`
- Media []dingtalkMediaResource `json:"media,omitempty"`
+ AppID string `json:"app_id"`
+ ConversationTitle string `json:"conversation_title,omitempty"`
+ Media []dingtalkMediaResource `json:"media,omitempty"`
}
type dingtalkMediaResource struct {
@@ -114,7 +116,7 @@ func inboundFromCallback(data *botCallbackData, appID string) (channel.InboundMe
}
chatType := dingtalkChatType(data.ConversationType)
- rawEvent := dingtalkRawEvent{AppID: appID}
+ rawEvent := dingtalkRawEvent{AppID: appID, ConversationTitle: strings.TrimSpace(data.ConversationTitle)}
msg := channel.InboundMessage{
EventID: data.MsgId,
MessageID: data.MsgId,
diff --git a/server/internal/integrations/dingtalk/inbound_test.go b/server/internal/integrations/dingtalk/inbound_test.go
index 4824cf084f..88d74d7947 100644
--- a/server/internal/integrations/dingtalk/inbound_test.go
+++ b/server/internal/integrations/dingtalk/inbound_test.go
@@ -38,8 +38,12 @@ func TestInboundFromCallback_P2PAddressedAndTrimmed(t *testing.T) {
}
func TestInboundFromCallback_GroupAddressing(t *testing.T) {
- if msg, ok := inboundFromCallback(textCallback(convTypeGroup, true), "a"); !ok || !msg.AddressedToBot {
+ callback := textCallback(convTypeGroup, true)
+ callback.ConversationTitle = "Platform team"
+ if msg, ok := inboundFromCallback(callback, "a"); !ok || !msg.AddressedToBot {
t.Fatalf("group mention must be addressed: ok=%v msg=%+v", ok, msg)
+ } else if raw, err := decodeDingTalkRaw(msg); err != nil || raw.ConversationTitle != "Platform team" {
+ t.Fatalf("group title = %q, err=%v", raw.ConversationTitle, err)
}
msg, ok := inboundFromCallback(textCallback(convTypeGroup, false), "a")
if !ok || msg.AddressedToBot {
diff --git a/server/internal/integrations/dingtalk/install.go b/server/internal/integrations/dingtalk/install.go
index 844f059ddf..4619b3260d 100644
--- a/server/internal/integrations/dingtalk/install.go
+++ b/server/internal/integrations/dingtalk/install.go
@@ -31,8 +31,8 @@ var (
// ErrRobotOwnedByAnotherWorkspace is returned when the pasted DingTalk robot
// is already connected to a live owner in a DIFFERENT Multica workspace — it
// would collide with the (channel_type, app_id) routing index. A DingTalk
- // robot is one bot identity and maps to one agent; reusing it here requires
- // disconnecting it in the other workspace first.
+ // robot is one bot identity and maps to one installation/default agent;
+ // group-specific routes may target other agents inside that workspace.
ErrRobotOwnedByAnotherWorkspace = errors.New("dingtalk: this DingTalk robot is already connected to a different Multica workspace")
// ErrRobotOwnedBySameWorkspace is returned when the robot is already connected
// to a DIFFERENT (live, non-archived) agent in the SAME workspace, pointing
@@ -124,7 +124,7 @@ func newInstallService(q installQueries, tx engine.TxStarter, box *secretbox.Box
// installPersist carries the resolved fields persistInstall writes. configJSON
// holds the AppKey (config->>'app_id') used for inbound routing; the ROW itself
-// is keyed by (workspace, agent) — one bot per agent.
+// is keyed by (workspace, agent) — one installation/default agent per bot.
type installPersist struct {
wsID pgtype.UUID
agentID pgtype.UUID
@@ -139,7 +139,8 @@ type installPersist struct {
// pgUniqueViolation is the Postgres SQLSTATE for a unique-constraint violation.
const pgUniqueViolation = "23505"
-// persistInstall stores one DingTalk bot per (workspace, agent). Reconnecting
+// persistInstall stores one DingTalk installation per (workspace, default
+// agent). Reconnecting
// the SAME AppKey updates the row in place and preserves its installation-scoped
// state. Connecting a DIFFERENT AppKey retires that state and inserts a fresh
// installation id: DingTalk senderStaffId is only organization-scoped, so user
diff --git a/server/internal/integrations/dingtalk/resolvers.go b/server/internal/integrations/dingtalk/resolvers.go
index 222f5cb1f4..d55c6c7209 100644
--- a/server/internal/integrations/dingtalk/resolvers.go
+++ b/server/internal/integrations/dingtalk/resolvers.go
@@ -11,6 +11,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/channel"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -32,11 +33,16 @@ const originDingTalkChat = "dingtalk_chat"
// "working on it" message on ingest); pass nil to disable it. Media is optional:
// when configured it uses the shared MediaResolver and intent-ledger pipeline.
func NewDingTalkResolverSet(q *db.Queries, tx engine.TxStarter, replier engine.OutboundReplier, ack *ackNotifier, media engine.MediaResolver) engine.ResolverSet {
+ lockRouteForAppend := func(ctx context.Context, appendTx pgx.Tx, arg db.LockDingTalkGroupRouteForAppendParams) error {
+ _, err := q.WithTx(appendTx).LockDingTalkGroupRouteForAppend(ctx, arg)
+ return err
+ }
set := engine.ResolverSet{
Installation: &installationResolver{q: q},
Identity: &identityResolver{q: q},
+ Validated: &validatedInboundResolver{q: q},
Dedup: &deduper{q: q},
- Session: &sessionBinder{session: engine.NewChatSession(q, tx, TypeDingTalk, engine.SessionTitles{
+ Session: &sessionBinder{q: q, lockRouteForAppend: lockRouteForAppend, session: engine.NewChatSession(q, tx, TypeDingTalk, engine.SessionTitles{
Group: "DingTalk group",
Direct: "DingTalk direct message",
Fallback: "DingTalk chat",
@@ -57,11 +63,12 @@ func NewDingTalkResolverSet(q *db.Queries, tx engine.TxStarter, replier engine.O
}
var (
- _ engine.InstallationResolver = (*installationResolver)(nil)
- _ engine.IdentityResolver = (*identityResolver)(nil)
- _ engine.Deduper = (*deduper)(nil)
- _ engine.SessionBinder = (*sessionBinder)(nil)
- _ engine.Auditor = (*auditor)(nil)
+ _ engine.InstallationResolver = (*installationResolver)(nil)
+ _ engine.IdentityResolver = (*identityResolver)(nil)
+ _ engine.ValidatedInboundResolver = (*validatedInboundResolver)(nil)
+ _ engine.Deduper = (*deduper)(nil)
+ _ engine.SessionBinder = (*sessionBinder)(nil)
+ _ engine.Auditor = (*auditor)(nil)
)
// dingtalkBindingConfig is the opaque outbound routing persisted on the chat
@@ -72,6 +79,7 @@ type dingtalkBindingConfig struct {
ConversationType string `json:"conversation_type"`
ConversationID string `json:"conversation_id"`
StaffID string `json:"staff_id,omitempty"`
+ AgentID string `json:"agent_id,omitempty"`
}
// dingtalkSessionRouting derives the session-isolation key and the outbound
@@ -79,11 +87,12 @@ type dingtalkBindingConfig struct {
// conversation (1:1 or group) is one continuous session keyed by its
// conversation id; the config carries everything the outbound path needs to send
// back.
-func dingtalkSessionRouting(msg channel.InboundMessage) (bindingKey string, config []byte) {
+func dingtalkSessionRouting(msg channel.InboundMessage, agentID pgtype.UUID) (bindingKey string, config []byte) {
chatID := msg.Source.ChatID
cfg := dingtalkBindingConfig{
ConversationType: convTypeGroup,
ConversationID: chatID,
+ AgentID: util.UUIDToString(agentID),
}
if msg.Source.ChatType == channel.ChatTypeP2P {
cfg.ConversationType = convTypeP2P
@@ -132,7 +141,11 @@ func nullText(s string) pgtype.Text {
// ---- installation routing ----
-type installationResolver struct{ q *db.Queries }
+type installationQueries interface {
+ GetChannelInstallationByAppID(ctx context.Context, arg db.GetChannelInstallationByAppIDParams) (db.ChannelInstallation, error)
+}
+
+type installationResolver struct{ q installationQueries }
func (r *installationResolver) ResolveInstallation(ctx context.Context, msg channel.InboundMessage) (engine.ResolvedInstallation, error) {
raw, err := decodeDingTalkRaw(msg)
@@ -153,14 +166,51 @@ func (r *installationResolver) ResolveInstallation(ctx context.Context, msg chan
}
return engine.ResolvedInstallation{}, err
}
+ return resolvedInstallation(inst, inst.AgentID), nil
+}
+
+// ---- validated inbound discovery / final routing ----
+
+type validatedInboundQueries interface {
+ DiscoverDingTalkGroupRoute(ctx context.Context, arg db.DiscoverDingTalkGroupRouteParams) (db.DiscoverDingTalkGroupRouteRow, error)
+}
+
+type validatedInboundResolver struct{ q validatedInboundQueries }
+
+func (r *validatedInboundResolver) ResolveValidatedInbound(ctx context.Context, inst engine.ResolvedInstallation, _ engine.ResolvedIdentity, msg channel.InboundMessage) (engine.ResolvedInstallation, error) {
+ if msg.Source.ChatType != channel.ChatTypeGroup {
+ return inst, nil
+ }
+ raw, err := decodeDingTalkRaw(msg)
+ if err != nil {
+ return inst, err
+ }
+ row, err := r.q.DiscoverDingTalkGroupRoute(ctx, db.DiscoverDingTalkGroupRouteParams{
+ InstallationID: inst.ID,
+ WorkspaceID: inst.WorkspaceID,
+ ConversationID: msg.Source.ChatID,
+ ConversationTitle: raw.ConversationTitle,
+ })
+ if err != nil {
+ return inst, err
+ }
+ inst.AgentID = row.AgentID
+ inst.RouteRevision = row.Revision
+ if !row.AgentActive {
+ return inst, engine.ErrTargetAgentArchived
+ }
+ return inst, nil
+}
+
+func resolvedInstallation(inst db.ChannelInstallation, agentID pgtype.UUID) engine.ResolvedInstallation {
return engine.ResolvedInstallation{
ID: inst.ID,
WorkspaceID: inst.WorkspaceID,
- AgentID: inst.AgentID,
+ AgentID: agentID,
InstallerUserID: inst.InstallerUserID,
Active: inst.Status == "active",
Platform: inst,
- }, nil
+ }
}
// ---- identity ----
@@ -236,11 +286,20 @@ type chatSession interface {
BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error
}
-type sessionBinder struct{ session chatSession }
+type sessionQueries interface {
+ DingTalkGroupRouteMatchesAgent(ctx context.Context, arg db.DingTalkGroupRouteMatchesAgentParams) (bool, error)
+ DeleteDingTalkStaleGroupChatBinding(ctx context.Context, arg db.DeleteDingTalkStaleGroupChatBindingParams) (int64, error)
+}
+
+type sessionBinder struct {
+ q sessionQueries
+ lockRouteForAppend func(context.Context, pgx.Tx, db.LockDingTalkGroupRouteForAppendParams) error
+ session chatSession
+}
func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessionParams) (pgtype.UUID, error) {
- bindingKey, config := dingtalkSessionRouting(p.Message)
- return r.session.EnsureSession(ctx, engine.EnsureSessionInput{
+ bindingKey, config := dingtalkSessionRouting(p.Message, p.Installation.AgentID)
+ input := engine.EnsureSessionInput{
WorkspaceID: p.Installation.WorkspaceID,
AgentID: p.Installation.AgentID,
InstallationID: p.Installation.ID,
@@ -248,7 +307,54 @@ func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessio
BindingKey: bindingKey,
BindingConfig: config,
ChatType: p.Message.Source.ChatType,
- })
+ }
+ if p.Message.Source.ChatType != channel.ChatTypeGroup || r.q == nil {
+ return r.session.EnsureSession(ctx, input)
+ }
+
+ routeParams := db.DingTalkGroupRouteMatchesAgentParams{
+ InstallationID: p.Installation.ID,
+ ConversationID: bindingKey,
+ AgentID: p.Installation.AgentID,
+ RouteRevision: p.Installation.RouteRevision,
+ }
+ staleParams := db.DeleteDingTalkStaleGroupChatBindingParams{
+ InstallationID: routeParams.InstallationID,
+ ConversationID: routeParams.ConversationID,
+ AgentID: routeParams.AgentID,
+ }
+ for attempt := 0; attempt < 3; attempt++ {
+ matches, err := r.q.DingTalkGroupRouteMatchesAgent(ctx, routeParams)
+ if err != nil {
+ return pgtype.UUID{}, fmt.Errorf("verify dingtalk group route: %w", err)
+ }
+ if !matches {
+ return pgtype.UUID{}, engine.ErrRouteChanged
+ }
+ if _, err := r.q.DeleteDingTalkStaleGroupChatBinding(ctx, staleParams); err != nil {
+ return pgtype.UUID{}, fmt.Errorf("retire stale dingtalk group session: %w", err)
+ }
+
+ sessionID, err := r.session.EnsureSession(ctx, input)
+ if err != nil {
+ return pgtype.UUID{}, err
+ }
+ matches, err = r.q.DingTalkGroupRouteMatchesAgent(ctx, routeParams)
+ if err != nil {
+ return pgtype.UUID{}, fmt.Errorf("recheck dingtalk group route: %w", err)
+ }
+ if !matches {
+ return pgtype.UUID{}, engine.ErrRouteChanged
+ }
+ retired, err := r.q.DeleteDingTalkStaleGroupChatBinding(ctx, staleParams)
+ if err != nil {
+ return pgtype.UUID{}, fmt.Errorf("recheck dingtalk group session: %w", err)
+ }
+ if retired == 0 {
+ return sessionID, nil
+ }
+ }
+ return pgtype.UUID{}, engine.ErrRouteChanged
}
func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {
@@ -260,7 +366,7 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams
if commandText == "" {
commandText = p.Message.Text
}
- return r.session.AppendUserMessage(ctx, engine.AppendInput{
+ input := engine.AppendInput{
SessionID: p.SessionID,
Sender: p.Sender,
InstallationID: p.InstallationID,
@@ -271,7 +377,25 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams
ClaimToken: p.ClaimToken,
MediaPendingSeconds: p.MediaPendingSeconds,
ForceFresh: p.Message.ForceFresh,
- })
+ }
+ if p.Message.Source.ChatType == channel.ChatTypeGroup && r.lockRouteForAppend != nil {
+ params := db.LockDingTalkGroupRouteForAppendParams{
+ InstallationID: p.InstallationID,
+ ConversationID: p.Message.Source.ChatID,
+ AgentID: p.AgentID,
+ RouteRevision: p.RouteRevision,
+ }
+ input.BeforeWrite = func(ctx context.Context, tx pgx.Tx) error {
+ if err := r.lockRouteForAppend(ctx, tx, params); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ErrRouteChanged
+ }
+ return fmt.Errorf("lock dingtalk group route for append: %w", err)
+ }
+ return nil
+ }
+ }
+ return r.session.AppendUserMessage(ctx, input)
}
func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
diff --git a/server/internal/integrations/dingtalk/resolvers_test.go b/server/internal/integrations/dingtalk/resolvers_test.go
index e7ff20544a..7824cd4479 100644
--- a/server/internal/integrations/dingtalk/resolvers_test.go
+++ b/server/internal/integrations/dingtalk/resolvers_test.go
@@ -3,8 +3,11 @@ package dingtalk
import (
"context"
"encoding/json"
+ "errors"
+ "strings"
"testing"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/integrations/channel"
@@ -12,17 +15,97 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
+type fakeInstallationQueries struct {
+ params db.GetChannelInstallationByAppIDParams
+ row db.ChannelInstallation
+ err error
+ calls int
+}
+
+type fakeValidatedInboundQueries struct {
+ params db.DiscoverDingTalkGroupRouteParams
+ row db.DiscoverDingTalkGroupRouteRow
+ err error
+ calls int
+}
+
+type fakeSessionQueries struct {
+ params db.DeleteDingTalkStaleGroupChatBindingParams
+ matches []bool
+ matchErrs []error
+ matchCalls int
+ deleteCounts []int64
+ deleteErrs []error
+ deleteCalls int
+}
+
+func (f *fakeSessionQueries) DingTalkGroupRouteMatchesAgent(context.Context, db.DingTalkGroupRouteMatchesAgentParams) (bool, error) {
+ call := f.matchCalls
+ f.matchCalls++
+ var err error
+ if call < len(f.matchErrs) {
+ err = f.matchErrs[call]
+ }
+ match := true
+ if call < len(f.matches) {
+ match = f.matches[call]
+ }
+ return match, err
+}
+
+func (f *fakeSessionQueries) DeleteDingTalkStaleGroupChatBinding(_ context.Context, params db.DeleteDingTalkStaleGroupChatBindingParams) (int64, error) {
+ f.params = params
+ call := f.deleteCalls
+ f.deleteCalls++
+ var count int64
+ if call < len(f.deleteCounts) {
+ count = f.deleteCounts[call]
+ }
+ var err error
+ if call < len(f.deleteErrs) {
+ err = f.deleteErrs[call]
+ }
+ return count, err
+}
+
+func (f *fakeInstallationQueries) GetChannelInstallationByAppID(_ context.Context, params db.GetChannelInstallationByAppIDParams) (db.ChannelInstallation, error) {
+ f.params = params
+ f.calls++
+ return f.row, f.err
+}
+
+func (f *fakeValidatedInboundQueries) DiscoverDingTalkGroupRoute(_ context.Context, params db.DiscoverDingTalkGroupRouteParams) (db.DiscoverDingTalkGroupRouteRow, error) {
+ f.params = params
+ f.calls++
+ return f.row, f.err
+}
+
type captureChatSession struct {
- append engine.AppendInput
- media engine.BindMediaInput
+ ensure engine.EnsureSessionInput
+ ensureCalls int
+ ensureErr error
+ append engine.AppendInput
+ appendCalls int
+ appended int
+ runGuard bool
+ media engine.BindMediaInput
}
-func (c *captureChatSession) EnsureSession(context.Context, engine.EnsureSessionInput) (pgtype.UUID, error) {
- return pgtype.UUID{}, nil
+func (c *captureChatSession) EnsureSession(_ context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error) {
+ c.ensure = in
+ c.ensureCalls++
+ return pgtype.UUID{}, c.ensureErr
}
func (c *captureChatSession) MarkPendingFresh(context.Context, pgtype.UUID) error { return nil }
-func (c *captureChatSession) AppendUserMessage(_ context.Context, in engine.AppendInput) (engine.AppendResult, error) {
+func (c *captureChatSession) AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error) {
c.append = in
+ c.appendCalls++
+ if c.runGuard && in.BeforeWrite != nil {
+ if err := in.BeforeWrite(ctx, nil); err != nil {
+ return engine.AppendResult{}, err
+ }
+ }
+ c.appended++
return engine.AppendResult{}, nil
}
func (c *captureChatSession) BindMediaRefs(_ context.Context, in engine.BindMediaInput) error {
@@ -37,6 +120,172 @@ func TestNewDingTalkResolverSetUsesDatabaseBackedIssueOrigin(t *testing.T) {
}
}
+func TestInstallationResolverGroupLookupIsReadOnly(t *testing.T) {
+ var installationID, workspaceID, defaultAgentID, installerID pgtype.UUID
+ installationID.Bytes[0], workspaceID.Bytes[0], defaultAgentID.Bytes[0], installerID.Bytes[0] = 1, 2, 3, 5
+ installationID.Valid, workspaceID.Valid, defaultAgentID.Valid, installerID.Valid = true, true, true, true
+ fake := &fakeInstallationQueries{row: db.ChannelInstallation{
+ ID: installationID, WorkspaceID: workspaceID, AgentID: defaultAgentID,
+ InstallerUserID: installerID, Status: "active",
+ }}
+ raw, _ := json.Marshal(dingtalkRawEvent{AppID: "app-key", ConversationTitle: "Platform team"})
+ resolved, err := (&installationResolver{q: fake}).ResolveInstallation(context.Background(), channel.InboundMessage{
+ Source: channel.Source{ChatID: "cid-platform", ChatType: channel.ChatTypeGroup},
+ Raw: raw,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resolved.ID != installationID || resolved.WorkspaceID != workspaceID || resolved.AgentID != defaultAgentID || resolved.InstallerUserID != installerID || !resolved.Active {
+ t.Fatalf("resolved group installation = %+v", resolved)
+ }
+ if fake.params.ChannelType != string(TypeDingTalk) || fake.params.AppID != "app-key" {
+ t.Fatalf("installation lookup params = %+v", fake.params)
+ }
+ platform, ok := resolved.Platform.(db.ChannelInstallation)
+ if !ok || platform.AgentID != defaultAgentID {
+ t.Fatalf("platform installation must retain default agent: %#v", resolved.Platform)
+ }
+}
+
+func TestDingTalkResolversRejectMalformedCallbackRaw(t *testing.T) {
+ t.Run("installation", func(t *testing.T) {
+ fake := &fakeInstallationQueries{}
+ _, err := (&installationResolver{q: fake}).ResolveInstallation(context.Background(), channel.InboundMessage{Raw: []byte("{")})
+ if err == nil || fake.calls != 0 {
+ t.Fatalf("malformed installation callback error=%v query calls=%d, want decode error before query", err, fake.calls)
+ }
+ })
+
+ t.Run("validated group route", func(t *testing.T) {
+ fake := &fakeValidatedInboundQueries{}
+ _, err := (&validatedInboundResolver{q: fake}).ResolveValidatedInbound(
+ context.Background(), engine.ResolvedInstallation{}, engine.ResolvedIdentity{},
+ channel.InboundMessage{Source: channel.Source{ChatType: channel.ChatTypeGroup}, Raw: []byte("{")},
+ )
+ if err == nil || fake.calls != 0 {
+ t.Fatalf("malformed discovery callback error=%v query calls=%d, want decode error before query", err, fake.calls)
+ }
+ })
+}
+
+func TestValidatedInboundResolverReturnsDiscoveryQueryErrorWithoutChangingRoute(t *testing.T) {
+ queryErr := errors.New("discover route database unavailable")
+ fake := &fakeValidatedInboundQueries{err: queryErr}
+ inst := engine.ResolvedInstallation{AgentID: pgtype.UUID{Bytes: [16]byte{3}, Valid: true}, RouteRevision: 4}
+ raw, _ := json.Marshal(dingtalkRawEvent{ConversationTitle: "Platform team"})
+
+ resolved, err := (&validatedInboundResolver{q: fake}).ResolveValidatedInbound(
+ context.Background(), inst, engine.ResolvedIdentity{},
+ channel.InboundMessage{Source: channel.Source{ChatID: "cid-platform", ChatType: channel.ChatTypeGroup}, Raw: raw},
+ )
+ if !errors.Is(err, queryErr) {
+ t.Fatalf("discovery query error = %v, want %v", err, queryErr)
+ }
+ if resolved.AgentID != inst.AgentID || resolved.RouteRevision != inst.RouteRevision || fake.calls != 1 {
+ t.Fatalf("failed discovery changed route: resolved=%+v calls=%d", resolved, fake.calls)
+ }
+}
+
+func TestDingTalkP2PSkipsGroupDiscoveryAndUsesDefaultAgentSession(t *testing.T) {
+ var installationID, workspaceID, defaultAgentID, senderID pgtype.UUID
+ installationID.Bytes[0], workspaceID.Bytes[0], defaultAgentID.Bytes[0], senderID.Bytes[0] = 1, 2, 3, 4
+ installationID.Valid, workspaceID.Valid, defaultAgentID.Valid, senderID.Valid = true, true, true, true
+ inst := engine.ResolvedInstallation{ID: installationID, WorkspaceID: workspaceID, AgentID: defaultAgentID}
+ msg := channel.InboundMessage{Source: channel.Source{
+ ChatID: "cid-direct", ChatType: channel.ChatTypeP2P, SenderID: "staff-7",
+ }}
+ discovery := &fakeValidatedInboundQueries{err: errors.New("must not query group routes for p2p")}
+
+ resolved, err := (&validatedInboundResolver{q: discovery}).ResolveValidatedInbound(
+ context.Background(), inst, engine.ResolvedIdentity{}, msg,
+ )
+ if err != nil || resolved.AgentID != defaultAgentID || discovery.calls != 0 {
+ t.Fatalf("p2p validated resolution = %+v err=%v discovery calls=%d", resolved, err, discovery.calls)
+ }
+
+ queries := &fakeSessionQueries{matchErrs: []error{errors.New("must not query group route session fence for p2p")}}
+ capture := &captureChatSession{}
+ appendFenceCalls := 0
+ binder := &sessionBinder{
+ q: queries, session: capture,
+ lockRouteForAppend: func(context.Context, pgx.Tx, db.LockDingTalkGroupRouteForAppendParams) error {
+ appendFenceCalls++
+ return errors.New("must not lock group route for p2p")
+ },
+ }
+ if _, err := binder.EnsureSession(context.Background(), engine.EnsureSessionParams{
+ Installation: inst,
+ Sender: senderID,
+ Message: msg,
+ }); err != nil {
+ t.Fatalf("p2p EnsureSession: %v", err)
+ }
+ if queries.matchCalls != 0 || queries.deleteCalls != 0 || capture.ensureCalls != 1 {
+ t.Fatalf("p2p route calls = match %d delete %d ensure %d, want 0/0/1", queries.matchCalls, queries.deleteCalls, capture.ensureCalls)
+ }
+ if capture.ensure.AgentID != defaultAgentID || capture.ensure.BindingKey != "cid-direct" || capture.ensure.ChatType != channel.ChatTypeP2P {
+ t.Fatalf("p2p session input = %+v, want default agent and direct-message binding", capture.ensure)
+ }
+ if _, err := binder.AppendMessage(context.Background(), engine.AppendParams{
+ SessionID: pgtype.UUID{Bytes: [16]byte{5}, Valid: true},
+ InstallationID: installationID,
+ AgentID: defaultAgentID,
+ Message: msg,
+ }); err != nil {
+ t.Fatalf("p2p AppendMessage: %v", err)
+ }
+ hasBeforeWrite := capture.append.BeforeWrite != nil
+ if appendFenceCalls != 0 || capture.appended != 1 || hasBeforeWrite {
+ t.Fatalf("p2p append = fence calls %d durable appends %d has beforeWrite %t, want 0/1/false", appendFenceCalls, capture.appended, hasBeforeWrite)
+ }
+}
+
+func TestValidatedInboundResolverDiscoversGroupAndFinalizesAgent(t *testing.T) {
+ var installationID, workspaceID, defaultAgentID, routeAgentID pgtype.UUID
+ installationID.Bytes[0], workspaceID.Bytes[0], defaultAgentID.Bytes[0], routeAgentID.Bytes[0] = 1, 2, 3, 4
+ installationID.Valid, workspaceID.Valid, defaultAgentID.Valid, routeAgentID.Valid = true, true, true, true
+ fake := &fakeValidatedInboundQueries{row: db.DiscoverDingTalkGroupRouteRow{
+ AgentID: routeAgentID, Revision: 7, AgentActive: true,
+ }}
+ raw, _ := json.Marshal(dingtalkRawEvent{ConversationTitle: "Platform team"})
+ resolved, err := (&validatedInboundResolver{q: fake}).ResolveValidatedInbound(
+ context.Background(),
+ engine.ResolvedInstallation{ID: installationID, WorkspaceID: workspaceID, AgentID: defaultAgentID},
+ engine.ResolvedIdentity{},
+ channel.InboundMessage{
+ Source: channel.Source{ChatID: "cid-platform", ChatType: channel.ChatTypeGroup},
+ Raw: raw,
+ },
+ )
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resolved.AgentID != routeAgentID || resolved.RouteRevision != 7 {
+ t.Fatalf("resolved route = agent %v revision %d, want agent %v revision 7", resolved.AgentID, resolved.RouteRevision, routeAgentID)
+ }
+ if fake.params.InstallationID != installationID || fake.params.WorkspaceID != workspaceID || fake.params.ConversationID != "cid-platform" || fake.params.ConversationTitle != "Platform team" {
+ t.Fatalf("discovery params = %+v", fake.params)
+ }
+}
+
+func TestValidatedInboundResolverPreservesArchivedRoute(t *testing.T) {
+ var routeAgentID pgtype.UUID
+ routeAgentID.Bytes[0], routeAgentID.Valid = 4, true
+ fake := &fakeValidatedInboundQueries{row: db.DiscoverDingTalkGroupRouteRow{AgentID: routeAgentID}}
+ raw, _ := json.Marshal(dingtalkRawEvent{})
+ resolved, err := (&validatedInboundResolver{q: fake}).ResolveValidatedInbound(
+ context.Background(), engine.ResolvedInstallation{}, engine.ResolvedIdentity{},
+ channel.InboundMessage{Source: channel.Source{ChatType: channel.ChatTypeGroup}, Raw: raw},
+ )
+ if err != engine.ErrTargetAgentArchived {
+ t.Fatalf("archived route error = %v, want %v", err, engine.ErrTargetAgentArchived)
+ }
+ if resolved.AgentID != routeAgentID {
+ t.Fatalf("archived route agent = %v, want preserved %v", resolved.AgentID, routeAgentID)
+ }
+}
+
func TestSessionBinder_MapsCommandTextAndMediaDeadline(t *testing.T) {
var session, sender, inst, claim pgtype.UUID
session.Bytes[0], sender.Bytes[0], inst.Bytes[0], claim.Bytes[0] = 2, 3, 4, 5
@@ -88,7 +337,7 @@ func TestDingTalkSessionRouting_P2PCarriesStaffID(t *testing.T) {
ChatType: channel.ChatTypeP2P,
SenderID: "staff-7",
}}
- key, cfg := dingtalkSessionRouting(msg)
+ key, cfg := dingtalkSessionRouting(msg, pgtype.UUID{})
if key != "cid-1" {
t.Errorf("binding key = %q, want conversation id", key)
}
@@ -107,7 +356,7 @@ func TestDingTalkSessionRouting_GroupOmitsStaffID(t *testing.T) {
ChatType: channel.ChatTypeGroup,
SenderID: "staff-7",
}}
- _, cfg := dingtalkSessionRouting(msg)
+ _, cfg := dingtalkSessionRouting(msg, pgtype.UUID{})
var dc dingtalkBindingConfig
_ = json.Unmarshal(cfg, &dc)
if dc.ConversationType != convTypeGroup || dc.StaffID != "" {
@@ -120,7 +369,7 @@ func TestOutboundTarget_RoundTripsBindingConfig(t *testing.T) {
ChatID: "cid-3",
ChatType: channel.ChatTypeP2P,
SenderID: "staff-3",
- }})
+ }}, pgtype.UUID{})
target := outboundTarget(db.ChannelChatSessionBinding{ChannelChatID: "cid-3", Config: cfg})
if target.ConversationType != convTypeP2P || target.StaffID != "staff-3" || target.ConversationID != "cid-3" {
t.Errorf("round-tripped target = %+v", target)
@@ -133,3 +382,182 @@ func TestOutboundTarget_FallsBackToChatID(t *testing.T) {
t.Errorf("missing config must fall back to a group send on chat id: %+v", target)
}
}
+
+func TestSessionBinder_ClearsStaleGroupBindingAndStampsAgent(t *testing.T) {
+ var installationID, agentID pgtype.UUID
+ installationID.Bytes[0], agentID.Bytes[0] = 8, 9
+ installationID.Valid, agentID.Valid = true, true
+ queries := &fakeSessionQueries{}
+ capture := &captureChatSession{}
+ binder := &sessionBinder{q: queries, session: capture}
+ if _, err := binder.EnsureSession(context.Background(), engine.EnsureSessionParams{
+ Installation: engine.ResolvedInstallation{ID: installationID, AgentID: agentID},
+ Message: channel.InboundMessage{Source: channel.Source{
+ ChatID: "cid-routed", ChatType: channel.ChatTypeGroup,
+ }},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if queries.params.InstallationID != installationID || queries.params.ConversationID != "cid-routed" || queries.params.AgentID != agentID {
+ t.Fatalf("stale binding guard params = %+v", queries.params)
+ }
+ var cfg dingtalkBindingConfig
+ if err := json.Unmarshal(capture.ensure.BindingConfig, &cfg); err != nil {
+ t.Fatal(err)
+ }
+ if cfg.AgentID == "" {
+ t.Fatalf("group binding config did not stamp routed agent: %+v", cfg)
+ }
+}
+
+func TestSessionBinder_StopsWhenGroupRouteChanged(t *testing.T) {
+ queries := &fakeSessionQueries{matches: []bool{false}}
+ capture := &captureChatSession{}
+ binder := &sessionBinder{q: queries, session: capture}
+ _, err := binder.EnsureSession(context.Background(), engine.EnsureSessionParams{
+ Installation: engine.ResolvedInstallation{ID: pgtype.UUID{Valid: true}, AgentID: pgtype.UUID{Valid: true}},
+ Message: channel.InboundMessage{Source: channel.Source{
+ ChatID: "cid-reassigned", ChatType: channel.ChatTypeGroup,
+ }},
+ })
+ if err == nil || capture.ensureCalls != 0 {
+ t.Fatalf("route change err=%v ensure calls=%d, want error before session creation", err, capture.ensureCalls)
+ }
+}
+
+func TestSessionBinder_GroupRouteFailureMatrix(t *testing.T) {
+ queryErr := errors.New("route query failed")
+ cleanupErr := errors.New("stale binding cleanup failed")
+ ensureErr := errors.New("ensure session failed")
+ for _, tc := range []struct {
+ name string
+ queries *fakeSessionQueries
+ ensureErr error
+ wantErr error
+ wantContains string
+ wantEnsures int
+ }{
+ {name: "initial route query error", queries: &fakeSessionQueries{matchErrs: []error{queryErr}}, wantErr: queryErr, wantContains: "verify dingtalk group route"},
+ {name: "initial stale binding cleanup error", queries: &fakeSessionQueries{matches: []bool{true}, deleteErrs: []error{cleanupErr}}, wantErr: cleanupErr, wantContains: "retire stale dingtalk group session"},
+ {name: "underlying ensure session error", queries: &fakeSessionQueries{matches: []bool{true}}, ensureErr: ensureErr, wantErr: ensureErr, wantEnsures: 1},
+ {name: "recheck route query error", queries: &fakeSessionQueries{matches: []bool{true, true}, matchErrs: []error{nil, queryErr}}, wantErr: queryErr, wantContains: "recheck dingtalk group route", wantEnsures: 1},
+ {name: "recheck stale binding cleanup error", queries: &fakeSessionQueries{matches: []bool{true, true}, deleteErrs: []error{nil, cleanupErr}}, wantErr: cleanupErr, wantContains: "recheck dingtalk group session", wantEnsures: 1},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ capture := &captureChatSession{ensureErr: tc.ensureErr}
+ _, err := (&sessionBinder{q: tc.queries, session: capture}).EnsureSession(context.Background(), dingtalkGroupEnsureParams())
+ if !errors.Is(err, tc.wantErr) {
+ t.Fatalf("EnsureSession error = %v, want %v", err, tc.wantErr)
+ }
+ if tc.wantContains != "" && !strings.Contains(err.Error(), tc.wantContains) {
+ t.Fatalf("EnsureSession error = %q, want context %q", err, tc.wantContains)
+ }
+ if capture.ensureCalls != tc.wantEnsures {
+ t.Fatalf("underlying ensure calls = %d, want %d", capture.ensureCalls, tc.wantEnsures)
+ }
+ if capture.appendCalls != 0 {
+ t.Fatalf("failed session resolution appended %d messages, want 0", capture.appendCalls)
+ }
+ })
+ }
+}
+
+func TestSessionBinder_RouteChangesAfterSessionCreation(t *testing.T) {
+ queries := &fakeSessionQueries{matches: []bool{true, false}}
+ capture := &captureChatSession{}
+ _, err := (&sessionBinder{q: queries, session: capture}).EnsureSession(context.Background(), dingtalkGroupEnsureParams())
+ if !errors.Is(err, engine.ErrRouteChanged) {
+ t.Fatalf("post-create route conflict = %v, want route changed", err)
+ }
+ if capture.ensureCalls != 1 {
+ t.Fatalf("underlying ensure calls = %d, want 1 before recheck conflict", capture.ensureCalls)
+ }
+ if capture.appendCalls != 0 {
+ t.Fatalf("post-create route conflict appended %d messages, want 0", capture.appendCalls)
+ }
+}
+
+func TestSessionBinder_RetryExhaustionReturnsRouteChanged(t *testing.T) {
+ queries := &fakeSessionQueries{
+ matches: []bool{true, true, true, true, true, true},
+ deleteCounts: []int64{0, 1, 0, 1, 0, 1},
+ }
+ capture := &captureChatSession{}
+ _, err := (&sessionBinder{q: queries, session: capture}).EnsureSession(context.Background(), dingtalkGroupEnsureParams())
+ if !errors.Is(err, engine.ErrRouteChanged) {
+ t.Fatalf("retry exhaustion error = %v, want route changed", err)
+ }
+ if capture.ensureCalls != 3 || queries.matchCalls != 6 || queries.deleteCalls != 6 {
+ t.Fatalf("retry attempts = ensure %d match %d cleanup %d, want 3/6/6", capture.ensureCalls, queries.matchCalls, queries.deleteCalls)
+ }
+ if capture.appendCalls != 0 {
+ t.Fatalf("retry exhaustion appended %d messages, want 0", capture.appendCalls)
+ }
+}
+
+func dingtalkGroupEnsureParams() engine.EnsureSessionParams {
+ return engine.EnsureSessionParams{
+ Installation: engine.ResolvedInstallation{
+ ID: pgtype.UUID{Bytes: [16]byte{8}, Valid: true},
+ AgentID: pgtype.UUID{Bytes: [16]byte{9}, Valid: true},
+ },
+ Message: channel.InboundMessage{Source: channel.Source{
+ ChatID: "cid-routed", ChatType: channel.ChatTypeGroup,
+ }},
+ }
+}
+
+func TestSessionBinder_AppendFenceMapsStaleRevisionToRouteChanged(t *testing.T) {
+ var installationID, agentID pgtype.UUID
+ installationID.Bytes[0], agentID.Bytes[0] = 8, 9
+ installationID.Valid, agentID.Valid = true, true
+ capture := &captureChatSession{runGuard: true}
+ var got db.LockDingTalkGroupRouteForAppendParams
+ binder := &sessionBinder{
+ session: capture,
+ lockRouteForAppend: func(_ context.Context, _ pgx.Tx, params db.LockDingTalkGroupRouteForAppendParams) error {
+ got = params
+ return pgx.ErrNoRows
+ },
+ }
+ _, err := binder.AppendMessage(context.Background(), engine.AppendParams{
+ InstallationID: installationID,
+ AgentID: agentID,
+ RouteRevision: 11,
+ Message: channel.InboundMessage{Source: channel.Source{
+ ChatID: "cid-fenced", ChatType: channel.ChatTypeGroup,
+ }},
+ })
+ if !errors.Is(err, engine.ErrRouteChanged) {
+ t.Fatalf("stale append fence error = %v, want route changed", err)
+ }
+ if got.InstallationID != installationID || got.AgentID != agentID || got.ConversationID != "cid-fenced" || got.RouteRevision != 11 {
+ t.Fatalf("append fence params = %+v", got)
+ }
+}
+
+func TestSessionBinder_AppendFenceReturnsInfrastructureErrorWithoutAppend(t *testing.T) {
+ lockErr := errors.New("route lock database unavailable")
+ capture := &captureChatSession{runGuard: true}
+ binder := &sessionBinder{
+ session: capture,
+ lockRouteForAppend: func(context.Context, pgx.Tx, db.LockDingTalkGroupRouteForAppendParams) error {
+ return lockErr
+ },
+ }
+
+ _, err := binder.AppendMessage(context.Background(), engine.AppendParams{
+ InstallationID: pgtype.UUID{Bytes: [16]byte{8}, Valid: true},
+ AgentID: pgtype.UUID{Bytes: [16]byte{9}, Valid: true},
+ RouteRevision: 11,
+ Message: channel.InboundMessage{Source: channel.Source{
+ ChatID: "cid-fenced", ChatType: channel.ChatTypeGroup,
+ }},
+ })
+ if !errors.Is(err, lockErr) || !strings.Contains(err.Error(), "lock dingtalk group route for append") {
+ t.Fatalf("append fence error = %v, want wrapped infrastructure error", err)
+ }
+ if capture.appendCalls != 1 || capture.appended != 0 {
+ t.Fatalf("append calls=%d durable appends=%d, want 1/0", capture.appendCalls, capture.appended)
+ }
+}
diff --git a/server/internal/migrations/dingtalk_group_route_migration_test.go b/server/internal/migrations/dingtalk_group_route_migration_test.go
new file mode 100644
index 0000000000..0ad9180451
--- /dev/null
+++ b/server/internal/migrations/dingtalk_group_route_migration_test.go
@@ -0,0 +1,117 @@
+package migrations
+
+import (
+ "context"
+ "errors"
+ "os"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+const dingtalkRouteMigrationTestSchema = "dingtalk_route_migration_test"
+
+func TestDingTalkGroupRouteMigrationsUpDownAndCatalog(t *testing.T) {
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ t.Skip("integration test requires Postgres at DATABASE_URL")
+ }
+
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ t.Fatalf("connect to Postgres: %v", err)
+ }
+ defer pool.Close()
+
+ conn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire Postgres connection: %v", err)
+ }
+ defer conn.Release()
+
+ cleanup := func() {
+ _, _ = pool.Exec(context.Background(), "DROP SCHEMA IF EXISTS "+dingtalkRouteMigrationTestSchema+" CASCADE")
+ }
+ cleanup()
+ t.Cleanup(cleanup)
+ if _, err := conn.Exec(ctx, "CREATE SCHEMA "+dingtalkRouteMigrationTestSchema); err != nil {
+ t.Fatalf("create isolated migration schema: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `SELECT set_config('search_path', $1, false)`, dingtalkRouteMigrationTestSchema); err != nil {
+ t.Fatalf("set isolated migration search path: %v", err)
+ }
+
+ for _, name := range []string{
+ "304_dingtalk_group_route.up.sql",
+ "305_dingtalk_group_route_installation_conversation_unique.up.sql",
+ "306_dingtalk_group_route_workspace_index.up.sql",
+ "307_dingtalk_group_route_id_unique.up.sql",
+ } {
+ applyMigrationFile(t, ctx, conn.Conn(), name)
+ }
+
+ assertDingTalkRouteIndex(t, ctx, conn.Conn(), "idx_dingtalk_group_route_installation_conversation", true)
+ assertDingTalkRouteIndex(t, ctx, conn.Conn(), "idx_dingtalk_group_route_workspace", false)
+ assertDingTalkRouteIndex(t, ctx, conn.Conn(), "idx_dingtalk_group_route_id_unique", true)
+
+ const stableID = "d2750000-0000-4000-8000-000000000001"
+ if _, err := conn.Exec(ctx, `
+ INSERT INTO dingtalk_group_route (
+ id, workspace_id, installation_id, conversation_id, agent_id
+ ) VALUES
+ ($1, 'd2750000-0000-4000-8000-000000000002', 'd2750000-0000-4000-8000-000000000003', 'group-a', 'd2750000-0000-4000-8000-000000000004')
+ `, stableID); err != nil {
+ t.Fatalf("insert first stable route id: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `
+ INSERT INTO dingtalk_group_route (
+ id, workspace_id, installation_id, conversation_id, agent_id
+ ) VALUES
+ ($1, 'd2750000-0000-4000-8000-000000000002', 'd2750000-0000-4000-8000-000000000005', 'group-b', 'd2750000-0000-4000-8000-000000000004')
+ `, stableID); !isUniqueViolationMigration(err) {
+ t.Fatalf("duplicate route id error = %v, want unique violation", err)
+ }
+
+ for _, name := range []string{
+ "307_dingtalk_group_route_id_unique.down.sql",
+ "306_dingtalk_group_route_workspace_index.down.sql",
+ "305_dingtalk_group_route_installation_conversation_unique.down.sql",
+ "304_dingtalk_group_route.down.sql",
+ } {
+ applyMigrationFile(t, ctx, conn.Conn(), name)
+ }
+
+ var tableExists bool
+ if err := conn.QueryRow(ctx, `SELECT to_regclass($1) IS NOT NULL`, dingtalkRouteMigrationTestSchema+".dingtalk_group_route").Scan(&tableExists); err != nil {
+ t.Fatalf("inspect rolled-back route table: %v", err)
+ }
+ if tableExists {
+ t.Fatal("dingtalk_group_route still exists after down migrations")
+ }
+}
+
+func assertDingTalkRouteIndex(t *testing.T, ctx context.Context, conn *pgx.Conn, name string, wantUnique bool) {
+ t.Helper()
+ var unique bool
+ err := conn.QueryRow(ctx, `
+ SELECT i.indisunique
+ FROM pg_index i
+ JOIN pg_class idx ON idx.oid = i.indexrelid
+ JOIN pg_namespace n ON n.oid = idx.relnamespace
+ WHERE n.nspname = $1 AND idx.relname = $2
+ `, dingtalkRouteMigrationTestSchema, name).Scan(&unique)
+ if err != nil {
+ t.Fatalf("inspect index %s: %v", name, err)
+ }
+ if unique != wantUnique {
+ t.Fatalf("index %s unique = %t, want %t", name, unique, wantUnique)
+ }
+}
+
+func isUniqueViolationMigration(err error) bool {
+ var pgErr *pgconn.PgError
+ return errors.As(err, &pgErr) && pgErr.Code == "23505"
+}
diff --git a/server/migrations/304_dingtalk_group_route.down.sql b/server/migrations/304_dingtalk_group_route.down.sql
new file mode 100644
index 0000000000..39f94770ae
--- /dev/null
+++ b/server/migrations/304_dingtalk_group_route.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS dingtalk_group_route;
diff --git a/server/migrations/304_dingtalk_group_route.up.sql b/server/migrations/304_dingtalk_group_route.up.sql
new file mode 100644
index 0000000000..9792e8aa64
--- /dev/null
+++ b/server/migrations/304_dingtalk_group_route.up.sql
@@ -0,0 +1,15 @@
+-- A DingTalk Stream robot can participate in multiple group conversations.
+-- Keep the robot credentials on channel_installation and route each observed
+-- group to its own Multica agent. Relationships are application-owned; this
+-- table intentionally has no foreign keys or inline unique constraints.
+CREATE TABLE dingtalk_group_route (
+ id UUID NOT NULL DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL,
+ installation_id UUID NOT NULL,
+ conversation_id TEXT NOT NULL,
+ conversation_title TEXT NOT NULL DEFAULT '',
+ agent_id UUID NOT NULL,
+ revision BIGINT NOT NULL DEFAULT 1,
+ discovered_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/305_dingtalk_group_route_installation_conversation_unique.down.sql b/server/migrations/305_dingtalk_group_route_installation_conversation_unique.down.sql
new file mode 100644
index 0000000000..450082047b
--- /dev/null
+++ b/server/migrations/305_dingtalk_group_route_installation_conversation_unique.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_dingtalk_group_route_installation_conversation;
diff --git a/server/migrations/305_dingtalk_group_route_installation_conversation_unique.up.sql b/server/migrations/305_dingtalk_group_route_installation_conversation_unique.up.sql
new file mode 100644
index 0000000000..f5eeaf2650
--- /dev/null
+++ b/server/migrations/305_dingtalk_group_route_installation_conversation_unique.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_dingtalk_group_route_installation_conversation ON dingtalk_group_route(installation_id, conversation_id);
diff --git a/server/migrations/306_dingtalk_group_route_workspace_index.down.sql b/server/migrations/306_dingtalk_group_route_workspace_index.down.sql
new file mode 100644
index 0000000000..094cf7b60c
--- /dev/null
+++ b/server/migrations/306_dingtalk_group_route_workspace_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_dingtalk_group_route_workspace;
diff --git a/server/migrations/306_dingtalk_group_route_workspace_index.up.sql b/server/migrations/306_dingtalk_group_route_workspace_index.up.sql
new file mode 100644
index 0000000000..9139178a2e
--- /dev/null
+++ b/server/migrations/306_dingtalk_group_route_workspace_index.up.sql
@@ -0,0 +1 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_dingtalk_group_route_workspace ON dingtalk_group_route(workspace_id);
diff --git a/server/migrations/307_dingtalk_group_route_id_unique.down.sql b/server/migrations/307_dingtalk_group_route_id_unique.down.sql
new file mode 100644
index 0000000000..5dbb8bece2
--- /dev/null
+++ b/server/migrations/307_dingtalk_group_route_id_unique.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_dingtalk_group_route_id_unique;
diff --git a/server/migrations/307_dingtalk_group_route_id_unique.up.sql b/server/migrations/307_dingtalk_group_route_id_unique.up.sql
new file mode 100644
index 0000000000..62da7019e9
--- /dev/null
+++ b/server/migrations/307_dingtalk_group_route_id_unique.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_dingtalk_group_route_id_unique ON dingtalk_group_route(id);
diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.go
index 5f7000ed5a..ff8d9ee0c1 100644
--- a/server/pkg/db/generated/channel.sql.go
+++ b/server/pkg/db/generated/channel.sql.go
@@ -579,6 +579,9 @@ cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM doomed)
RETURNING chat_session_id
),
+cleared_dingtalk_group_routes AS (
+ DELETE FROM dingtalk_group_route WHERE installation_id IN (SELECT id FROM doomed)
+),
cleared_outbound_cards AS (
-- Reach channel_outbound_card_message (keyed by chat_session_id, no FK)
-- through the just-removed chat-session bindings, same as the reclaim path.
@@ -1541,6 +1544,10 @@ cleared_chat_sessions AS (
WHERE installation_id IN (SELECT id FROM dead)
RETURNING chat_session_id
),
+cleared_dingtalk_group_routes AS (
+ DELETE FROM dingtalk_group_route
+ WHERE installation_id IN (SELECT id FROM dead)
+),
cleared_outbound_cards AS (
-- channel_outbound_card_message is keyed by chat_session_id (no installation_id,
-- no FK), so it is reached through the just-removed chat-session bindings. On an
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 9fe70183f9..464a9e9858 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -2061,6 +2061,24 @@ func (q *Queries) ListPendingChatTasksForSession(ctx context.Context, chatSessio
return items, nil
}
+const lockChatSessionForAppend = `-- name: LockChatSessionForAppend :one
+SELECT id FROM chat_session
+WHERE id = $1
+FOR KEY SHARE
+`
+
+// The append transaction's first lock. FOR KEY SHARE conflicts with workspace
+// or session deletion but remains compatible with normal non-key session
+// updates and task enqueueing. DingTalk then acquires its route fence, matching
+// the workspace teardown order chat_session -> dingtalk_group_route and
+// preventing a route/session lock inversion.
+func (q *Queries) LockChatSessionForAppend(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, lockChatSessionForAppend, id)
+ var id_2 pgtype.UUID
+ err := row.Scan(&id_2)
+ return id_2, err
+}
+
const lockChatSessionForDelete = `-- name: LockChatSessionForDelete :one
SELECT id FROM chat_session
WHERE id = $1
diff --git a/server/pkg/db/generated/dingtalk.sql.go b/server/pkg/db/generated/dingtalk.sql.go
index 2e89595a4a..a0a9793645 100644
--- a/server/pkg/db/generated/dingtalk.sql.go
+++ b/server/pkg/db/generated/dingtalk.sql.go
@@ -25,6 +25,10 @@ cleared_chat_sessions AS (
WHERE installation_id IN (SELECT id FROM retired)
RETURNING chat_session_id
),
+cleared_group_routes AS (
+ DELETE FROM dingtalk_group_route
+ WHERE installation_id IN (SELECT id FROM retired)
+),
cleared_outbound_cards AS (
DELETE FROM channel_outbound_card_message
WHERE chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
@@ -75,6 +79,204 @@ func (q *Queries) DeleteDingTalkInstallationForReplacement(ctx context.Context,
return id, err
}
+const deleteDingTalkStaleGroupChatBinding = `-- name: DeleteDingTalkStaleGroupChatBinding :one
+WITH cleared AS (
+ DELETE FROM channel_chat_session_binding b
+ WHERE b.installation_id = $1
+ AND b.channel_type = 'dingtalk'
+ AND b.channel_chat_id = $2::text
+ AND COALESCE(
+ NULLIF(b.config ->> 'agent_id', ''),
+ (
+ SELECT i.agent_id::text
+ FROM channel_installation i
+ WHERE i.id = b.installation_id
+ ),
+ ''
+ ) <> $3::uuid::text
+ RETURNING b.chat_session_id
+), cleared_outbound_cards AS (
+ DELETE FROM channel_outbound_card_message
+ WHERE chat_session_id IN (SELECT chat_session_id FROM cleared)
+)
+SELECT count(*)::bigint AS cleared_count
+FROM cleared
+`
+
+type DeleteDingTalkStaleGroupChatBindingParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ConversationID string `json:"conversation_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+}
+
+// A route reassignment normally removes the group's binding in the same query.
+// An inbound message that resolved immediately before the reassignment can,
+// however, finish creating its old-agent binding immediately afterwards. Every
+// subsequent group message runs this guard before EnsureSession. Legacy
+// bindings have no agent stamp; preserve them when the effective route is still
+// the installation's original/default agent, but retire them after a genuine
+// reassignment so the new route can never inherit the old agent's transcript.
+func (q *Queries) DeleteDingTalkStaleGroupChatBinding(ctx context.Context, arg DeleteDingTalkStaleGroupChatBindingParams) (int64, error) {
+ row := q.db.QueryRow(ctx, deleteDingTalkStaleGroupChatBinding, arg.InstallationID, arg.ConversationID, arg.AgentID)
+ var cleared_count int64
+ err := row.Scan(&cleared_count)
+ return cleared_count, err
+}
+
+const dingTalkGroupRouteMatchesAgent = `-- name: DingTalkGroupRouteMatchesAgent :one
+SELECT EXISTS (
+ SELECT 1
+ FROM dingtalk_group_route r
+ JOIN agent a ON a.id = r.agent_id
+ AND a.workspace_id = r.workspace_id
+ WHERE r.installation_id = $1
+ AND r.conversation_id = $2::text
+ AND r.agent_id = $3
+ AND r.revision = $4
+ AND a.kind = 'user'
+ AND a.archived_at IS NULL
+) AS matches
+`
+
+type DingTalkGroupRouteMatchesAgentParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ConversationID string `json:"conversation_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ RouteRevision int64 `json:"route_revision"`
+}
+
+func (q *Queries) DingTalkGroupRouteMatchesAgent(ctx context.Context, arg DingTalkGroupRouteMatchesAgentParams) (bool, error) {
+ row := q.db.QueryRow(ctx, dingTalkGroupRouteMatchesAgent,
+ arg.InstallationID,
+ arg.ConversationID,
+ arg.AgentID,
+ arg.RouteRevision,
+ )
+ var matches bool
+ err := row.Scan(&matches)
+ return matches, err
+}
+
+const discoverDingTalkGroupRoute = `-- name: DiscoverDingTalkGroupRoute :one
+
+WITH workspace_guard AS MATERIALIZED (
+ SELECT w.id
+ FROM workspace w
+ WHERE w.id = $1
+ FOR KEY SHARE
+), installation AS MATERIALIZED (
+ SELECT i.id, i.workspace_id, i.agent_id, i.channel_type, i.config, i.status, i.ws_lease_token, i.ws_lease_expires_at, i.installer_user_id, i.installed_at, i.created_at, i.updated_at
+ FROM channel_installation i
+ JOIN workspace_guard w ON w.id = i.workspace_id
+ WHERE i.id = $2
+ AND i.workspace_id = $1
+ AND i.channel_type = 'dingtalk'
+ AND i.status = 'active'
+ FOR SHARE OF i
+), group_route AS (
+ INSERT INTO dingtalk_group_route (
+ workspace_id, installation_id, conversation_id,
+ conversation_title, agent_id
+ )
+ SELECT
+ i.workspace_id, i.id, $3::text,
+ $4::text, i.agent_id
+ FROM installation i
+ ON CONFLICT (installation_id, conversation_id) DO UPDATE SET
+ conversation_title = CASE
+ WHEN EXCLUDED.conversation_title = '' THEN dingtalk_group_route.conversation_title
+ ELSE EXCLUDED.conversation_title
+ END,
+ updated_at = CASE
+ WHEN EXCLUDED.conversation_title <> ''
+ AND EXCLUDED.conversation_title IS DISTINCT FROM dingtalk_group_route.conversation_title
+ THEN now()
+ ELSE dingtalk_group_route.updated_at
+ END
+ RETURNING agent_id, workspace_id, revision
+)
+SELECT r.agent_id,
+ r.revision,
+ EXISTS (
+ SELECT 1 FROM agent a
+ WHERE a.id = r.agent_id
+ AND a.workspace_id = r.workspace_id
+ AND a.kind = 'user'
+ AND a.archived_at IS NULL
+ ) AS agent_active
+FROM group_route r
+`
+
+type DiscoverDingTalkGroupRouteParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ConversationID string `json:"conversation_id"`
+ ConversationTitle string `json:"conversation_title"`
+}
+
+type DiscoverDingTalkGroupRouteRow struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ Revision int64 `json:"revision"`
+ AgentActive bool `json:"agent_active"`
+}
+
+// DingTalk-specific installation identity operations. The underlying channel_*
+// tables are shared, but these replacement semantics belong to DingTalk's BYO
+// AppKey model and deliberately stay out of the shared channel query surface.
+// Persist a group only after the shared inbound router has accepted the @bot
+// message and validated the sender's identity/workspace membership. The INSERT
+// default is the installation's agent; a later admin reassignment survives
+// subsequent inbound events because the conflict update refreshes only the
+// human-readable title. The returned active bit revalidates the effective route
+// target at runtime while preserving the route across archive/restore. The
+// workspace/installation locks serialize discovery with teardown and revoke:
+// revoke-first rechecks status after the wait and returns no row; discovery-
+// first completes before revoke, matching the existing in-flight semantics.
+func (q *Queries) DiscoverDingTalkGroupRoute(ctx context.Context, arg DiscoverDingTalkGroupRouteParams) (DiscoverDingTalkGroupRouteRow, error) {
+ row := q.db.QueryRow(ctx, discoverDingTalkGroupRoute,
+ arg.WorkspaceID,
+ arg.InstallationID,
+ arg.ConversationID,
+ arg.ConversationTitle,
+ )
+ var i DiscoverDingTalkGroupRouteRow
+ err := row.Scan(&i.AgentID, &i.Revision, &i.AgentActive)
+ return i, err
+}
+
+const getDingTalkGroupRouteInWorkspace = `-- name: GetDingTalkGroupRouteInWorkspace :one
+SELECT r.id, r.workspace_id, r.installation_id, r.conversation_id, r.conversation_title, r.agent_id, r.revision, r.discovered_at, r.updated_at
+FROM dingtalk_group_route r
+JOIN channel_installation i ON i.id = r.installation_id
+WHERE r.id = $1
+ AND r.workspace_id = $2
+ AND i.workspace_id = $2
+ AND i.channel_type = 'dingtalk'
+ AND i.status = 'active'
+`
+
+type GetDingTalkGroupRouteInWorkspaceParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) GetDingTalkGroupRouteInWorkspace(ctx context.Context, arg GetDingTalkGroupRouteInWorkspaceParams) (DingtalkGroupRoute, error) {
+ row := q.db.QueryRow(ctx, getDingTalkGroupRouteInWorkspace, arg.ID, arg.WorkspaceID)
+ var i DingtalkGroupRoute
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.InstallationID,
+ &i.ConversationID,
+ &i.ConversationTitle,
+ &i.AgentID,
+ &i.Revision,
+ &i.DiscoveredAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
const getDingTalkInstallationOwnerForUpdate = `-- name: GetDingTalkInstallationOwnerForUpdate :one
SELECT id, COALESCE(config ->> 'app_id', '')::text AS app_id
FROM channel_installation
@@ -105,8 +307,91 @@ func (q *Queries) GetDingTalkInstallationOwnerForUpdate(ctx context.Context, arg
return i, err
}
-const lockDingTalkInstallationOwner = `-- name: LockDingTalkInstallationOwner :exec
+const listDingTalkGroupRoutesByWorkspace = `-- name: ListDingTalkGroupRoutesByWorkspace :many
+SELECT r.id, r.workspace_id, r.installation_id, r.conversation_id, r.conversation_title, r.agent_id, r.revision, r.discovered_at, r.updated_at
+FROM dingtalk_group_route r
+JOIN channel_installation i ON i.id = r.installation_id
+WHERE r.workspace_id = $1
+ AND i.workspace_id = $1
+ AND i.channel_type = 'dingtalk'
+ AND i.status = 'active'
+ORDER BY r.discovered_at ASC
+`
+
+func (q *Queries) ListDingTalkGroupRoutesByWorkspace(ctx context.Context, workspaceID pgtype.UUID) ([]DingtalkGroupRoute, error) {
+ rows, err := q.db.Query(ctx, listDingTalkGroupRoutesByWorkspace, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []DingtalkGroupRoute{}
+ for rows.Next() {
+ var i DingtalkGroupRoute
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.InstallationID,
+ &i.ConversationID,
+ &i.ConversationTitle,
+ &i.AgentID,
+ &i.Revision,
+ &i.DiscoveredAt,
+ &i.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const lockDingTalkGroupRouteForAppend = `-- name: LockDingTalkGroupRouteForAppend :one
+WITH target_agent AS MATERIALIZED (
+ SELECT a.id
+ FROM agent a
+ WHERE a.id = $3
+ AND a.kind = 'user'
+ AND a.archived_at IS NULL
+ FOR SHARE
+)
+SELECT r.revision
+FROM dingtalk_group_route r
+WHERE r.installation_id = $1
+ AND r.conversation_id = $2::text
+ AND r.agent_id = $3
+ AND r.revision = $4
+ AND EXISTS (SELECT 1 FROM target_agent)
+FOR SHARE OF r
+`
+
+type LockDingTalkGroupRouteForAppendParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ConversationID string `json:"conversation_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ RouteRevision int64 `json:"route_revision"`
+}
+
+// This is the durable cutover fence. The active target agent and route are
+// locked in the same order as ReassignDingTalkGroupRoute, and the lock remains
+// held by AppendUserMessage's transaction until the message and dedup mark
+// commit. A PATCH that wins first changes revision and produces no row; an
+// inbound append that wins first makes PATCH wait until that append commits.
+func (q *Queries) LockDingTalkGroupRouteForAppend(ctx context.Context, arg LockDingTalkGroupRouteForAppendParams) (int64, error) {
+ row := q.db.QueryRow(ctx, lockDingTalkGroupRouteForAppend,
+ arg.InstallationID,
+ arg.ConversationID,
+ arg.AgentID,
+ arg.RouteRevision,
+ )
+ var revision int64
+ err := row.Scan(&revision)
+ return revision, err
+}
+const lockDingTalkInstallationOwner = `-- name: LockDingTalkInstallationOwner :exec
SELECT pg_advisory_xact_lock(
hashtextextended(
($1::uuid)::text || ':' ||
@@ -121,9 +406,6 @@ type LockDingTalkInstallationOwnerParams struct {
AgentID pgtype.UUID `json:"agent_id"`
}
-// DingTalk-specific installation identity operations. The underlying channel_*
-// tables are shared, but these replacement semantics belong to DingTalk's BYO
-// AppKey model and deliberately stay out of the shared channel query surface.
// Serializes install / replacement decisions for one logical
// (workspace, agent, channel) slot. A different-AppKey replacement deletes the
// old row and inserts a fresh installation id; the advisory lock closes the
@@ -133,3 +415,106 @@ func (q *Queries) LockDingTalkInstallationOwner(ctx context.Context, arg LockDin
_, err := q.db.Exec(ctx, lockDingTalkInstallationOwner, arg.WorkspaceID, arg.AgentID)
return err
}
+
+const reassignDingTalkGroupRoute = `-- name: ReassignDingTalkGroupRoute :one
+WITH workspace_guard AS MATERIALIZED (
+ SELECT w.id
+ FROM workspace w
+ WHERE w.id = $2
+ FOR KEY SHARE
+), target_agent AS MATERIALIZED (
+ SELECT a.id
+ FROM agent a
+ JOIN workspace_guard w ON w.id = a.workspace_id
+ WHERE a.id = $1
+ AND a.workspace_id = $2
+ AND a.kind = 'user'
+ AND a.archived_at IS NULL
+ FOR SHARE
+), active_installation AS MATERIALIZED (
+ SELECT i.id
+ FROM channel_installation i
+ JOIN dingtalk_group_route r ON r.installation_id = i.id
+ WHERE r.id = $3
+ AND r.workspace_id = $2
+ AND i.workspace_id = $2
+ AND i.channel_type = 'dingtalk'
+ AND i.status = 'active'
+ AND EXISTS (SELECT 1 FROM target_agent)
+ FOR SHARE OF i
+), target AS (
+ SELECT r.id, r.workspace_id, r.installation_id, r.conversation_id, r.conversation_title, r.agent_id, r.revision, r.discovered_at, r.updated_at, r.agent_id AS previous_agent_id
+ FROM dingtalk_group_route r
+ JOIN active_installation i ON i.id = r.installation_id
+ WHERE r.id = $3
+ AND r.workspace_id = $2
+ FOR UPDATE OF r
+), updated AS (
+ UPDATE dingtalk_group_route r
+ SET agent_id = $1,
+ revision = r.revision + 1,
+ updated_at = now()
+ FROM target t
+ WHERE r.id = t.id
+ RETURNING r.id, r.workspace_id, r.installation_id, r.conversation_id, r.conversation_title, r.agent_id, r.revision, r.discovered_at, r.updated_at, t.previous_agent_id
+), cleared_chat_sessions AS (
+ DELETE FROM channel_chat_session_binding b
+ USING updated u
+ WHERE u.previous_agent_id IS DISTINCT FROM u.agent_id
+ AND b.installation_id = u.installation_id
+ AND b.channel_chat_id = u.conversation_id
+ RETURNING b.chat_session_id
+), cleared_outbound_cards AS (
+ DELETE FROM channel_outbound_card_message
+ WHERE chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
+)
+SELECT id, workspace_id, installation_id, conversation_id,
+ conversation_title, agent_id, revision, discovered_at, updated_at
+FROM updated
+`
+
+type ReassignDingTalkGroupRouteParams struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ID pgtype.UUID `json:"id"`
+}
+
+type ReassignDingTalkGroupRouteRow struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ConversationID string `json:"conversation_id"`
+ ConversationTitle string `json:"conversation_title"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ Revision int64 `json:"revision"`
+ DiscoveredAt pgtype.Timestamptz `json:"discovered_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
+// Reassigning a group must also sever its existing chat-session binding. The
+// next message creates a fresh session for the new agent, so transcripts and
+// pending outbound updates cannot cross agent boundaries. The old chat session
+// remains as history; only its DingTalk route and outbound card state are
+// removed. The target agent existence/workspace/archive check is repeated here
+// so a concurrent archive or delete cannot create a dangling route. The active
+// workspace, active installation, and route locks preserve the teardown order;
+// the installation is share-locked before the route is update-locked. Revoke
+// takes an exclusive lock on that same installation row, defining the race:
+// PATCH-first may finish before revoke, while revoke-first makes PATCH wait,
+// re-check status, and return no row without touching the route or binding.
+func (q *Queries) ReassignDingTalkGroupRoute(ctx context.Context, arg ReassignDingTalkGroupRouteParams) (ReassignDingTalkGroupRouteRow, error) {
+ row := q.db.QueryRow(ctx, reassignDingTalkGroupRoute, arg.AgentID, arg.WorkspaceID, arg.ID)
+ var i ReassignDingTalkGroupRouteRow
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.InstallationID,
+ &i.ConversationID,
+ &i.ConversationTitle,
+ &i.AgentID,
+ &i.Revision,
+ &i.DiscoveredAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 264302d573..7ec96f1bf4 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -509,6 +509,18 @@ type DaemonToken struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
+type DingtalkGroupRoute struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ConversationID string `json:"conversation_id"`
+ ConversationTitle string `json:"conversation_title"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ Revision int64 `json:"revision"`
+ DiscoveredAt pgtype.Timestamptz `json:"discovered_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
type Feedback struct {
ID pgtype.UUID `json:"id"`
UserID pgtype.UUID `json:"user_id"`
diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.go
index c98bd4efc9..5a94e22b46 100644
--- a/server/pkg/db/generated/workspace.sql.go
+++ b/server/pkg/db/generated/workspace.sql.go
@@ -72,6 +72,9 @@ cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM ws_installations)
RETURNING chat_session_id
),
+cleared_dingtalk_group_routes AS (
+ DELETE FROM dingtalk_group_route WHERE workspace_id = $1
+),
cleared_outbound_cards AS (
-- channel_outbound_card_message is keyed by chat_session_id (no FK); its own
-- chat_session rows cascade away with the workspace, so reach the cards through
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index 49aeaac9f2..30d1490b6d 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -386,6 +386,9 @@ deleted_channel_chat_bindings AS (
WHERE installation_id IN (SELECT id FROM ws_channel_installations)
OR chat_session_id IN (SELECT id FROM ws_sessions)
),
+deleted_dingtalk_group_routes AS (
+ DELETE FROM dingtalk_group_route WHERE workspace_id = $1
+),
deleted_channel_inbound_dedup AS (
DELETE FROM channel_inbound_message_dedup
WHERE installation_id IN (SELECT id FROM ws_channel_installations)
diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sql
index 956fb458fd..11d74ac164 100644
--- a/server/pkg/db/queries/channel.sql
+++ b/server/pkg/db/queries/channel.sql
@@ -209,6 +209,10 @@ cleared_chat_sessions AS (
WHERE installation_id IN (SELECT id FROM dead)
RETURNING chat_session_id
),
+cleared_dingtalk_group_routes AS (
+ DELETE FROM dingtalk_group_route
+ WHERE installation_id IN (SELECT id FROM dead)
+),
cleared_outbound_cards AS (
-- channel_outbound_card_message is keyed by chat_session_id (no installation_id,
-- no FK), so it is reached through the just-removed chat-session bindings. On an
@@ -260,6 +264,9 @@ cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM doomed)
RETURNING chat_session_id
),
+cleared_dingtalk_group_routes AS (
+ DELETE FROM dingtalk_group_route WHERE installation_id IN (SELECT id FROM doomed)
+),
cleared_outbound_cards AS (
-- Reach channel_outbound_card_message (keyed by chat_session_id, no FK)
-- through the just-removed chat-session bindings, same as the reclaim path.
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index c81e89f28d..d9a5e62a37 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -332,6 +332,16 @@ SELECT id FROM chat_session
WHERE id = $1
FOR UPDATE;
+-- name: LockChatSessionForAppend :one
+-- The append transaction's first lock. FOR KEY SHARE conflicts with workspace
+-- or session deletion but remains compatible with normal non-key session
+-- updates and task enqueueing. DingTalk then acquires its route fence, matching
+-- the workspace teardown order chat_session -> dingtalk_group_route and
+-- preventing a route/session lock inversion.
+SELECT id FROM chat_session
+WHERE id = $1
+FOR KEY SHARE;
+
-- name: LockChatSessionForRuntimeBind :one
-- Acquires an exclusive (FOR UPDATE) row lock on chat_session(id), serialising
-- "which runtime does this session execute on" against "enqueue the next task".
diff --git a/server/pkg/db/queries/dingtalk.sql b/server/pkg/db/queries/dingtalk.sql
index 5c26c6a424..887ceace96 100644
--- a/server/pkg/db/queries/dingtalk.sql
+++ b/server/pkg/db/queries/dingtalk.sql
@@ -2,6 +2,220 @@
-- tables are shared, but these replacement semantics belong to DingTalk's BYO
-- AppKey model and deliberately stay out of the shared channel query surface.
+-- name: DiscoverDingTalkGroupRoute :one
+-- Persist a group only after the shared inbound router has accepted the @bot
+-- message and validated the sender's identity/workspace membership. The INSERT
+-- default is the installation's agent; a later admin reassignment survives
+-- subsequent inbound events because the conflict update refreshes only the
+-- human-readable title. The returned active bit revalidates the effective route
+-- target at runtime while preserving the route across archive/restore. The
+-- workspace/installation locks serialize discovery with teardown and revoke:
+-- revoke-first rechecks status after the wait and returns no row; discovery-
+-- first completes before revoke, matching the existing in-flight semantics.
+WITH workspace_guard AS MATERIALIZED (
+ SELECT w.id
+ FROM workspace w
+ WHERE w.id = sqlc.arg(workspace_id)
+ FOR KEY SHARE
+), installation AS MATERIALIZED (
+ SELECT i.*
+ FROM channel_installation i
+ JOIN workspace_guard w ON w.id = i.workspace_id
+ WHERE i.id = sqlc.arg(installation_id)
+ AND i.workspace_id = sqlc.arg(workspace_id)
+ AND i.channel_type = 'dingtalk'
+ AND i.status = 'active'
+ FOR SHARE OF i
+), group_route AS (
+ INSERT INTO dingtalk_group_route (
+ workspace_id, installation_id, conversation_id,
+ conversation_title, agent_id
+ )
+ SELECT
+ i.workspace_id, i.id, sqlc.arg(conversation_id)::text,
+ sqlc.arg(conversation_title)::text, i.agent_id
+ FROM installation i
+ ON CONFLICT (installation_id, conversation_id) DO UPDATE SET
+ conversation_title = CASE
+ WHEN EXCLUDED.conversation_title = '' THEN dingtalk_group_route.conversation_title
+ ELSE EXCLUDED.conversation_title
+ END,
+ updated_at = CASE
+ WHEN EXCLUDED.conversation_title <> ''
+ AND EXCLUDED.conversation_title IS DISTINCT FROM dingtalk_group_route.conversation_title
+ THEN now()
+ ELSE dingtalk_group_route.updated_at
+ END
+ RETURNING agent_id, workspace_id, revision
+)
+SELECT r.agent_id,
+ r.revision,
+ EXISTS (
+ SELECT 1 FROM agent a
+ WHERE a.id = r.agent_id
+ AND a.workspace_id = r.workspace_id
+ AND a.kind = 'user'
+ AND a.archived_at IS NULL
+ ) AS agent_active
+FROM group_route r;
+
+-- name: ListDingTalkGroupRoutesByWorkspace :many
+SELECT r.*
+FROM dingtalk_group_route r
+JOIN channel_installation i ON i.id = r.installation_id
+WHERE r.workspace_id = sqlc.arg(workspace_id)
+ AND i.workspace_id = sqlc.arg(workspace_id)
+ AND i.channel_type = 'dingtalk'
+ AND i.status = 'active'
+ORDER BY r.discovered_at ASC;
+
+-- name: GetDingTalkGroupRouteInWorkspace :one
+-- Handler diagnosis deliberately uses the same active-installation boundary as
+-- reassignment. Retained routes stay available for reconnect internally, but a
+-- revoked installation's route is not a PATCH-visible resource.
+SELECT r.*
+FROM dingtalk_group_route r
+JOIN channel_installation i ON i.id = r.installation_id
+WHERE r.id = sqlc.arg(id)
+ AND r.workspace_id = sqlc.arg(workspace_id)
+ AND i.workspace_id = sqlc.arg(workspace_id)
+ AND i.channel_type = 'dingtalk'
+ AND i.status = 'active';
+
+-- name: ReassignDingTalkGroupRoute :one
+-- Reassigning a group must also sever its existing chat-session binding. The
+-- next message creates a fresh session for the new agent, so transcripts and
+-- pending outbound updates cannot cross agent boundaries. The old chat session
+-- remains as history; only its DingTalk route and outbound card state are
+-- removed. The target agent existence/workspace/archive check is repeated here
+-- so a concurrent archive or delete cannot create a dangling route. The active
+-- workspace, active installation, and route locks preserve the teardown order;
+-- the installation is share-locked before the route is update-locked. Revoke
+-- takes an exclusive lock on that same installation row, defining the race:
+-- PATCH-first may finish before revoke, while revoke-first makes PATCH wait,
+-- re-check status, and return no row without touching the route or binding.
+WITH workspace_guard AS MATERIALIZED (
+ SELECT w.id
+ FROM workspace w
+ WHERE w.id = sqlc.arg(workspace_id)
+ FOR KEY SHARE
+), target_agent AS MATERIALIZED (
+ SELECT a.id
+ FROM agent a
+ JOIN workspace_guard w ON w.id = a.workspace_id
+ WHERE a.id = sqlc.arg(agent_id)
+ AND a.workspace_id = sqlc.arg(workspace_id)
+ AND a.kind = 'user'
+ AND a.archived_at IS NULL
+ FOR SHARE
+), active_installation AS MATERIALIZED (
+ SELECT i.id
+ FROM channel_installation i
+ JOIN dingtalk_group_route r ON r.installation_id = i.id
+ WHERE r.id = sqlc.arg(id)
+ AND r.workspace_id = sqlc.arg(workspace_id)
+ AND i.workspace_id = sqlc.arg(workspace_id)
+ AND i.channel_type = 'dingtalk'
+ AND i.status = 'active'
+ AND EXISTS (SELECT 1 FROM target_agent)
+ FOR SHARE OF i
+), target AS (
+ SELECT r.*, r.agent_id AS previous_agent_id
+ FROM dingtalk_group_route r
+ JOIN active_installation i ON i.id = r.installation_id
+ WHERE r.id = sqlc.arg(id)
+ AND r.workspace_id = sqlc.arg(workspace_id)
+ FOR UPDATE OF r
+), updated AS (
+ UPDATE dingtalk_group_route r
+ SET agent_id = sqlc.arg(agent_id),
+ revision = r.revision + 1,
+ updated_at = now()
+ FROM target t
+ WHERE r.id = t.id
+ RETURNING r.*, t.previous_agent_id
+), cleared_chat_sessions AS (
+ DELETE FROM channel_chat_session_binding b
+ USING updated u
+ WHERE u.previous_agent_id IS DISTINCT FROM u.agent_id
+ AND b.installation_id = u.installation_id
+ AND b.channel_chat_id = u.conversation_id
+ RETURNING b.chat_session_id
+), cleared_outbound_cards AS (
+ DELETE FROM channel_outbound_card_message
+ WHERE chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
+)
+SELECT id, workspace_id, installation_id, conversation_id,
+ conversation_title, agent_id, revision, discovered_at, updated_at
+FROM updated;
+
+-- name: DingTalkGroupRouteMatchesAgent :one
+SELECT EXISTS (
+ SELECT 1
+ FROM dingtalk_group_route r
+ JOIN agent a ON a.id = r.agent_id
+ AND a.workspace_id = r.workspace_id
+ WHERE r.installation_id = sqlc.arg(installation_id)
+ AND r.conversation_id = sqlc.arg(conversation_id)::text
+ AND r.agent_id = sqlc.arg(agent_id)
+ AND r.revision = sqlc.arg(route_revision)
+ AND a.kind = 'user'
+ AND a.archived_at IS NULL
+) AS matches;
+
+-- name: LockDingTalkGroupRouteForAppend :one
+-- This is the durable cutover fence. The active target agent and route are
+-- locked in the same order as ReassignDingTalkGroupRoute, and the lock remains
+-- held by AppendUserMessage's transaction until the message and dedup mark
+-- commit. A PATCH that wins first changes revision and produces no row; an
+-- inbound append that wins first makes PATCH wait until that append commits.
+WITH target_agent AS MATERIALIZED (
+ SELECT a.id
+ FROM agent a
+ WHERE a.id = sqlc.arg(agent_id)
+ AND a.kind = 'user'
+ AND a.archived_at IS NULL
+ FOR SHARE
+)
+SELECT r.revision
+FROM dingtalk_group_route r
+WHERE r.installation_id = sqlc.arg(installation_id)
+ AND r.conversation_id = sqlc.arg(conversation_id)::text
+ AND r.agent_id = sqlc.arg(agent_id)
+ AND r.revision = sqlc.arg(route_revision)
+ AND EXISTS (SELECT 1 FROM target_agent)
+FOR SHARE OF r;
+
+-- name: DeleteDingTalkStaleGroupChatBinding :one
+-- A route reassignment normally removes the group's binding in the same query.
+-- An inbound message that resolved immediately before the reassignment can,
+-- however, finish creating its old-agent binding immediately afterwards. Every
+-- subsequent group message runs this guard before EnsureSession. Legacy
+-- bindings have no agent stamp; preserve them when the effective route is still
+-- the installation's original/default agent, but retire them after a genuine
+-- reassignment so the new route can never inherit the old agent's transcript.
+WITH cleared AS (
+ DELETE FROM channel_chat_session_binding b
+ WHERE b.installation_id = sqlc.arg(installation_id)
+ AND b.channel_type = 'dingtalk'
+ AND b.channel_chat_id = sqlc.arg(conversation_id)::text
+ AND COALESCE(
+ NULLIF(b.config ->> 'agent_id', ''),
+ (
+ SELECT i.agent_id::text
+ FROM channel_installation i
+ WHERE i.id = b.installation_id
+ ),
+ ''
+ ) <> sqlc.arg(agent_id)::uuid::text
+ RETURNING b.chat_session_id
+), cleared_outbound_cards AS (
+ DELETE FROM channel_outbound_card_message
+ WHERE chat_session_id IN (SELECT chat_session_id FROM cleared)
+)
+SELECT count(*)::bigint AS cleared_count
+FROM cleared;
+
-- name: LockDingTalkInstallationOwner :exec
-- Serializes install / replacement decisions for one logical
-- (workspace, agent, channel) slot. A different-AppKey replacement deletes the
@@ -52,6 +266,10 @@ cleared_chat_sessions AS (
WHERE installation_id IN (SELECT id FROM retired)
RETURNING chat_session_id
),
+cleared_group_routes AS (
+ DELETE FROM dingtalk_group_route
+ WHERE installation_id IN (SELECT id FROM retired)
+),
cleared_outbound_cards AS (
DELETE FROM channel_outbound_card_message
WHERE chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sql
index 351de18606..0e391b6f0c 100644
--- a/server/pkg/db/queries/workspace.sql
+++ b/server/pkg/db/queries/workspace.sql
@@ -115,6 +115,9 @@ cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM ws_installations)
RETURNING chat_session_id
),
+cleared_dingtalk_group_routes AS (
+ DELETE FROM dingtalk_group_route WHERE workspace_id = $1
+),
cleared_outbound_cards AS (
-- channel_outbound_card_message is keyed by chat_session_id (no FK); its own
-- chat_session rows cascade away with the workspace, so reach the cards through
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index 40322e31f5..1fdb13f8f5 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -436,6 +436,9 @@ deleted_channel_chat_bindings AS (
WHERE installation_id IN (SELECT id FROM ws_channel_installations)
OR chat_session_id IN (SELECT id FROM ws_sessions)
),
+deleted_dingtalk_group_routes AS (
+ DELETE FROM dingtalk_group_route WHERE workspace_id = $1
+),
deleted_channel_inbound_dedup AS (
DELETE FROM channel_inbound_message_dedup
WHERE installation_id IN (SELECT id FROM ws_channel_installations)
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index 3a347d885c..80388750c1 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -187,6 +187,7 @@ const (
// as Slack's BYO channel installation.
EventDingTalkInstallationCreated = "dingtalk_installation:created"
EventDingTalkInstallationRevoked = "dingtalk_installation:revoked"
+ EventDingTalkGroupRouteUpdated = "dingtalk_group_route:updated"
// WeCom smart-bot installation lifecycle. Same semantics as Lark /
// Slack: `created` covers both first install and re-install via