Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6426: refactor(dingtalk): safely retire group routing and enhance discovery (#7241)
YYClaw5e2d349ec4cb
diff --git a/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx b/apps/docs/content/docs/dingtalk-bot-integration.ja.mdxindex c5a25cdbd8..222f646df3 100644--- a/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx+++ b/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx@@ -1,138 +1,97 @@----title: DingTalk Bot 連携-description: Multica エージェントをあなた自身の DingTalk アプリに接続します——DingTalk オープンプラットフォームで Stream モードのロボットを作成し、その AppKey と AppSecret をコピーして Multica に貼り付ければ、DingTalk の中から DM したり、グループで @ メンションしたり、/issue と入力したりできます。+title: DingTalk Bot+description: エージェントを DingTalk に接続し、DM やグループチャットから直接仕事を依頼します。---import { Callout } from "fumadocs-ui/components/callout";-任意の[エージェント](/agents)を DingTalk Bot に接続すれば、チームは DingTalk の中から直接それを使えます——Bot に DM したり、グループで @ メンションしたり、スクリーンショットを送ったり、`/issue` と入力してアプリを開かずに [Multica イシュー](/issues)を起票したりできます。+[エージェント](/agents)を DingTalk に接続すると、そのエージェントが属するワークスペースのメンバーは、Bot に DM を送ったり、グループで @ メンションしたり、`/issue` コマンドで Multica [タスク](/issues)を直接作成したりできます。会話と実行記録は Multica ワークスペースに保存されます。-DingTalk 連携は[コミュニティメンテナンス](/community-maintained)です。毎リリースに同梱されますが、公式のサポート SLA は付きません。問題があれば [GitHub issues](https://github.com/multica-ai/multica/issues) に報告してください。--DingTalk は**自分のアプリを持ち込む(BYO: bring-your-own-app)**モデルを採用しています。ワークスペースの admin が DingTalk アプリを作成し、Stream モードのロボットを追加して、その認証情報を Multica に貼り付けます。セットアップ時に選んだエージェントが DM と新しく検出されたグループのデフォルトになります。同じロボットを複数のグループに追加し、グループごとに別のエージェントへルーティングできます。(これは紐づけがスキャンしてインストールするフローである [Lark](/lark-bot-integration) とは異なります。)--セットアップ全体は以下のとおりで、所要時間は約 5 分です。最終的に、Multica に貼り付ける 2 つの認証情報が得られます。+<Callout type="info">+DingTalk 連携は[コミュニティがメンテナンス](/community-maintained)しており、公式サポートの SLA はありません。問題がある場合は [GitHub issues](https://github.com/multica-ai/multica/issues) に報告してください。+</Callout>-- **AppKey** —— アプリの client id-- **AppSecret** —— アプリの client secret-## DingTalk アプリをセットアップする+## Bot を接続する-### 1. アプリを作成し、Stream モードのロボットを追加する+エージェントの作成者またはワークスペースの owner/admin は、エージェントを DingTalk に接続できます。エージェントと DingTalk Bot は 1 対 1 の接続関係です。-1. [DingTalk オープンプラットフォーム](https://open-dev.dingtalk.com)を開き、**企業内部アプリ**(企业内部应用)を作成します。-2. そのアプリを開き、**ロボット**(机器人)機能を追加します。-3. ロボット設定で、**メッセージ受信モード**を **Stream モード**(推送模式)に設定します。これにより、Bot は webhook を受け取るのではなく、長時間維持される push 接続を通じて外向きに接続するようになります。+## 1. Stream モードのロボットを作成する-これがプラットフォーム層で Multica が必要とするすべてです——Bot は Stream モードで外向きに接続するので、公開アドレスを設定する必要はありません。+1. [DingTalk オープンプラットフォーム](https://open-dev.dingtalk.com)で**企業内部アプリ**を作成します。+2. ロボット機能を有効にし、**メッセージ受信モード**を **Stream モード**に設定します。-| 設定 | なぜそこにあるか |-|---|---|-| **企業内部アプリ** | ロボットを保持し、AppKey / AppSecret 認証情報を発行するアプリのコンテナです。 |-| **ロボット機能** | @ メンションされ、返信を投稿する Bot のアイデンティティを作成します。 |-| **Stream モード** | Bot は長時間維持される Stream 接続を通じて外向きに接続します——**公開 webhook/URL は不要**です。 |-| **ロボット送信権限** | Bot が DingTalk にメッセージを送り返せるようにします(エージェントの返信や能動的なメッセージ)。 |-| **メッセージ読み取り権限** | Bot が 1:1 メッセージと、自分を @ メンションしたグループメッセージを受け取れるようにします。 |+## 2. ロボットに権限を付与する-**webhook URL も OAuth リダイレクト URL もありません**。ロボットは Stream モードで動作し、BYO は OAuth を使わないからです。+**ロボットメッセージ送信権限**(`qyapi_robot_sendmsg`)はデフォルトで追加されています。Multica に Bot 名を表示するには、**DingTalk グループ基本情報管理権限**(`qyapi_chat_manage`)を手動で追加します。-<Callout type="info">-DingTalk にはネイティブの入力中/リアクションのインジケーターがないため——Slack とは異なり——Bot は処理を始めると短い「処理中」の合図を先に返し、完全な返信はエージェントの処理が終わってから届きます。短時間に連投したメッセージは 1 つの合図にまとめられます。-</Callout>+## 3. アプリ認証情報を取得する-### 2. ロボットに権限を付与する+**凭证与基础信息**(認証情報と基本情報)ページを開き、**Client ID(AppKey)** と **Client Secret(AppSecret)** をコピーします。-ロボットに、**メッセージを受信**し、**メッセージを送り返す**ために必要なスコープ(ロボットのメッセージ送信権限)を付与します。送信権限がないと、エージェントは動作しても返信を配信できません。+## 4. エージェントを DingTalk に接続する-### 3. AppKey と AppSecret をコピーする+1. Multica に戻り、**エージェント → _あなたのエージェント_ → 機能 → 連携**を開きます。+2. **DingTalk に接続**をクリックします。+3. **AppKey** と **AppSecret** を入力し、送信します。-アプリの **凭证与基础信息**(認証情報と基本情報)を開き、以下をコピーします。+## 5. DingTalk アカウントと Multica アカウントを連携する-- **AppKey** —— これがアプリの **client id** です-- **AppSecret** —— これがアプリの **client secret** です+DingTalk で Bot に DM を送るか、グループで @ メンションして、アカウント連携を一度開始します。Bot との DM にリンクが届きます(有効期間は約 15 分)。リンクを開き、接続成功のメッセージが表示されたら完了です。-### 4. Multica で接続する-1. **Agents → _あなたのエージェント_** からそのエージェントを開き、**Integrations** タブ(または左サイドバーの **Integrations** 区画)を開きます。-2. **Connect DingTalk** をクリックします。-3. **AppKey** と **AppSecret** を貼り付け、**Connect** をクリックします。-4. エージェントに **Connected to DingTalk** と表示されます。Bot はこれで、自身の Stream 接続を通じて待ち受けています。+## DingTalk でエージェントに仕事を依頼する-<Callout type="warning">-2 つの認証情報は**同じ** DingTalk アプリのものでなければならず、そのアプリは 1 つの Multica ワークスペースに 1 回だけインストールできます。2 つ目のインストールや別のワークスペースへの接続は拒否されます。インストール時のエージェントは DM のデフォルトとして残り、グループは再接続せずに別のエージェントへルーティングできます。-</Callout>+### DM-<Callout type="info">-1 つのロボットを**複数のエージェント**で使うには、各 DingTalk グループに追加して一度 @ メンションし、**Settings → Integrations → DingTalk → グループルーティング**でグループごとのエージェントを選びます。別の Bot ID や DM 用エージェントが必要な場合だけ、別の DingTalk アプリをインストールしてください。-</Callout>+Bot に直接メッセージを送ります。エージェントが依頼内容の処理を終えると、結果が DM に返信されます。-## この連携でできること+### グループチャット-| 場所 | 動作 |-|---|---|-| **エージェント → Integrations** | owner と admin には **Connect DingTalk** が表示され、接続すると **Connected to DingTalk** バッジと **Disconnect** コントロールに切り替わります。 |-| **Bot に DM** | ワークスペースメンバーが 1:1 チャットで Bot に直接メッセージを送ります。会話はそのエージェントとの Multica [chat](/chat) セッションになり、すべてのメッセージが読み取られます。 |-| **グループで @ メンション** | 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 は作られません。既存の会話履歴はそのまま残ります。 |-| **返信** | エージェントの回答は、同じ 1:1 チャットまたはグループに投稿し返されます。 |+Bot を DingTalk グループに追加し、`@your-bot <メッセージ>` を送ります。追加の質問でも毎回改めて @ メンションしてください。Bot は自分宛てに @ メンションされたメッセージだけを処理します。-## Bot を使う(メンバー)+### 画像を送る-### 最初のメッセージ:アカウントを紐づける+DM とグループチャットのどちらでも、テキストと画像を混在させたメッセージを送れます。PNG、JPEG、GIF、WebP、BMP に対応し、1 メッセージあたり最大 4 枚、1 枚あたり 10 MB までです。ファイルと音声メッセージには現在対応していません。-初めて Bot を @ メンションするか DM すると、Bot は **アカウントを紐づける** プロンプトで返信し、それはプロダクト内の **/dingtalk/bind** ページを指しています。リンクをタップして Multica にサインインすると、あなたの DingTalk アイデンティティがあなたの Multica メンバーシップに紐づきます——これによって、エージェントがあなたとして振る舞えるようになります(たとえば `/issue` はあなたの名義でイシューを起票します)。このリンクは使い切りで、約 15 分で失効します。新しいものが必要なら、もう一度 Bot にメッセージを送るだけです。+### `/issue` でタスクを作成する-<Callout type="warning">-Bot を使えるのは **ワークスペースのメンバー** だけです。メンバーでない場合や、アイデンティティの紐づけをスキップした場合、Bot は実行されません——あなたのメッセージは破棄されます(内容は保存せず、監査のために記録されます)。-</Callout>+`/issue <タイトル>` または `/issue <タイトル>{改行}<詳細説明>` を送ると、新しい Multica タスクが作成され、Bot に接続されたエージェントに自動的に割り当てられます。同じメッセージの画像も、添付ファイルとしてタスクに追加されます。通常の会話メッセージとは異なり、`/issue` コマンドは Multica の「[チャット](/chat)」に記録されません。-### 対話とコマンド+### `/new` で最初から始める-- **グループで** —— Bot をグループに追加してから、`@your-bot <あなたのメッセージ>` とします。フォローアップのたびに再度メンションしてください(Bot は自分をメンションしたメッセージだけを読みます)。-- **1:1 チャットで** —— Bot を開いて直接メッセージを送ります。メンションは不要で、すべてのメッセージが読み取られます。-- **画像を送る** —— スクリーンショットや写真を、テキストの有無を問わず送れます。会話に入り、エージェントが参照できます。対応形式は PNG・JPEG・GIF・WebP・BMP、1 メッセージあたり最大 4 枚、1 枚あたり 10 MB までです。-- **イシューを起票する** —— `/issue Safari でログインのリダイレクトが壊れている` と送り、必要なら続く行に説明を書きます。Multica は同期的にイシューを作成し、同じメッセージの画像をそのイシューに添付して、ID とタイトルをチャットに返します。-- **新しく始める** —— `/new <あなたのメッセージ>` と送ると、そのメッセージを過去の文脈なしで実行します。`/new` だけを送れば、fresh-start を次の空でないメッセージに適用できます。どちらも既存の会話履歴は削除しません。+`/new` を送ると、次に送信に成功したメッセージをエージェントが新しいコンテキストで処理します。`/new <メッセージ>` を送ると、そのメッセージをすぐに新しいコンテキストで処理させることもできます。-## 管理と切断+`/new` コマンドは、エージェントに新しいコンテキストでメッセージを処理させるだけです。新しい Multica の「チャット」は作成されません。-ワークスペース全体の管理は **Settings → Integrations** にあります。-- **Connected bots** は、ワークスペース内のすべての Bot と、それぞれが紐づくエージェントを一覧表示します(すべてのメンバーから見えます)。-- **グループルーティング**は Bot が検出したすべてのグループを表示します。owner と admin はグループごとに固定のエージェントを選べ、全メンバーが現在のルートを確認できます。-- ルートを変更するたびに、選択したエージェント用の新しい Chat セッションが作成されます。エージェント A → B → A と戻しても、A の以前のセッションは再開されません。割り当てたエージェントをアーカイブするとルートは保持されますが、そのエージェントを復元するかグループを再割り当てするまで、処理は停止して利用不可の通知が返ります。-- **Disconnect** は **owner / admin 専用** です。切断すると Bot は DingTalk メッセージの受信を停止し、その接続が破棄されます。インストール記録は監査のために保持され、あとで再接続できます。+## 接続を管理する-## 権限+- **エージェント → _あなたのエージェント_ → 機能 → 連携**ページでは、エージェントの作成者とワークスペースの owner/admin が DingTalk への接続と切断を行えます。接続後は、Bot 名、Bot がメッセージを正常に処理したことのある DingTalk グループ、および各グループでの Bot のアクティビティ状況データが表示されます。エージェントの読み取り権限を持つワークスペースメンバーは、これらの情報をすべて確認できます。直近 90 日間に正常に処理されたメッセージがないグループは**長期間未使用**にまとめられ、展開時に読み込まれます。+- **設定 → 連携**ページには、現在のワークスペース内で、自分に読み取り権限があり、DingTalk に接続済みのエージェントがすべて表示されます。Bot の DingTalk グループ内でのアクティビティ状況データも表示されます。ワークスペースの owner/admin は、リスト内の任意のエージェントの DingTalk 接続をここから直接切断できます。切断後、Bot はメッセージを受信しなくなりますが、インストール記録は監査用に保持されます。ワークスペースの owner/admin は、グループを一覧から削除することもできます。この操作で会話やメッセージが削除されることはありません。その後、DingTalk アカウントを連携済みのワークスペースメンバーが同じグループで Bot を @メンションし、そのメッセージを Multica が正常に受け付けると、グループは再び表示されます。-- **接続 / 切断** にはワークスペースの **owner** または **admin** が必要です。-- **Bot との対話** には、DingTalk アイデンティティを紐づけたワークスペースメンバーであることが必要です。それ以外の人は一律に破棄されます。-- 破棄されたメッセージの本文が保存されることはありません——監査のために破棄理由だけが記録されます。-## セルフホストのセットアップ+## セルフホスト設定-Multica Cloud では連携はすでに利用可能です——このセクションは飛ばしてください。+Multica Cloud ユーザーはこのセクションをスキップできます。セルフホスト環境では、DingTalk の `AppSecret` を暗号化するためのキーを先に設定します。-セルフホストの場合、DingTalk は**保存時の暗号化キーを設定するまでオフ**です。このキーは各アプリの AppSecret をデータベース保存前に暗号化します。AppKey は機密情報ではないインストールのルーティング識別子として平文で保存されます。BYO にはデプロイレベルの OAuth の client id/secret は**不要**です——各インストールは admin が貼り付けた認証情報を使います。+```dotenv+MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>+```-1. 32 バイトのキーを生成し、API サーバーに設定します。+次のコマンドで生成できます。- ```dotenv- MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>- ```+```bash+openssl rand -base64 32+```- たとえば: `openssl rand -base64 32`。+API サービスを再起動した後、DingTalk に接続します。このキーは長期間保存してください。変更または紛失すると、既存のトークンを復号できず、再接続が必要になります。-2. API を再起動します。キーを設定するまで、**Settings → Integrations** には「DingTalk integration not enabled」という通知が表示され、**Connect DingTalk** のエントリポイントは非表示のままになります。+アカウント連携リンクは `MULTICA_APP_URL` を使用し、未設定の場合は `FRONTEND_ORIGIN` にフォールバックします。メンバーがアクセスできる Multica のアドレスを指定してください。-<Callout type="info">-キーはちょうど 32 バイトにデコードされなければなりません——`openssl rand -base64 32` はそれを満たします。これは長く使い続けるシークレットとして扱ってください。ローテーションしたり紛失したりすると、すでに保存済みの認証情報が復号できなくなり、すべての Bot を再接続せざるを得なくなります。「アカウントを紐づける」リンクは、Web アプリの URL(`MULTICA_APP_URL`、未設定時は `FRONTEND_ORIGIN` にフォールバック)から生成されます。通常のデプロイではこれは既に設定されているため、追加で設定するものはありません。-</Callout>## 次に-- [Chat 連携](/channels) — チャンネルエンジン、セッション、認可の仕組み-- [エージェント](/agents) · [Chat](/chat) · [イシュー](/issues)-- [環境変数](/environment-variables) — セルフホスト構成の完全なリファレンス+- [チャット連携](/channels) —— Channel エンジン、セッション、認可の仕組み+- [エージェント](/agents) · [Chat](/chat) · [タスク](/issues)+- [環境変数](/environment-variables) —— セルフホスト設定の完全なリファレンスdiff --git a/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx b/apps/docs/content/docs/dingtalk-bot-integration.ko.mdxindex 00a2f7cb0e..fda0108066 100644--- a/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx+++ b/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx@@ -1,138 +1,97 @@----title: DingTalk Bot 연동-description: Multica 에이전트를 자체 DingTalk 앱에 연결하세요 — DingTalk 오픈 플랫폼에서 Stream 모드 로봇을 만들고, AppKey + AppSecret을 복사해 Multica에 붙여넣은 다음, DingTalk 안에서 DM하거나 그룹에서 @로 멘션하거나 /issue를 입력하세요.+title: DingTalk Bot+description: 에이전트를 DingTalk에 연결해 DM이나 그룹 채팅에서 바로 작업을 요청합니다.---import { Callout } from "fumadocs-ui/components/callout";-아무 [에이전트](/agents)나 DingTalk 봇에 연결하면, 팀이 DingTalk 안에서 바로 그 에이전트와 함께 일할 수 있습니다 — 봇에게 DM을 보내거나, 그룹에서 `@`로 멘션하거나, 스크린샷을 보내거나, `/issue`를 입력해 앱을 열지 않고도 [Multica 이슈](/issues)를 생성하세요.+[에이전트](/agents)를 DingTalk에 연결하면 해당 에이전트가 속한 워크스페이스의 멤버는 봇에게 DM을 보내거나, 그룹에서 @ 멘션하거나, `/issue` 명령으로 Multica [태스크](/issues)를 바로 만들 수 있습니다. 대화와 실행 기록은 Multica 워크스페이스에 저장됩니다.-DingTalk 연동은 [커뮤니티가 유지관리](/community-maintained)합니다. 매 릴리스에 포함되지만 공식 지원 SLA는 제공되지 않습니다. 문제가 있으면 [GitHub issues](https://github.com/multica-ai/multica/issues)에 보고해 주세요.--DingTalk은 **자체 앱 사용(BYO)** 모델을 따릅니다. 워크스페이스 admin이 DingTalk 앱을 만들고 Stream 모드 로봇을 추가한 다음, 그 자격 증명을 Multica에 붙여넣습니다. 설정할 때 선택한 에이전트가 DM과 새로 발견된 그룹의 기본 에이전트가 됩니다. 같은 로봇을 여러 그룹에 추가하고 그룹마다 다른 에이전트로 라우팅할 수 있습니다. (바인딩이 스캔하여 설치하는 방식인 [Lark](/lark-bot-integration)와는 다릅니다.)--전체 설정은 아래에 있으며 약 5분이 걸립니다. 마지막에는 Multica에 붙여넣을 두 개의 자격 증명을 얻게 됩니다:+<Callout type="info">+DingTalk 연동은 [커뮤니티가 유지관리](/community-maintained)하며 공식 지원 SLA는 제공되지 않습니다. 문제가 있으면 [GitHub issues](https://github.com/multica-ai/multica/issues)에 보고해 주세요.+</Callout>-- **AppKey** — 앱의 client id-- **AppSecret** — 앱의 client secret-## DingTalk 앱 설정하기+## 봇 연결하기-### 1. 앱을 만들고 Stream 모드 로봇 추가하기+에이전트 생성자 또는 워크스페이스 owner/admin은 에이전트를 DingTalk에 연결할 수 있습니다. 에이전트와 DingTalk 봇은 1:1로 연결됩니다.-1. [DingTalk 오픈 플랫폼](https://open-dev.dingtalk.com)으로 이동해 **기업 내부 앱**(企业内部应用)을 만듭니다.-2. 그 앱을 열고 **로봇**(机器人) 기능을 추가합니다.-3. 로봇 설정에서 **메시지 수신 모드**를 **Stream 모드**(推送模式)로 설정합니다. 이것이 봇으로 하여금 webhook을 받는 대신, 오래 유지되는 push 연결을 통해 밖으로 연결하게 합니다.+## 1. Stream 모드 로봇 만들기-이것이 플랫폼 수준에서 Multica가 필요로 하는 전부입니다 — 봇이 Stream 모드로 밖으로 연결하므로, 공개 주소를 구성할 필요가 없습니다:+1. [DingTalk 오픈 플랫폼](https://open-dev.dingtalk.com)에서 **기업 내부 앱**을 만듭니다.+2. 로봇 기능을 활성화하고 **메시지 수신 모드**를 **Stream 모드**로 설정합니다.-| 설정 | 이유 |-|---|---|-| **기업 내부 앱** | 로봇을 담고 AppKey / AppSecret 자격 증명을 발급하는 앱 컨테이너입니다. |-| **로봇 기능** | `@`로 멘션되고 답변을 게시하는 봇 신원을 생성합니다. |-| **Stream 모드** | 봇이 오래 유지되는 Stream 연결로 밖으로 연결합니다 — **공개 webhook / URL이 필요 없습니다**. |-| **로봇 전송 권한** | 봇이 DingTalk으로 메시지를 다시 보낼 수 있게 합니다(에이전트의 답변과 능동적 메시지). |-| **메시지 읽기 권한** | 봇이 1:1 메시지와, 자신을 `@`로 멘션한 그룹 메시지를 받을 수 있게 합니다. |+## 2. 로봇에 권한 부여하기-**webhook URL도 OAuth redirect URL도 없습니다.** 로봇이 Stream 모드로 동작하고, BYO는 OAuth를 사용하지 않기 때문입니다.+**로봇 메시지 전송 권한**(`qyapi_robot_sendmsg`)은 기본으로 추가되어 있습니다. Multica에 봇 이름을 표시하려면 **DingTalk 그룹 기본 정보 관리 권한**(`qyapi_chat_manage`)을 수동으로 추가하세요.-<Callout type="info">-DingTalk에는 기본 입력 중 / 반응 표시기가 없으므로 — Slack과 달리 — 봇이 처리를 시작하면 짧은 "처리 중" 안내를 먼저 보내고, 전체 답변은 에이전트가 끝난 뒤에 도착합니다. 짧은 시간에 연달아 보낸 메시지는 하나의 안내로 합쳐집니다.-</Callout>+## 3. 앱 자격 증명 가져오기-### 2. 로봇에 권한 부여하기+**凭证与基础信息**(자격 증명 및 기본 정보) 페이지에서 **Client ID(AppKey)**와 **Client Secret(AppSecret)**을 복사합니다.-로봇이 **메시지를 받고** **메시지를 다시 보낼** 수 있도록 필요한 스코프(로봇 메시지 전송 권한)를 부여하세요. 전송 권한이 없으면 에이전트는 실행되더라도 답변을 전달할 수 없습니다.+## 4. 에이전트를 DingTalk에 연결하기-### 3. AppKey와 AppSecret 복사하기+1. Multica로 돌아가 **에이전트 → _당신의 에이전트_ → 기능 → 연동**을 엽니다.+2. **DingTalk 연결**을 클릭합니다.+3. **AppKey**와 **AppSecret**을 입력한 뒤 제출합니다.-앱의 **凭证与基础信息**(자격 증명 및 기본 정보)을 열고 복사합니다:+## 5. DingTalk 계정과 Multica 계정 연결하기-- **AppKey** — 이것이 앱의 **client id**입니다-- **AppSecret** — 이것이 앱의 **client secret**입니다+DingTalk에서 봇에게 DM을 보내거나 그룹에서 @ 멘션해 계정 연결을 한 번 요청합니다. 봇과의 DM으로 링크가 오며 약 15분 동안 유효합니다. 링크를 열어 연결 성공 안내가 표시되면 완료입니다.-### 4. Multica에서 연결하기-1. **Agents → _당신의 에이전트_** → **Integrations** 탭(또는 왼쪽 사이드바의 **Integrations** 섹션)에서 에이전트를 엽니다.-2. **Connect DingTalk**을 클릭합니다.-3. **AppKey**와 **AppSecret**을 붙여넣은 다음 **Connect**를 클릭합니다.-4. 에이전트에 **Connected to DingTalk**이 표시됩니다. 봇은 이제 자체 Stream 연결로 수신 대기합니다.+## DingTalk에서 에이전트에게 작업 요청하기-<Callout type="warning">-두 자격 증명은 **같은** DingTalk 앱에서 와야 하며, 그 앱은 하나의 Multica 워크스페이스에 한 번만 설치할 수 있습니다. 두 번째 설치나 다른 워크스페이스 연결은 거부됩니다. 설치할 때 선택한 에이전트는 DM의 기본값으로 유지되고, 그룹은 앱을 다시 연결하지 않고 다른 에이전트로 라우팅할 수 있습니다.-</Callout>+### DM-<Callout type="info">-하나의 로봇을 **여러 에이전트**에서 사용하려면 각 DingTalk 그룹에 추가하고 한 번 @ 멘션한 뒤, **Settings → Integrations → DingTalk → 그룹 라우팅**에서 그룹별 에이전트를 선택하세요. 별도의 봇 ID나 DM 에이전트가 필요할 때만 DingTalk 앱을 따로 설치하면 됩니다.-</Callout>+봇에게 바로 메시지를 보내세요. 에이전트가 요청받은 일을 마치면 결과를 DM으로 보냅니다.-## 연동이 하는 일+### 그룹 채팅-| 위치 | 동작 |-|---|---|-| **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은 만들어지지 않습니다. 기존 대화 기록은 그대로 유지됩니다. |-| **답변** | 에이전트의 답변은 같은 1:1 채팅 또는 그룹으로 다시 게시됩니다. |+봇을 DingTalk 그룹에 추가한 뒤 `@your-bot <메시지>`를 보내세요. 후속 질문에서도 매번 봇을 다시 @ 멘션해야 합니다. 봇은 자신이 @ 멘션된 메시지만 처리합니다.-## 봇 사용하기 (멤버)+### 이미지 보내기-### 첫 메시지: 계정 연결하기+DM과 그룹 채팅 모두 텍스트와 이미지가 함께 있는 메시지를 지원합니다. PNG, JPEG, GIF, WebP, BMP 형식을 지원하며 메시지당 최대 4장, 이미지당 최대 10 MB까지 보낼 수 있습니다. 파일과 음성 메시지는 아직 지원하지 않습니다.-봇을 처음 `@`로 멘션하거나 DM하면, **계정을 연결하라**는 안내로 답하며, 이는 제품 내 **/dingtalk/bind** 페이지를 가리킵니다. 링크를 탭하고 Multica에 로그인하면, 당신의 DingTalk 신원이 Multica 멤버십에 바인딩됩니다 — 바로 이 단계가 에이전트로 하여금 당신을 대신해 행동하게 합니다(예: `/issue`는 당신 이름으로 이슈를 생성합니다). 이 링크는 일회용이며 약 15분 후에 만료됩니다. 새 링크가 필요하면 봇에게 다시 메시지를 보내세요.+### `/issue`로 태스크 만들기-<Callout type="warning">-**워크스페이스 멤버**만 봇을 사용할 수 있습니다. 멤버가 아니거나 신원 연결을 건너뛰면 봇은 실행되지 않으며, 메시지는 폐기됩니다(감사 목적으로 기록되며, 내용은 저장하지 않습니다).-</Callout>+`/issue <제목>` 또는 `/issue <제목>{줄 바꿈}<상세 설명>`을 보내면 새 Multica 태스크가 만들어지고 봇에 연결된 에이전트에 자동으로 할당됩니다. 같은 메시지의 이미지도 첨부 파일로 태스크에 추가됩니다. 일반 대화 메시지와 달리 `/issue` 명령은 Multica의 “[채팅](/chat)”에 기록을 남기지 않습니다.-### 대화와 명령+### `/new`로 새로 시작하기-- **그룹에서** — 봇을 그룹에 추가한 다음 `@your-bot <당신의 메시지>`로 보내세요. 후속 메시지마다 다시 멘션하세요(봇은 자신을 멘션한 메시지만 읽습니다).-- **1:1 채팅에서** — 봇을 열고 직접 메시지를 보내세요. 멘션이 필요 없으며, 모든 메시지를 읽습니다.-- **이미지 보내기** — 텍스트가 있든 없든 스크린샷이나 사진을 보내세요. 대화에 들어가 에이전트가 참고할 수 있습니다. PNG, JPEG, GIF, WebP, BMP를 지원하며, 메시지당 최대 4장, 장당 10 MB까지입니다.-- **이슈 생성** — `/issue Safari에서 로그인 리다이렉트가 깨졌어요`를 보내고 필요하면 다음 줄에 설명을 추가하세요. Multica가 이슈를 동기적으로 만들고, 같은 메시지의 이미지를 해당 이슈에 첨부한 뒤 ID와 제목을 채팅에 돌려줍니다.-- **새로 시작하기** — `/new <당신의 메시지>`를 보내 그 메시지를 이전 맥락 없이 실행하거나, `/new`만 보내 fresh-start를 다음 비어 있지 않은 메시지에 적용하세요. 어느 방식도 기존 대화 기록을 삭제하지 않습니다.+`/new`를 보내면 그다음으로 전송에 성공한 메시지를 에이전트가 새 맥락에서 처리합니다. `/new <메시지>`를 보내면 에이전트가 해당 메시지를 바로 새 맥락에서 처리하게 할 수도 있습니다.-## 관리 및 연결 해제+`/new` 명령은 에이전트가 메시지를 새 맥락에서 처리하게만 할 뿐, 새로운 Multica “채팅”을 만들지는 않습니다.-워크스페이스 전체 관리는 **Settings → Integrations**에 있습니다:-- **Connected bots**는 워크스페이스 내 모든 봇과 각 봇이 바인딩된 에이전트를 나열합니다(모든 멤버에게 보입니다).-- **그룹 라우팅**은 봇이 발견한 모든 그룹을 보여줍니다. owner와 admin은 그룹마다 고정 에이전트를 선택할 수 있고, 모든 멤버는 현재 라우팅을 볼 수 있습니다.-- 라우팅을 변경할 때마다 선택한 에이전트의 새 Chat 세션이 생성됩니다. 에이전트 A → B → A로 되돌려도 A의 이전 세션은 재개되지 않습니다. 할당된 에이전트를 보관하면 라우팅은 유지되지만, 해당 에이전트를 복원하거나 그룹을 다시 할당할 때까지 처리가 중지되고 사용할 수 없다는 안내가 표시됩니다.-- **Disconnect**는 **owner / admin 전용**입니다. 봇이 DingTalk 메시지 수신을 멈추고 연결이 해체됩니다. 설치 기록은 감사용으로 유지되며, 이후 다시 연결할 수 있습니다.+## 연결 관리-## 권한+- **에이전트 → _당신의 에이전트_ → 기능 → 연동** 페이지에서 에이전트 생성자와 워크스페이스 owner/admin은 DingTalk에 연결하거나 연결을 해제할 수 있습니다. DingTalk에 연결하면 이 페이지에 봇 이름, 봇이 메시지를 정상적으로 처리한 적이 있는 DingTalk 그룹, 그리고 각 그룹에서의 봇 활동 상태 데이터가 표시됩니다. 에이전트 읽기 권한이 있는 워크스페이스 멤버는 모두 이 정보를 볼 수 있습니다. 최근 90일 동안 정상적으로 처리된 메시지가 없는 그룹은 **장기 미활동**에 모이며 펼칠 때 불러옵니다.+- **설정 → 연동** 페이지에는 현재 워크스페이스에서 자신에게 읽기 권한이 있고 DingTalk에 연결된 모든 에이전트 목록과 DingTalk 그룹에서의 봇 활동 상태 데이터가 표시됩니다. 워크스페이스 owner/admin은 목록에 있는 에이전트의 DingTalk 연결을 여기서 바로 해제할 수도 있습니다. 연결을 해제하면 봇은 메시지 수신을 멈추지만 설치 기록은 감사용으로 보관됩니다. 워크스페이스 owner/admin은 그룹을 목록에서 삭제할 수도 있습니다. 이 작업은 대화나 메시지를 삭제하지 않습니다. 이후 DingTalk 계정을 연결한 워크스페이스 멤버가 같은 그룹에서 봇을 다시 @멘션하고 Multica가 해당 메시지를 정상적으로 접수하면 그룹이 다시 표시됩니다.-- **연결 / 연결 해제**에는 워크스페이스 **owner** 또는 **admin**이 필요합니다.-- **봇과 대화하기**에는 DingTalk 신원이 연결된 워크스페이스 멤버여야 합니다. 그 외의 사람은 모두 폐기됩니다.-- 폐기된 메시지의 본문은 절대 저장되지 않으며 — 감사용 폐기 사유만 기록됩니다.## 자체 호스팅 설정-Multica Cloud에서는 연동이 이미 사용 가능합니다 — 이 섹션은 건너뛰세요.+Multica Cloud 사용자는 이 섹션을 건너뛸 수 있습니다. 자체 호스팅 배포에서는 DingTalk `AppSecret`을 암호화하기 위한 키를 먼저 설정해야 합니다.-자체 호스팅의 경우, DingTalk은 **at-rest 암호화 키를 설정하기 전까지 꺼져 있습니다**. 이 키는 각 앱의 AppSecret을 데이터베이스에 저장하기 전에 암호화합니다. AppKey는 비밀이 아닌 installation 라우팅 식별자로 평문 저장됩니다. BYO에는 배포 수준의 OAuth client id/secret이 **필요 없습니다** — 각 installation은 admin이 붙여넣은 자격 증명을 사용합니다.+```dotenv+MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>+```-1. 32바이트 키를 생성해 API 서버에 설정합니다:+다음과 같이 생성할 수 있습니다.- ```dotenv- MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>- ```+```bash+openssl rand -base64 32+```- 예를 들면: `openssl rand -base64 32`.+API 서비스를 재시작한 뒤 DingTalk에 연결하세요. 이 키는 계속 보관해야 합니다. 키를 바꾸거나 잃으면 기존 토큰을 복호화할 수 없어 다시 연결해야 합니다.-2. API를 재시작하세요. 키가 설정되기 전까지 **Settings → Integrations**에는 "DingTalk integration not enabled" 안내가 표시되고, **Connect DingTalk** 진입점은 숨겨진 채로 유지됩니다.+계정 연결 링크는 `MULTICA_APP_URL`을 사용하고, 설정하지 않으면 `FRONTEND_ORIGIN`으로 대체합니다. 멤버가 접근할 수 있는 Multica 주소여야 합니다.-<Callout type="info">-키는 정확히 32바이트로 디코딩되어야 하며 — `openssl rand -base64 32`가 이를 충족합니다. 오래 유지되는 시크릿으로 다루세요: 키를 회전하거나 잃으면 이미 저장된 자격 증명을 복호화할 수 없게 되어, 모든 봇이 다시 연결해야 합니다. "계정을 연결하세요" 링크는 웹 앱 URL(`MULTICA_APP_URL`, 없으면 `FRONTEND_ORIGIN`으로 폴백)에서 만들어집니다. 일반적인 배포에서는 이미 설정되어 있으므로 추가로 구성할 것은 없습니다.-</Callout>## 다음-- [Chat 연동](/channels) — channel 엔진, 세션, 권한이 어떻게 동작하는지-- [에이전트](/agents) · [Chat](/chat) · [이슈](/issues)-- [환경 변수](/environment-variables) — 전체 자체 호스팅 구성 참조+- [채팅 연동](/channels) —— Channel 엔진, 세션, 권한 부여 방식+- [에이전트](/agents) · [Chat](/chat) · [태스크](/issues)+- [환경 변수](/environment-variables) —— 전체 자체 호스팅 설정 참조diff --git a/apps/docs/content/docs/dingtalk-bot-integration.mdx b/apps/docs/content/docs/dingtalk-bot-integration.mdxindex db0d855508..df8361be73 100644--- a/apps/docs/content/docs/dingtalk-bot-integration.mdx+++ b/apps/docs/content/docs/dingtalk-bot-integration.mdx@@ -1,138 +1,97 @@----title: DingTalk Bot integration-description: Connect a Multica agent to your own DingTalk app — create a Stream-mode robot in the DingTalk Open Platform, copy its AppKey + AppSecret, paste them into Multica, then DM it, @-mention it in a group, or type /issue from inside DingTalk.+title: DingTalk Bot+description: Connect an agent to DingTalk and give it work directly in DMs or group chats.---import { Callout } from "fumadocs-ui/components/callout";-Connect any [agent](/agents) to a DingTalk bot and your team can work with it from inside DingTalk — DM the bot, @-mention it in a group, send it screenshots, or type `/issue` to file a [Multica issue](/issues) without opening the app.+After connecting an [agent](/agents) to DingTalk, members of the agent's workspace can DM the Bot, @-mention it in a group, or use the `/issue` command to create a Multica [issue](/issues) directly. Conversations and run records are saved to the Multica workspace.-DingTalk support is [community-maintained](/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).+<Callout type="info">+The DingTalk integration is [community-maintained](/community-maintained) and has no official support SLA. Report problems in [GitHub issues](https://github.com/multica-ai/multica/issues).+</Callout>-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:+## Connect the Bot-- an **AppKey** — the app's client id-- an **AppSecret** — the app's client secret+The agent's creator or a workspace owner/admin can connect the agent to DingTalk. Agents and DingTalk Bots have a one-to-one connection.-## Set up your DingTalk app+## 1. Create a Stream-mode robot-### 1. Create the app and add a Stream-mode robot+1. Create an **enterprise internal app** in the [DingTalk Open Platform](https://open-dev.dingtalk.com).+2. Enable the robot capability and set **Message Receiving Mode** to **Stream Mode**.-1. Go to the [DingTalk Open Platform](https://open-dev.dingtalk.com) and create an **enterprise internal app** (企业内部应用).-2. Open the app and add the **robot** (机器人) capability.-3. In the robot settings, set the **message-receiving mode** to **Stream mode** (Stream 模式 / 推送模式). This is what lets the bot connect out over a long-lived push connection instead of receiving a webhook.+## 2. Grant permissions to the robot-This is everything Multica needs at the platform level — it connects out over Stream mode, so you don't configure any public address:+The **Robot Message Sending** permission (`qyapi_robot_sendmsg`) is added by default. To show the Bot's name in Multica, manually add the **DingTalk Group Basic Information Management** permission (`qyapi_chat_manage`).-| Setting | Why it's there |-|---|---|-| **Enterprise internal app** | The app container that owns the robot and issues the AppKey / AppSecret credentials. |-| **Robot capability** | Creates the bot identity that gets @-mentioned and posts replies. |-| **Stream mode** | The bot connects out over a long-lived Stream connection — **no public webhook / URL needed**. |-| **Robot send permission** | Lets the bot send messages back into DingTalk (the agent's replies and proactive messages). |-| **Message-read scopes** | So the bot receives 1:1 messages and the group messages that @-mention it. |+## 3. Get the application credentials-There is **no webhook URL and no OAuth redirect URL**, because the robot runs over Stream mode and BYO doesn't use OAuth.+Open **Credentials & Basic Information** page and copy the **Client ID (AppKey)** and **Client Secret (AppSecret)**.-<Callout type="info">-DingTalk has no native typing / reaction indicator, so — unlike Slack — the bot instead posts a short "working on it" acknowledgement when it starts, and the full reply follows once the agent is done. A quick burst of messages is coalesced into a single acknowledgement.-</Callout>+## 4. Connect the agent to DingTalk-### 2. Grant the robot its permissions--Grant the robot the scopes it needs so it can **receive messages** and **send messages back** (the robot message-send permission). Without the send permission the agent can run but its reply can't be delivered.--### 3. Copy the AppKey and AppSecret+1. Return to Multica and open **Agents → _your agent_ → Capabilities → Integrations**.+2. Click **Connect DingTalk**.+3. Enter the **AppKey** and **AppSecret**, then submit.-Open the app's **凭证与基础信息** (Credentials & Basic Information) and copy:+## 5. Link your DingTalk and Multica accounts-- the **AppKey** — this is your app's **client id**-- the **AppSecret** — this is your app's **client secret**+DM the Bot in DingTalk or @-mention it in a group to trigger a linking request. You will receive a link in your DM with the Bot; it is valid for about 15 minutes. Open the link. When the success message appears, account linking is complete.-### 4. Connect it in Multica-1. Open the agent in **Agents → _your agent_** → the **Integrations** tab (or the **Integrations** section in the left sidebar).-2. Click **Connect DingTalk**.-3. Paste the **AppKey** and the **AppSecret**, then click **Connect**.-4. The agent shows **Connected to DingTalk**. The bot is now listening over its own Stream connection.+## Give the agent work in DingTalk-<Callout type="warning">-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>+### Direct messages-<Callout type="info">-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>+Send the Bot a message. When the agent finishes the work, it replies with the result in the DM.-## What the integration does+### Group chats-| Surface | Behavior |-|---|---|-| **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. 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. |-| **Reply** | The agent's answer is posted back into the same 1:1 chat or group. |+Add the Bot to a DingTalk group, then send `@your-bot <message>`. You must @-mention the Bot again in every follow-up. The Bot processes only messages that @-mention it.-## Use the bot (members)+### Send images-### First message: link your account+Direct messages and group chats both support messages containing text and images. Supported image formats are PNG, JPEG, GIF, WebP, and BMP. Each message can contain up to 4 images, with a maximum size of 10 MB per image. Files and voice messages are not currently supported.-The first time you @-mention or DM the bot, it replies with a **link your account** prompt pointing at the in-product **/dingtalk/bind** page. Tap the link, sign in to Multica, and your DingTalk identity is bound to your Multica membership — this is what lets the agent act as you (e.g. `/issue` files under your name). The link is single-use and expires in about 15 minutes; just message the bot again for a fresh one.+### Create an issue with `/issue`-<Callout type="warning">-Only **members of the workspace** can use the bot. If you aren't a member, or you skip the identity link, the bot won't run — your message is dropped (recorded for audit, without its contents).-</Callout>+Send `/issue <title>` or `/issue <title>{newline}<detailed description>` to create a new Multica issue and automatically assign it to the agent connected to the Bot. Images in the same message are also added to the issue as attachments. Unlike regular chat messages, the `/issue` command leaves no record in Multica [Chat](/chat).-### Chat and commands+### Start over with `/new`-- **In a group** — add the bot to the group, then `@your-bot <your message>`. Re-mention it for each follow-up (the bot only reads messages that mention it).-- **In a 1:1 chat** — open the bot and message it directly; no mention needed, every message is read.-- **Send images** — send screenshots or photos, with or without text; they show up in the conversation for the agent to work with. PNG, JPEG, GIF, WebP, or BMP; up to 4 images per message, 10 MB each.-- **File an issue** — send `/issue the login redirect is broken on Safari`; add the description on following lines if needed. Multica creates the issue synchronously, attaches images from that message to it, and posts its ID and title back into the chat.-- **Start fresh** — send `/new <your message>` to run that message without prior context, or send `/new` by itself to apply the fresh start to your next non-empty message. A bare `/new` gets a confirmation, and its pending intent remains active until a later chat task is successfully queued. Neither form removes the existing conversation history.+Send `/new`, and the next message sent successfully will be processed by the agent in a fresh context. You can also send `/new <message>` to have the agent process that message immediately in a fresh context.-## Manage and disconnect+The `/new` command only makes the agent process messages in a fresh context. It does not create a new Multica Chat.-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.+## Manage connections-## Permissions+- On **Agents → _your agent_ → Capabilities → Integrations**, the agent's creator and workspace owners/admins can connect the agent to DingTalk or disconnect it. Once connected, this page shows the Bot's name, DingTalk groups where it has successfully processed messages, and its activity status data in those groups. Any workspace member with read access to the agent can see this information. Groups with no successfully processed messages in the last 90 days are placed under **Long inactive** and loaded when expanded.+- **Settings → Integrations** lists every DingTalk-connected agent in the current workspace that the viewer can read, along with the Bot's activity status data in DingTalk groups. Workspace owners/admins can also disconnect any listed agent from DingTalk. After disconnection, the Bot stops receiving messages, while the installation record is retained for audit. Workspace owners/admins can also forget a group. This removes the group from the list without deleting conversations or messages. The group reappears if a workspace member with a linked DingTalk account later @mentions the Bot there and Multica accepts the message.-- **Connect / disconnect** require workspace **owner** or **admin**.-- **Talking to the bot** requires being a workspace member with a linked DingTalk identity. Everyone else is dropped.-- Message bodies for dropped messages are never stored — only a drop reason, for audit.-## Self-host setup+## Self-hosting setup-On Multica Cloud the integration is already available — skip this section.+Multica Cloud users can skip this section. A self-hosted deployment must first set a key for encrypting the DingTalk `AppSecret`:-For self-host, DingTalk is **off until you set an at-rest encryption key**. The key encrypts each app's AppSecret before it reaches the database; the AppKey remains the installation's non-secret routing identifier. BYO needs **no** OAuth client id/secret at the deployment level — each installation uses the credentials the admin pastes.+```dotenv+MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>+```-1. Generate a 32-byte key and set it on the API server:+Generate one with:- ```dotenv- MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>- ```+```bash+openssl rand -base64 32+```- For example: `openssl rand -base64 32`.+Restart the API service, then connect DingTalk. Keep this key permanently: if it is changed or lost, existing tokens cannot be decrypted and the connection must be set up again.-2. Restart the API. Until the key is set, **Settings → Integrations** shows a "DingTalk integration not enabled" notice and the **Connect DingTalk** entry points stay hidden.+Account-linking URLs use `MULTICA_APP_URL`, falling back to `FRONTEND_ORIGIN` when it is unset. The URL must point to a Multica address that members can access.-<Callout type="info">-The key must decode to exactly 32 bytes — `openssl rand -base64 32` does this. Treat it as a long-lived secret: rotating or losing it makes already-stored credentials undecryptable, forcing every bot to reconnect. The "link your account" link is built from your web app URL (`MULTICA_APP_URL`, falling back to `FRONTEND_ORIGIN`) — a normal deployment already sets this, so there's nothing extra to configure.-</Callout>## Next-- [Chat integrations](/channels) — how the channel engine, sessions, and authorization work+- [Chat integrations](/channels) — how the Channel engine, sessions, and authorization work- [Agents](/agents) · [Chat](/chat) · [Issues](/issues)-- [Environment variables](/environment-variables) — full self-host configuration reference+- [Environment variables](/environment-variables) — complete self-hosting configuration referencediff --git a/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx b/apps/docs/content/docs/dingtalk-bot-integration.zh.mdxindex 6794270f72..65d21a2f52 100644--- a/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx+++ b/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx@@ -1,138 +1,97 @@----title: 钉钉 Bot 接入-description: 把 Multica 智能体接入你自己的钉钉 app——在钉钉开放平台创建一个 Stream 模式的机器人、复制它的 AppKey 与 AppSecret、粘贴进 Multica,然后就能在钉钉里私聊它、在群里 @ 它,或输入 /issue。+title: 钉钉 Bot+description: 把智能体接入钉钉,在私聊或群聊中直接交代工作。---import { Callout } from "fumadocs-ui/components/callout";-把任意[智能体](/agents)接入一个钉钉 Bot,团队就能在钉钉里直接使用它——私聊 Bot、在群里 @ 它、发截图给它,或者输入 `/issue` 直接创建一个 [Multica issue](/issues),不用打开应用。+把[智能体](/agents)接入钉钉后,智能体所在工作区的成员可以私聊 Bot、在群里 @ Bot,或用 `/issue` 指令直接创建 Multica [任务](/issues)。对话和执行记录会保存到 Multica 工作区。-钉钉集成[由社区维护](/community-maintained):每个版本都会随包发布,但不附带官方支持 SLA。遇到问题请提到 [GitHub issues](https://github.com/multica-ai/multica/issues)。--钉钉走的是**自带应用(bring-your-own-app,BYO)**模式:工作区管理员创建一个钉钉 app,给它加一个 Stream 模式的机器人,再把凭证粘贴进 Multica。设置时选择的智能体是机器人的默认智能体,负责私聊和刚发现的群聊。同一个机器人可以加入多个群,每个群之后都能分别路由到不同智能体。(这一点和 [Lark](/lark-bot-integration) 不同,Lark 的绑定是扫码安装流程。)--整个设置流程在下面,大约五分钟。最后你会得到两个凭证粘贴进 Multica:+<Callout type="info">+钉钉集成[由社区维护](/community-maintained),不提供官方支持 SLA。遇到问题请提交到 [GitHub issues](https://github.com/multica-ai/multica/issues)。+</Callout>-- 一个 **AppKey** —— app 的 client id-- 一个 **AppSecret** —— app 的 client secret-## 设置你的钉钉 app+## 连接 Bot-### 1. 创建 app 并添加一个 Stream 模式的机器人+智能体创建者或工作区 owner/admin 可以将智能体接入钉钉,智能体跟钉钉 Bot 是 1:1 的连接关系。-1. 打开[钉钉开放平台](https://open-dev.dingtalk.com),创建一个**企业内部应用**。-2. 进入该应用,添加**机器人**能力。-3. 在机器人设置里,把**消息接收模式**设为 **Stream 模式**(推送模式)。正是这一项让 Bot 通过一条长连接向外推送接收消息,而不是去接收一个 webhook。+## 1. 创建 Stream 模式机器人-这就是 Multica 在平台层所需的一切——它通过 Stream 模式向外连接,所以你不用配置任何公网地址:+1. 在[钉钉开放平台](https://open-dev.dingtalk.com)创建一个**企业内部应用**。+2. 开启机器人能力,其中**消息接收模式**设为 **Stream 模式**。-| 配置项 | 为什么需要它 |-|---|---|-| **企业内部应用** | 承载机器人、并签发 AppKey / AppSecret 凭证的那个 app 容器。 |-| **机器人能力** | 创建被 @ 和发回复用的那个 Bot 身份。 |-| **Stream 模式** | Bot 通过一条长连接的 Stream 向外连接——**无需任何公网 webhook / URL**。 |-| **机器人发送权限** | 让 Bot 能把消息发回钉钉(智能体的回复以及主动消息)。 |-| **消息读取权限** | 让 Bot 能接收单聊消息,以及群里 @ 了它的消息。 |+## 2. 给机器人授权-这里**既没有 webhook URL,也没有 OAuth 重定向 URL**,因为机器人跑在 Stream 模式上,而 BYO 不使用 OAuth。+默认已添加“机器人发消息权限”(`qyapi_robot_sendmsg`)。如需在 Multica 平台显示 Bot 名称,需手动添加“钉群基础信息管理权限”(`qyapi_chat_manage`)。-<Callout type="info">-钉钉没有原生的「正在输入」/ 表情回应指示器,所以——和 Slack 不同——Bot 会在开始处理时先回一条简短的「正在处理」提示,完整回复在智能体处理完后送达。短时间内连发的多条消息会合并为一条提示。-</Callout>+## 3. 获取应用凭证-### 2. 给机器人授权+进入**凭证与基础信息**页面,复制 **Client ID(AppKey)** 和 **Client Secret(AppSecret)**。-给机器人授予它需要的权限,让它既能**接收消息**又能**把消息发回去**(机器人消息发送权限)。没有发送权限,智能体能跑,但它的回复发不出来。+## 4. 把智能体接入钉钉-### 3. 复制 AppKey 和 AppSecret+1. 回到 Multica,打开 **智能体 → _你的智能体_ → 能力 → 集成**。+2. 点击**连接钉钉**。+3. 填入 **AppKey** 和 **AppSecret** 后提交。-打开该应用的 **凭证与基础信息**,复制:+## 5. 关联钉钉账号与 Multica 平台账号-- **AppKey** —— 这就是你 app 的 **client id**-- **AppSecret** —— 这就是你 app 的 **client secret**+在钉钉上跟 Bot 私聊,或者在群里 @ Bot,触发一次关联请求,你会在 Bot 私聊对话框中收到一个链接(有效期约 15 分钟),点击链接后看到连接成功的提示即大功告成。-### 4. 在 Multica 里连接它-1. 在 **Agents → _你的智能体_** 打开该智能体 → **Integrations** tab(或左侧栏的 **Integrations** 区块)。-2. 点击 **Connect DingTalk**。-3. 粘贴 **AppKey** 和 **AppSecret**,然后点击 **Connect**。-4. 智能体显示 **Connected to DingTalk**。Bot 现在通过它自己的 Stream 连接在监听了。+## 在钉钉中给智能体交代工作-<Callout type="warning">-这两个凭证必须来自**同一个**钉钉 app,而且该 app 在一个 Multica 工作区中只安装一次。尝试把它作为第二个安装或连接到其他工作区会被拒绝。安装时选择的智能体仍负责私聊;群路由可直接指向其他智能体,无需重新连接 app。-</Callout>+### 私聊-<Callout type="info">-想让一个机器人服务**多个智能体**?把它加入各个钉钉群,在每个群里 @ 一次让 Multica 自动发现,然后到 **Settings → Integrations → DingTalk → 群路由** 为每个群选择智能体。只有需要不同机器人身份或不同私聊智能体时,才需要安装多个钉钉 app。-</Callout>+直接给 Bot 发消息即可。智能体处理完任务后,会将结果回复至私聊对话框中。-## 这个集成能做什么+### 群聊-| 入口 | 行为 |-|---|---|-| **智能体 → Integrations** | 所有者和管理员能看到 **Connect DingTalk**;连接后它会变成一个 **Connected to DingTalk** 徽标,并带一个 **Disconnect** 操作。 |-| **私聊 Bot** | 工作区成员在单聊里直接给 Bot 发消息。这段对话会成为该智能体的一个 Multica [chat](/chat) 会话;每一条消息都会被读取。 |-| **群里 @ 它** | 把 Bot 加进群再 @ 它。第一次 @ 会自动发现该群,并先使用机器人的默认智能体;所有者或管理员可在**群路由**中改成其他智能体。只有 @ 它的消息会被读取——Bot 不会监听整个群。 |-| **发图片** | 单聊里的图片、或群里随 @ 一起发的图片,都会进入对话让智能体看到——支持 PNG、JPEG、GIF、WebP、BMP,每条消息最多 4 张、每张不超过 10 MB。每张图片都会复制进 Multica 存储,所以钉钉的临时链接过期后,它在对话里依然可见。随 `/issue` 一起发送的图片会改为附到新建的 issue 上,而不是这条聊天消息。文件和语音不支持。 |-| **`/issue` 命令** | 以 `/issue <标题>` 开头,会按输入直接、同步地以你的身份创建 Multica 任务,并在原对话中返回任务编号和标题;后续行会作为描述。同一条钉钉消息中的图片会附到新建任务中。这条命令不会出现在 Multica Chat;新建任务是 Multica 中记录的处理结果。 |-| **`/new` 命令** | 以 `/new <你的消息>` 开头,会让这条消息在不带旧上下文的情况下运行。单独发送 `/new` 会把同样的 fresh 意图留给下一条非空消息,不会创建空 turn;已有对话记录保持不变。 |-| **回复** | 智能体的答复会被发回同一个单聊或群里。 |+把 Bot 加入钉群,再发送 `@your-bot <消息>`。每次追问都要重新 @,Bot 只处理 @ 它的消息。-## 使用 Bot(成员)+### 发送图片-### 第一条消息:绑定你的账号+私聊和群聊都支持图文混排消息,图片支持 PNG、JPEG、GIF、WebP 和 BMP;每条消息最多 4 张,每张不超过 10 MB。暂不支持文件和语音消息。-第一次 @ 或私聊 Bot 时,它会回一条 **绑定你的账号** 提示,指向产品内的 **/dingtalk/bind** 页面。点开链接、登录 Multica,你的钉钉身份就会绑定到你的 Multica 成员身份——正是这一步让智能体能以你的身份行事(比如 `/issue` 会把 issue 记在你名下)。这个链接是一次性的,大约 15 分钟后过期;再给 Bot 发条消息就能拿到一个新的。+### 使用 `/issue` 创建任务-<Callout type="warning">-只有**工作区成员**才能使用 Bot。如果你不是成员,或者跳过了身份绑定,Bot 不会运行——你的消息会被丢弃(仅出于审计目的记录,不保存消息内容)。-</Callout>+发送 `/issue <标题>` 或者 `/issue <标题>{换行}<详细描述>`,就可以创建一个新 Multica 任务,并自动指派给 Bot 连接着的智能体。同一条消息内的图片也会以附件的形式添加到该任务中。跟普通对话消息不一样的是,`/issue` 指令不会在 Multica 的“[对话](/chat)”中留下记录。-### 对话与命令+### 使用 `/new` 重新开始-- **在群里** —— 把 Bot 加进群,然后 `@your-bot <你的消息>`。每次追问都要重新 @ 它一下(Bot 只读取 @ 了它的消息)。-- **在单聊里** —— 打开 Bot 并直接给它发消息;不用 @,每一条消息都会被读取。-- **发图片** —— 直接发截图或照片,带不带文字都行;它们会进入对话,供智能体查看。支持 PNG、JPEG、GIF、WebP、BMP;每条消息最多 4 张,每张不超过 10 MB。-- **创建 issue** —— 发送 `/issue Safari 上登录跳转坏了`,需要时可在后续行补充描述。Multica 会同步创建 issue,将同一条消息中的图片附到该 issue,并在聊天中返回编号和标题。-- **重新开始** —— 发送 `/new <你的消息>`,让这条消息不带旧上下文运行;也可以单独发送 `/new`,把 fresh 意图应用到下一条非空消息。两种方式都不会删除已有对话记录。+发送 `/new`,再下一条成功发送的消息就会让智能体在全新的上下文中处理;也可以发送 `/new <消息>`,智能体会直接在全新的上下文中处理这条消息。-## 管理与断开+需要注意的是,`/new` 指令只是让智能体在全新的上下文中处理消息,并不会创建一个全新的 Multica “对话”。-工作区级别的管理在 **Settings → Integrations**:-- **Connected bots** 列出工作区里每个 Bot 以及它各自绑定的智能体(所有成员都能看到)。-- **群路由**列出 Bot 已发现的所有群。所有者和管理员可为每个群选择一个固定智能体;所有成员都能查看当前路由。-- 每次更改路由都会为所选智能体创建一个新的 Chat 会话。将智能体 A → 智能体 B → 智能体 A 不会恢复 A 之前的会话。已分配的智能体归档后,路由会保留,但消息处理会暂停并提示不可用,直到该智能体恢复或群被重新分配。-- **Disconnect** 仅限 **所有者 / 管理员**。它会让 Bot 停止接收钉钉消息并拆掉它的连接;安装记录会保留以便审计,之后你可以重新连接。+## 管理连接-## 权限+- 在**智能体 → _你的智能体_ → 能力 → 集成**页面,智能体创建者、工作区 owner/admin 可以在此连接钉钉,或者断开连接。连接上钉钉后,这里会显示 Bot 名称和已成功处理过消息的钉群,以及 Bot 在钉群内的活跃状态数据,有智能体读权限的工作区成员都能看到这些信息。最近 90 天没有成功处理消息的群会归入**长期未活跃**,展开时再加载。+- 在**设置 → 集成**页面,显示当前工作区内所有有读权限且连接了钉钉的智能体列表,以及 Bot 在钉群内的活跃状态数据。工作区 owner/admin 还可以在此直接断开列表中任意智能体的钉钉连接。断开后 Bot 停止接收消息,安装记录仍会保留用于审计。工作区 owner/admin 还可以忘记某个群。忘记只会从列表中移除该群,不会删除对话和消息。如果已关联钉钉账号的工作区成员以后在该群再次 @ Bot,且 Multica 成功接收这条消息,群会重新出现。-- **连接 / 断开** 需要工作区**所有者**或**管理员**。-- **和 Bot 对话** 需要你是工作区成员且已绑定钉钉身份。其余的人一律被丢弃。-- 对于被丢弃的消息,绝不保存消息内容——只记录一个丢弃原因,用于审计。## 自部署配置-在 Multica Cloud 上这个集成已经可用——可跳过本节。+Multica Cloud 用户可跳过本节。自托管部署需要先设置一个用于加密钉钉 `AppSecret` 的密钥:-自部署时,**在你设置好静态加密密钥之前,钉钉是关闭的**。这个密钥会在每个 app 的 AppSecret 落库前对其加密;AppKey 作为非敏感的安装路由标识明文保存。BYO 在部署层面**不需要** OAuth client id/secret——每个安装用的都是管理员粘贴进来的那对凭证。+```dotenv+MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>+```-1. 生成一个 32 字节的密钥并设置到 API 服务器:+可以这样生成:- ```dotenv- MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>- ```+```bash+openssl rand -base64 32+```- 例如:`openssl rand -base64 32`。+重启 API 服务后,再连接钉钉。该密钥需要长期保存:更换或丢失后,已有 token 无法解密,需要重新连接。-2. 重启 API。在密钥设置好之前,**Settings → Integrations** 会显示一条「DingTalk integration not enabled」提示,**Connect DingTalk** 入口也会保持隐藏。+账号绑定链接使用 `MULTICA_APP_URL`,未设置时回退到 `FRONTEND_ORIGIN`;它需要指向成员可以访问的 Multica 地址。-<Callout type="info">-这个密钥必须正好解码出 32 字节——`openssl rand -base64 32` 就能做到。把它当成一个长期有效的密钥:轮换或丢失它会让已存储的凭证无法解密,迫使每个 Bot 重新连接。「绑定你的账号」链接是用你的 Web 应用地址(`MULTICA_APP_URL`,未设置时回退到 `FRONTEND_ORIGIN`)拼出来的——正常部署里这个值本来就有,不需要额外配置。-</Callout>-## 下一步+## 接下来-- [聊天集成](/channels) —— channel 引擎、会话与授权是怎么运作的-- [智能体](/agents) · [Chat](/chat) · [Issues](/issues)+- [聊天集成](/channels) —— Channel 引擎、会话与授权是怎么运作的+- [智能体](/agents) · [Chat](/chat) · [任务](/issues)- [环境变量](/environment-variables) —— 完整的自部署配置参考diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 44c6fdc453..d8a3ce2f9a 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -176,13 +176,12 @@ import type {ListSlackInstallationsResponse,RegisterSlackBYORequest,RedeemSlackBindingTokenResponse,- DingTalkGroupRoute,DingTalkInstallation,- ListDingTalkGroupRoutesResponse,ListDingTalkInstallationsResponse,+ ListDingTalkGroupsResponse,+ ListDingTalkGroupsParams,RegisterDingTalkBYORequest,RedeemDingTalkBindingTokenResponse,- UpdateDingTalkGroupRouteRequest,WecomInstallation,ListWecomInstallationsResponse,RegisterWecomBYORequest,@@ -322,14 +321,12 @@ import {WorkspaceSubscriptionSeatReconcileResultSchema,CreateWorkspaceSubscriptionPortalResponseSchema,DingTalkInstallationSchema,- DingTalkGroupRouteSchema,- ListDingTalkGroupRoutesResponseSchema,ListDingTalkInstallationsResponseSchema,+ ListDingTalkGroupsResponseSchema,RedeemDingTalkBindingTokenResponseSchema,EMPTY_DINGTALK_INSTALLATION,- EMPTY_DINGTALK_GROUP_ROUTE,- EMPTY_LIST_DINGTALK_GROUP_ROUTES_RESPONSE,EMPTY_LIST_DINGTALK_INSTALLATIONS_RESPONSE,+ EMPTY_LIST_DINGTALK_GROUPS_RESPONSE,EMPTY_REDEEM_DINGTALK_BINDING_TOKEN_RESPONSE,WecomInstallationSchema,ListWecomInstallationsResponseSchema,@@ -581,6 +578,16 @@ function workspaceHeader(return slug ? { "X-Workspace-Slug": slug } : undefined;}+function dingTalkGroupSearch(params: ListDingTalkGroupsParams): string {+ const search = new URLSearchParams();+ if (params.activity) search.set("activity", params.activity);+ if (params.installationId) search.set("installation_id", params.installationId);+ if (params.offset !== undefined) search.set("offset", String(params.offset));+ if (params.limit !== undefined) search.set("limit", String(params.limit));+ const encoded = search.toString();+ return encoded ? `?${encoded}` : "";+}+export class ApiClient {private baseUrl: string;private token: string | null = null;@@ -4200,36 +4207,74 @@ export class ApiClient {);}- async listDingTalkGroupRoutes(+ async listDingTalkGroups(workspaceId: string,- ): Promise<ListDingTalkGroupRoutesResponse> {- const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/dingtalk/group-routes`);+ params: ListDingTalkGroupsParams = {},+ ): Promise<ListDingTalkGroupsResponse> {+ let raw: unknown;+ try {+ const search = dingTalkGroupSearch(params);+ raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/dingtalk/groups${search}`);+ } catch (error) {+ // Installed clients can be newer than the server they reconnect to. A+ // backend predating group discovery 404s this additive endpoint. The+ // first admin-only version returns 403 to members; both mean this client+ // cannot use the workspace inventory, while real failures stay visible.+ if (+ error instanceof ApiError &&+ (error.status === 404 || error.status === 403)+ ) {+ return EMPTY_LIST_DINGTALK_GROUPS_RESPONSE;+ }+ throw error;+ }+ return parseWithFallback(+ raw,+ ListDingTalkGroupsResponseSchema,+ EMPTY_LIST_DINGTALK_GROUPS_RESPONSE,+ { endpoint: "GET /api/workspaces/:id/dingtalk/groups" },+ );+ }++ async listAgentDingTalkGroups(+ agentId: string,+ params: ListDingTalkGroupsParams = {},+ ): Promise<ListDingTalkGroupsResponse> {+ let raw: unknown;+ try {+ const search = dingTalkGroupSearch(params);+ raw = await this.fetch<unknown>(`/api/agents/${agentId}/dingtalk/groups${search}`);+ } catch (error) {+ // Keep installed clients compatible with servers that predate agent-+ // scoped group discovery. Authorization failures must remain visible.+ if (error instanceof ApiError && error.status === 404) {+ return EMPTY_LIST_DINGTALK_GROUPS_RESPONSE;+ }+ throw error;+ }return parseWithFallback(raw,- ListDingTalkGroupRoutesResponseSchema,- EMPTY_LIST_DINGTALK_GROUP_ROUTES_RESPONSE,- { endpoint: "GET /api/workspaces/:id/dingtalk/group-routes" },+ ListDingTalkGroupsResponseSchema,+ EMPTY_LIST_DINGTALK_GROUPS_RESPONSE,+ { endpoint: "GET /api/agents/:id/dingtalk/groups" },);}- async updateDingTalkGroupRoute(+ async forgetDingTalkGroup(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) },+ installationId: string,+ conversationId: string,+ ): Promise<void> {+ await this.fetch(+ `/api/workspaces/${workspaceId}/dingtalk/installations/${installationId}/groups/${encodeURIComponent(conversationId)}`,+ { method: "DELETE" },);- 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,- // returning the new installation.+ // registerDingTalkBYO performs a bring-your-own-app install: the agent owner+ // or a workspace owner/admin pastes the AppKey (client id) + AppSecret+ // (client secret) of the DingTalk Stream-mode robot they created, and the+ // backend validates + persists it, returning the new installation.async registerDingTalkBYO(workspaceId: string,agentId: string,diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex 52f5818672..cc833f7be1 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -382,31 +382,47 @@ 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();+ expect(res.installations[0]?.agent_available).toBeUndefined();});- it("parses the new-server group-routing capability", async () => {+ it("preserves the orphaned-Agent marker from a new server", async () => {stubFetchJson({- installations: [{- id: "dt-1",- status: "active",- bound_dingtalk_user_ids: ["staff-1001"],- }],+ installations: [+ { id: "dt-orphan", status: "active", agent_available: false },+ ],+ configured: true,+ });+ const client = new ApiClient("https://api.example.test");+ const res = await client.listDingTalkInstallations("ws-1");+ expect(res.installations[0]?.agent_available).toBe(false);+ });++ it("parses linked DingTalk identities from a new-server row", async () => {+ stubFetchJson({+ installations: [+ {+ id: "dt-1",+ status: "active",+ bound_dingtalk_user_ids: ["staff-1001"],+ },+ ],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);expect(res.installations[0]?.bound_dingtalk_user_ids).toEqual(["staff-1001"]);});- it("defaults missing or malformed linked-identity IDs to an empty list", async () => {+ it("defaults missing or malformed linked identities to an empty list", async () => {stubFetchJson({installations: [{ id: "dt-old", status: "active" },- { id: "dt-broken", status: "active", bound_dingtalk_user_ids: "staff-1001" },+ {+ id: "dt-broken",+ status: "active",+ bound_dingtalk_user_ids: "staff-1001",+ },],configured: true,});@@ -417,52 +433,6 @@ describe("ApiClient schema fallback", () => {});});- 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" }),- }),- );- });- });-describe("Telegram integration", () => {it("falls back to a safe empty installation list when the response is malformed", async () => {stubFetchJson({ installations: "not-an-array", configured: true });@@ -506,6 +476,143 @@ describe("ApiClient schema fallback", () => {});});+ describe("listDingTalkGroups", () => {+ it("preserves bot activity metadata for each group relationship", async () => {+ stubFetchJson({+ groups: [+ {+ conversation_id: "cid-platform",+ conversation_title: "Platform",+ bots: [+ {+ installation_id: "inst-1",+ agent_id: "agent-1",+ bot_name: "Release Bot",+ bot_identity_issue: "",+ last_active_at: "2026-08-19T08:00:00Z",+ mention_count: 18,+ },+ ],+ },+ ],+ group_discovery_supported: true,+ });+ const client = new ApiClient("https://api.example.test");+ const res = await client.listDingTalkGroups("ws-1");+ expect(res.groups[0]?.bots[0]).toMatchObject({+ last_active_at: "2026-08-19T08:00:00Z",+ mention_count: 18,+ });+ });++ it("uses an agent-scoped endpoint for Agent detail group visibility", async () => {+ stubFetchJson({ groups: [], group_discovery_supported: true });+ const client = new ApiClient("https://api.example.test");+ await client.listAgentDingTalkGroups("agent-1");+ expect(vi.mocked(fetch)).toHaveBeenCalledWith(+ "https://api.example.test/api/agents/agent-1/dingtalk/groups",+ expect.any(Object),+ );+ });++ it("requests one inactive installation page and can forget an observation", async () => {+ stubFetchJson({ groups: [], group_discovery_supported: true });+ const client = new ApiClient("https://api.example.test");+ await client.listDingTalkGroups("ws-1", {+ activity: "inactive",+ installationId: "inst-1",+ offset: 20,+ limit: 10,+ });+ expect(vi.mocked(fetch)).toHaveBeenLastCalledWith(+ "https://api.example.test/api/workspaces/ws-1/dingtalk/groups?activity=inactive&installation_id=inst-1&offset=20&limit=10",+ expect.any(Object),+ );++ vi.mocked(fetch).mockResolvedValueOnce(new Response(null, { status: 204 }));+ await client.forgetDingTalkGroup("ws-1", "inst-1", "cid/encoded");+ expect(vi.mocked(fetch)).toHaveBeenLastCalledWith(+ "https://api.example.test/api/workspaces/ws-1/dingtalk/installations/inst-1/groups/cid%2Fencoded",+ expect.objectContaining({ method: "DELETE" }),+ );+ });++ it("treats an older backend's missing endpoint as an empty group list", async () => {+ stubFetchJson({ error: "not found" }, 404);+ const client = new ApiClient("https://api.example.test");+ await expect(client.listDingTalkGroups("ws-1")).resolves.toEqual({+ groups: [],+ group_discovery_supported: false,+ });+ });++ it("treats an older backend's admin-only group inventory as unsupported for members", async () => {+ stubFetchJson({ error: "forbidden" }, 403);+ const client = new ApiClient("https://api.example.test");+ await expect(client.listDingTalkGroups("ws-1")).resolves.toEqual({+ groups: [],+ group_discovery_supported: false,+ });+ });++ it("does not hide a real group-list server failure", async () => {+ stubFetchJson({ error: "unavailable" }, 503);+ const client = new ApiClient("https://api.example.test");+ await expect(client.listDingTalkGroups("ws-1")).rejects.toMatchObject({+ status: 503,+ });+ });++ it("falls back to an empty group list when the response is malformed", async () => {+ stubFetchJson({ groups: "not-an-array" });+ const client = new ApiClient("https://api.example.test");+ await expect(client.listDingTalkGroups("ws-1")).resolves.toEqual({+ groups: [],+ group_discovery_supported: false,+ });+ });++ it("defaults additive bot identity fields and isolates a malformed bot list", async () => {+ stubFetchJson({+ groups: [+ {+ conversation_id: "cid-platform",+ conversation_title: "Platform",+ bots: [{ installation_id: "inst-1", agent_id: "agent-1" }],+ },+ {+ conversation_id: "cid-old-server",+ bots: "not-an-array",+ },+ ],+ group_discovery_supported: true,+ future_field: true,+ });+ const client = new ApiClient("https://api.example.test");+ const res = await client.listDingTalkGroups("ws-1");+ expect(res.group_discovery_supported).toBe(true);+ expect(res.groups).toEqual([+ {+ conversation_id: "cid-platform",+ conversation_title: "Platform",+ bots: [+ {+ installation_id: "inst-1",+ agent_id: "agent-1",+ bot_name: "",+ bot_identity_issue: "",+ },+ ],+ },+ {+ conversation_id: "cid-old-server",+ conversation_title: "",+ bots: [],+ },+ ]);+ });+ });+describe("getConfig", () => {it("drops malformed daemon setup URLs instead of throwing", async () => {stubFetchJson({diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex f987939c8a..5a36a52ea8 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -29,10 +29,9 @@ import type {WorkspaceSubscriptionSeatReconcileResult,CreateWorkspaceSubscriptionPortalResponse,CronPreviewResponse,- DingTalkGroupRoute,DingTalkInstallation,- ListDingTalkGroupRoutesResponse,ListDingTalkInstallationsResponse,+ ListDingTalkGroupsResponse,RedeemDingTalkBindingTokenResponse,WecomInstallation,ListWecomInstallationsResponse,@@ -2567,6 +2566,7 @@ export const DingTalkInstallationSchema = z.object({installed_at: z.string().default(""),created_at: z.string().default(""),updated_at: z.string().default(""),+ agent_available: z.boolean().optional(),bound_dingtalk_user_ids: z.array(z.string()).catch([]).default([]),}).loose();@@ -2586,7 +2586,6 @@ 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 = {@@ -2594,34 +2593,32 @@ export const EMPTY_LIST_DINGTALK_INSTALLATIONS_RESPONSE: ListDingTalkInstallatioconfigured: false,};-export const DingTalkGroupRouteSchema = z.object({- id: z.string(),- workspace_id: z.string().default(""),+export const DingTalkGroupBotSchema = z.object({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(""),+ bot_name: z.string().default(""),+ bot_identity_issue: z.string().default(""),+ last_active_at: z.string().optional(),+ mention_count: z.number().int().nonnegative().optional(),}).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 DingTalkGroupSchema = z.object({+ conversation_id: z.string(),+ conversation_title: z.string().default(""),+ bots: z.array(DingTalkGroupBotSchema).catch([]).default([]),+}).loose();-export const ListDingTalkGroupRoutesResponseSchema = z.object({- routes: z.array(DingTalkGroupRouteSchema).default([]),+export const ListDingTalkGroupsResponseSchema = z.object({+ groups: z.array(DingTalkGroupSchema).default([]),+ group_discovery_supported: z.boolean().default(false),+ inactive_group_counts: z.record(z.string(), z.number().int().nonnegative()).optional(),+ bot_identities: z.record(z.string(), DingTalkGroupBotSchema).optional(),+ next_offset: z.number().int().nonnegative().optional(),}).loose();-export const EMPTY_LIST_DINGTALK_GROUP_ROUTES_RESPONSE: ListDingTalkGroupRoutesResponse = {- routes: [],+export const EMPTY_LIST_DINGTALK_GROUPS_RESPONSE: ListDingTalkGroupsResponse = {+ groups: [],+ group_discovery_supported: false,};export const RedeemDingTalkBindingTokenResponseSchema = z.object({diff --git a/packages/core/dingtalk/index.ts b/packages/core/dingtalk/index.tsindex 834291a51f..b8d4ba079d 100644--- a/packages/core/dingtalk/index.ts+++ b/packages/core/dingtalk/index.ts@@ -1,5 +1,8 @@export {dingtalkKeys,dingtalkInstallationsOptions,- dingtalkGroupRoutesOptions,+ dingtalkGroupsOptions,+ dingtalkAgentGroupsOptions,+ dingtalkInactiveGroupsOptions,+ dingtalkAgentInactiveGroupsOptions,} from "./queries";diff --git a/packages/core/dingtalk/queries.test.ts b/packages/core/dingtalk/queries.test.tsnew file mode 100644index 0000000000..b8fbd61e0c--- /dev/null+++ b/packages/core/dingtalk/queries.test.ts@@ -0,0 +1,81 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";+import {+ dingtalkAgentGroupsOptions,+ dingtalkAgentInactiveGroupsOptions,+ dingtalkGroupsOptions,+ dingtalkInactiveGroupsOptions,+ dingtalkKeys,+} from "./queries";++describe("dingtalkGroupsOptions", () => {+ it("is workspace-scoped and polls only while discovery is healthy", () => {+ const options = dingtalkGroupsOptions("ws-1");+ expect(options.queryKey).toEqual(dingtalkKeys.groups("ws-1"));+ expect(options.enabled).toBe(true);+ const interval = options.refetchInterval;+ expect(typeof interval).toBe("function");+ if (typeof interval !== "function") return;+ expect(+ interval({+ state: {+ status: "success",+ data: { groups: [], group_discovery_supported: true },+ },+ } as never),+ ).toBe(5_000);+ expect(+ interval({+ state: {+ status: "success",+ data: { groups: [], group_discovery_supported: false },+ },+ } as never),+ ).toBe(false);+ expect(+ interval({+ state: {+ status: "success",+ data: { groups: [] },+ },+ } as never),+ ).toBe(false);+ expect(+ interval({+ state: {+ status: "success",+ data: { groups: [], group_discovery_supported: null },+ },+ } as never),+ ).toBe(false);+ expect(interval({ state: { status: "error" } } as never)).toBe(false);+ });++ it("stays disabled before workspace context is available", () => {+ expect(dingtalkGroupsOptions("").enabled).toBe(false);+ });++ it("separates each Agent detail cache from the admin workspace inventory", () => {+ const options = dingtalkAgentGroupsOptions("ws-1", "agent-1");+ expect(options.queryKey).toEqual(dingtalkKeys.agentGroups("ws-1", "agent-1"));+ expect(options.queryKey).not.toEqual(dingtalkKeys.groups("ws-1"));+ expect(options.enabled).toBe(true);+ expect(dingtalkAgentGroupsOptions("ws-1", "").enabled).toBe(false);+ });++ it("keeps inactive pages scoped to one installation", () => {+ const workspace = dingtalkInactiveGroupsOptions("ws-1", "inst-1");+ expect(workspace.queryKey).toEqual(+ dingtalkKeys.inactiveGroups("ws-1", "inst-1"),+ );+ expect(workspace.initialPageParam).toBe(0);+ expect(workspace.getNextPageParam?.({ next_offset: 20 } as never, [], 0, [])).toBe(20);++ const agent = dingtalkAgentInactiveGroupsOptions("ws-1", "agent-1", "inst-1");+ expect(agent.queryKey).toEqual(+ dingtalkKeys.agentInactiveGroups("ws-1", "agent-1", "inst-1"),+ );+ expect(dingtalkInactiveGroupsOptions("ws-1", "").enabled).toBe(false);+ });+});diff --git a/packages/core/dingtalk/queries.ts b/packages/core/dingtalk/queries.tsindex 62692e454a..fbc24b15d4 100644--- a/packages/core/dingtalk/queries.ts+++ b/packages/core/dingtalk/queries.ts@@ -1,4 +1,4 @@-import { queryOptions } from "@tanstack/react-query";+import { infiniteQueryOptions, queryOptions } from "@tanstack/react-query";import { api } from "../api";/** Query key namespace for everything DingTalk-installation-related. Realtime@@ -8,7 +8,13 @@ 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,+ groups: (wsId: string) => [...dingtalkKeys.all(wsId), "groups"] as const,+ agentGroups: (wsId: string, agentId: string) =>+ [...dingtalkKeys.groups(wsId), "agent", agentId] as const,+ inactiveGroups: (wsId: string, installationId: string) =>+ [...dingtalkKeys.groups(wsId), "inactive", installationId] as const,+ agentInactiveGroups: (wsId: string, agentId: string, installationId: string) =>+ [...dingtalkKeys.agentGroups(wsId, agentId), "inactive", installationId] as const,};export const dingtalkInstallationsOptions = (wsId: string) =>@@ -18,14 +24,63 @@ export const dingtalkInstallationsOptions = (wsId: string) =>enabled: !!wsId,});-export const dingtalkGroupRoutesOptions = (wsId: string) =>+export const dingtalkGroupsOptions = (wsId: string) =>queryOptions({- queryKey: dingtalkKeys.groupRoutes(wsId),- queryFn: () => api.listDingTalkGroupRoutes(wsId),+ queryKey: dingtalkKeys.groups(wsId),+ queryFn: () => api.listDingTalkGroups(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),+ // Group discovery arrives through DingTalk Stream callbacks rather than an+ // HTTP mutation, so refresh lightly while the permission-filtered Settings+ // inventory is open. Stop after an error instead of hammering a backend.+ refetchInterval: (query) =>+ query.state.status === "success" &&+ query.state.data?.group_discovery_supported === true+ ? 5_000+ : false,+ });++export const dingtalkAgentGroupsOptions = (wsId: string, agentId: string) =>+ queryOptions({+ queryKey: dingtalkKeys.agentGroups(wsId, agentId),+ queryFn: () => api.listAgentDingTalkGroups(agentId),+ enabled: !!wsId && !!agentId,+ // Agent detail uses a separate cache and a permission-scoped endpoint; it+ // must never borrow the admin workspace inventory and filter it client-side.+ refetchInterval: (query) =>+ query.state.status === "success" &&+ query.state.data?.group_discovery_supported === true+ ? 5_000+ : false,+ });++export const dingtalkInactiveGroupsOptions = (wsId: string, installationId: string) =>+ infiniteQueryOptions({+ queryKey: dingtalkKeys.inactiveGroups(wsId, installationId),+ initialPageParam: 0,+ queryFn: ({ pageParam }) =>+ api.listDingTalkGroups(wsId, {+ activity: "inactive",+ installationId,+ offset: pageParam,+ }),+ getNextPageParam: (page) => page.next_offset,+ enabled: !!wsId && !!installationId,+ });++export const dingtalkAgentInactiveGroupsOptions = (+ wsId: string,+ agentId: string,+ installationId: string,+) =>+ infiniteQueryOptions({+ queryKey: dingtalkKeys.agentInactiveGroups(wsId, agentId, installationId),+ initialPageParam: 0,+ queryFn: ({ pageParam }) =>+ api.listAgentDingTalkGroups(agentId, {+ activity: "inactive",+ installationId,+ offset: pageParam,+ }),+ getNextPageParam: (page) => page.next_offset,+ enabled: !!wsId && !!agentId && !!installationId,});diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex 952b95a069..f27f91d102 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -11,7 +11,6 @@ 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 { issueStatusKeys } from "../issue-statuses/queries";import {markWorkspaceDeletePending,@@ -240,7 +239,6 @@ describe("useRealtimeSync — ws instance change", () => {queryKey: issueKeys.attachments("issue-1"),});});-it("refetches the status catalog after an admin changes it elsewhere", async () => {const ws = createMockWs();renderHook(() => useRealtimeSync(ws, stores), {@@ -265,7 +263,7 @@ describe("useRealtimeSync — ws instance change", () => {});});- it("invalidates DingTalk group routes after a route update event", async () => {+ it("ignores removed DingTalk group-route events", () => {const ws = createMockWs();renderHook(() => useRealtimeSync(ws, stores), {wrapper: createWrapper(qc),@@ -274,11 +272,8 @@ describe("useRealtimeSync — ws instance change", () => {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"),- });+ expect(invalidateSpy).not.toHaveBeenCalled();});});diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex dd0fa8dacf..7d53e99b81 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -863,10 +863,6 @@ 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.tsindex d247067ba6..d46a3f053b 100644--- a/packages/core/types/dingtalk.ts+++ b/packages/core/types/dingtalk.ts@@ -1,5 +1,4 @@-/** A DingTalk robot installation with one default Multica agent. Group routes- * may target other agents without duplicating the installation.+/** A DingTalk robot installation bound to a single Multica agent.** Wire shape mirrors `DingTalkInstallationResponse` in* `server/internal/handler/dingtalk.go`. New fields the backend adds in the@@ -14,6 +13,9 @@ export interface DingTalkInstallation {installed_at: string;created_at: string;updated_at: string;+ /** False only when a workspace admin is viewing an orphaned installation+ * whose Agent no longer exists. Optional for older backends. */+ agent_available?: boolean;/** DingTalk staff ids linked by the currently authenticated Multica user for* this bot. Member-scoped so the member-visible installation endpoint does* not disclose other members' DingTalk identities. */@@ -32,38 +34,57 @@ 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;+/** One connected Multica bot observed in a DingTalk group. */+export interface DingTalkGroupBot {installation_id: string;+ agent_id: string;+ /** Readable DingTalk bot name. Empty on older backends, transient lookup+ * failures, or until the app is granted qyapi_chat_manage. */+ bot_name: string;+ /** Machine-readable reason the readable identity is unavailable. */+ bot_identity_issue: string;+ /** Latest accepted @mention from this group, in RFC 3339. Optional for+ * compatibility with older backends; empty when no durable message remains. */+ last_active_at?: string;+ /** Number of deduplicated group messages accepted for this bot. */+ mention_count?: number;+}++/** A DingTalk group observed after a validated @bot callback. */+export interface DingTalkGroup {conversation_id: string;conversation_title: string;- agent_id: string;- discovered_at: string;- updated_at: string;+ bots: DingTalkGroupBot[];}-export interface ListDingTalkGroupRoutesResponse {- routes: DingTalkGroupRoute[];+export interface ListDingTalkGroupsResponse {+ groups: DingTalkGroup[];+ /** False when an installed client is connected to a backend that predates+ * group discovery. Callers use it to avoid polling an absent endpoint. */+ group_discovery_supported: boolean;+ /** Historical observations outside the 90-day active window, keyed by bot+ * installation. Additive for compatibility with older servers. */+ inactive_group_counts?: Record<string, number>;+ /** App-wide identity keyed by installation, available even when every group+ * for that bot is outside the active window. */+ bot_identities?: Record<string, DingTalkGroupBot>;+ /** Offset for the next inactive page. Absent when the page is complete. */+ next_offset?: number;}-export interface UpdateDingTalkGroupRouteRequest {- agent_id: string;+export interface ListDingTalkGroupsParams {+ activity?: "inactive";+ installationId?: string;+ offset?: number;+ limit?: number;}/** Request body for a bring-your-own-app (BYO) install: the AppKey and- * AppSecret the admin pastes from the DingTalk Stream-mode robot they created.- * The backend validates both before persisting, then returns the created- * DingTalkInstallation. */+ * AppSecret an agent owner or workspace admin pastes from the DingTalk+ * Stream-mode robot they created. The backend validates both before persisting,+ * then returns the created DingTalkInstallation. */export interface RegisterDingTalkBYORequest {client_id: string;client_secret: string;diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex f2686688eb..6897551ce7 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -220,12 +220,13 @@ export type {} from "./slack";export type {DingTalkInstallation,- DingTalkGroupRoute,ListDingTalkInstallationsResponse,- ListDingTalkGroupRoutesResponse,+ DingTalkGroupBot,+ DingTalkGroup,+ ListDingTalkGroupsResponse,+ ListDingTalkGroupsParams,RegisterDingTalkBYORequest,RedeemDingTalkBindingTokenResponse,- UpdateDingTalkGroupRouteRequest,} from "./dingtalk";export type {WecomInstallation,diff --git a/packages/views/agents/components/tabs/integrations-tab.test.tsx b/packages/views/agents/components/tabs/integrations-tab.test.tsxindex d2db766bfc..59d2329bab 100644--- a/packages/views/agents/components/tabs/integrations-tab.test.tsx+++ b/packages/views/agents/components/tabs/integrations-tab.test.tsx@@ -3,6 +3,7 @@import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import type { ReactNode } from "react";import { cleanup, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";import type { Agent } from "@multica/core/types";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../../../locales/en/common.json";@@ -14,7 +15,7 @@ import enSettings from "../../../locales/en/settings.json";// is the shared LarkAgentBindButton, exhaustively covered in// lark-tab.test.tsx — here we stub it to a marker so the tests assert the// branch selection, not the install flow.-type MemberRole = "owner" | "admin" | "member" | "guest";+type MemberRole = "owner" | "admin" | "member";const membersRef = vi.hoisted(() => ({current: [{ user_id: "user-1", role: "owner" as MemberRole }],@@ -26,16 +27,34 @@ const installationsRef = vi.hoisted(() => ({install_supported: true,},}));+const groupsRef = vi.hoisted(() => ({+ current: {+ data: { groups: [] as unknown[], group_discovery_supported: true },+ isLoading: false,+ isError: false,+ refetch: vi.fn(),+ },+}));vi.mock("@tanstack/react-query", () => ({useQuery: (opts: { queryKey: unknown[]; enabled?: boolean }) => {if (opts.enabled === false) return { data: undefined };const key = JSON.stringify(opts.queryKey);if (key.includes("members")) return { data: membersRef.current };+ if (key.includes("groups")) return groupsRef.current;if (key.includes("installations")) return { data: installationsRef.current };return { data: undefined };},useQueryClient: () => ({ invalidateQueries: vi.fn() }),+ useInfiniteQuery: () => ({+ data: undefined,+ isLoading: false,+ isError: false,+ refetch: vi.fn(),+ hasNextPage: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ }),queryOptions: <T,>(opts: T) => opts,}));@@ -75,6 +94,34 @@ vi.mock("@multica/core/telegram", () => ({}),}));+vi.mock("@multica/core/dingtalk", () => ({+ dingtalkInstallationsOptions: () => ({+ queryKey: ["dingtalk", "installations"],+ queryFn: vi.fn(),+ }),+ dingtalkAgentGroupsOptions: (_wsId: string, agentId: string) => ({+ queryKey: ["dingtalk", "groups", "agent", agentId],+ queryFn: vi.fn(),+ }),+ dingtalkKeys: {+ groups: (wsId: string) => ["dingtalk", "groups", wsId],+ inactiveGroups: (wsId: string, installationId: string) =>+ ["dingtalk", "groups", wsId, "inactive", installationId],+ agentInactiveGroups: (wsId: string, agentId: string, installationId: string) =>+ ["dingtalk", "groups", wsId, "agent", agentId, "inactive", installationId],+ },+}));++vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({ getAgentName: (id: string) => `Agent ${id}` }),+}));++vi.mock("../../../common/actor-avatar", () => ({+ ActorAvatar: ({ actorId }: { actorId: string }) => (+ <span data-testid="actor-avatar" data-actor-id={actorId} />+ ),+}));+vi.mock("@multica/core/auth", () => {const useAuthStore = Object.assign((sel?: (s: { user: { id: string } }) => unknown) =>@@ -128,7 +175,10 @@ const TEST_RESOURCES = {en: { common: enCommon, agents: enAgents, settings: enSettings },};-afterEach(cleanup);+afterEach(() => {+ cleanup();+ vi.useRealTimers();+});const agent: Agent = {id: "agent-1",@@ -171,11 +221,55 @@ function resetFixtures() {configured: true,install_supported: true,};+ groupsRef.current = {+ data: { groups: [], group_discovery_supported: true },+ isLoading: false,+ isError: false,+ refetch: vi.fn(),+ };}describe("IntegrationsTab", () => {beforeEach(resetFixtures);+ it.each([+ { role: "owner", ownsAgent: false, permissionMode: "private", canManage: true },+ { role: "owner", ownsAgent: true, permissionMode: "private", canManage: true },+ { role: "admin", ownsAgent: false, permissionMode: "private", canManage: true },+ { role: "admin", ownsAgent: true, permissionMode: "private", canManage: true },+ { role: "member", ownsAgent: false, permissionMode: "private", canManage: false },+ { role: "member", ownsAgent: true, permissionMode: "private", canManage: true },+ { role: "owner", ownsAgent: false, permissionMode: "public_to", canManage: true },+ { role: "owner", ownsAgent: true, permissionMode: "public_to", canManage: true },+ { role: "admin", ownsAgent: false, permissionMode: "public_to", canManage: true },+ { role: "admin", ownsAgent: true, permissionMode: "public_to", canManage: true },+ { role: "member", ownsAgent: false, permissionMode: "public_to", canManage: false },+ { role: "member", ownsAgent: true, permissionMode: "public_to", canManage: true },+ ] as const)(+ "keeps DingTalk management independent of Agent access mode: role=$role ownsAgent=$ownsAgent permissionMode=$permissionMode",+ ({ role, ownsAgent, permissionMode, canManage }) => {+ membersRef.current = [{ user_id: "user-1", role }];+ renderTab(+ <IntegrationsTab+ agent={{+ ...agent,+ owner_id: ownsAgent ? "user-1" : "user-2",+ permission_mode: permissionMode,+ visibility: permissionMode === "private" ? "private" : "workspace",+ }}+ />,+ );+ expect(screen.queryByTestId("dingtalk-agent-connect") !== null).toBe(canManage);+ },+ );++ it("does not expose Agent management when the owner is no longer a workspace member", () => {+ membersRef.current = [];+ renderTab(<IntegrationsTab agent={agent} />);+ expect(screen.queryByTestId("dingtalk-agent-connect")).toBeNull();+ expect(screen.queryByTestId("lark-bind-button")).toBeNull();+ });+it("renders the shared bind entries for an owner when configured and supported", () => {renderTab(<IntegrationsTab agent={agent} />);expect(screen.getByText("Lark")).toBeTruthy();@@ -193,6 +287,244 @@ describe("IntegrationsTab", () => {renderTab(<IntegrationsTab agent={agent} />);const section = screen.getByText("DingTalk").closest("section");expect(section?.querySelector('[data-testid="dingtalk-mark"].h-5.w-5')).toBeTruthy();+ expect(screen.getByText(enSettings.dingtalk.agent_page_description)).toBeTruthy();+ });++ it("shows only this Agent's 1:1 bot and its groups", () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-08-19T10:00:00Z"));+ installationsRef.current = {+ installations: [+ { id: "inst-1", agent_id: "agent-1", status: "active" },+ ],+ configured: true,+ install_supported: true,+ };+ groupsRef.current.data.groups = [+ {+ conversation_id: "cid-platform",+ conversation_title: "Platform team",+ bots: [+ {+ installation_id: "inst-1",+ agent_id: "agent-1",+ bot_name: "Release Bot",+ bot_identity_issue: "",+ last_active_at: "2026-08-19T08:00:00Z",+ mention_count: 18,+ },+ {+ installation_id: "inst-2",+ agent_id: "agent-2",+ bot_name: "Support Bot",+ bot_identity_issue: "",+ },+ ],+ },+ {+ conversation_id: "cid-unrelated",+ conversation_title: "Unrelated group",+ bots: [+ {+ installation_id: "inst-3",+ agent_id: "agent-3",+ bot_name: "Other Bot",+ bot_identity_issue: "",+ },+ ],+ },+ ];++ renderTab(<IntegrationsTab agent={agent} />);+ expect(screen.getByText("Platform team")).toBeTruthy();+ expect(screen.getByText("Release Bot")).toBeTruthy();+ const connectedLabel = screen.getByText("Connected bot:");+ expect(connectedLabel.parentElement?.parentElement?.classList).toContain(+ "text-caption",+ );+ const groupDescription = screen.getByText(+ enSettings.dingtalk.groups_description,+ );+ expect(groupDescription.classList).toContain("text-caption");+ expect(groupDescription.classList).not.toContain("text-micro");+ const groupName = screen.getByText("Platform team");+ expect(groupName.classList).toContain("min-w-0");+ expect(groupName.parentElement?.classList).toContain("flex-1");+ const conversationId = screen.getByLabelText(+ "DingTalk group conversation ID cid-platform",+ );+ expect(conversationId.textContent).toBe("cid-platform");+ expect(conversationId.classList).toContain("text-micro");+ expect(conversationId.classList).toContain("text-faint-foreground");+ expect(conversationId.classList).toContain("group-hover:text-muted-foreground");+ const activity = screen.getByTestId("dingtalk-group-activity");+ expect(activity.textContent).toBe("Last active 2h ago·18 mentions");+ expect(activity.classList).toContain("tabular-nums");+ expect(activity.classList).not.toContain("whitespace-nowrap");+ expect(conversationId.parentElement?.parentElement).toBe(+ groupName.parentElement?.parentElement,+ );+ expect(activity.parentElement).not.toBe(screen.getByText("Platform team").parentElement);+ expect(screen.queryByText("Support Bot")).toBeNull();+ expect(screen.queryByText("Unrelated group")).toBeNull();+ });++ it("keeps the member-visible group list available to a non-owner member", () => {+ membersRef.current = [{ user_id: "user-1", role: "member" }];+ installationsRef.current = {+ installations: [+ { id: "inst-1", agent_id: "agent-1", status: "active" },+ ],+ configured: true,+ install_supported: true,+ };+ groupsRef.current.data.groups = [+ {+ conversation_id: "cid-platform",+ conversation_title: "Platform team",+ bots: [+ {+ installation_id: "inst-1",+ agent_id: "agent-1",+ bot_name: "Release Bot",+ bot_identity_issue: "",+ },+ ],+ },+ ];++ renderTab(<IntegrationsTab agent={{ ...agent, owner_id: "user-2" }} />);+ expect(screen.getByText("Platform team")).toBeTruthy();+ expect(screen.getByText("Release Bot")).toBeTruthy();+ expect(screen.getByText("Connected bot:")).toBeTruthy();+ expect(screen.queryByText(/Connected to Agent/i)).toBeNull();+ expect(screen.queryByText("Lark")).toBeNull();+ });++ it("shows the latest permission remediation to an Agent owner even when a cached bot name remains", async () => {+ membersRef.current = [{ user_id: "user-1", role: "member" }];+ installationsRef.current = {+ installations: [+ { id: "inst-1", agent_id: "agent-1", status: "active" },+ ],+ configured: true,+ install_supported: true,+ };+ groupsRef.current.data.groups = [+ {+ conversation_id: "cid-named",+ conversation_title: "Release room",+ bots: [+ {+ installation_id: "inst-1",+ agent_id: "agent-1",+ bot_name: "Release Bot",+ bot_identity_issue: "",+ },+ ],+ },+ {+ conversation_id: "cid-unnamed",+ conversation_title: "",+ bots: [+ {+ installation_id: "inst-1",+ agent_id: "agent-1",+ bot_name: "",+ bot_identity_issue: "missing_qyapi_chat_manage",+ },+ ],+ },+ ];+ renderTab(<IntegrationsTab agent={agent} />);+ expect(screen.getByText("Untitled DingTalk group")).toBeTruthy();+ expect(screen.getByText("Release Bot")).toBeTruthy();+ const info = screen.getByRole("button", { name: /qyapi_chat_manage/ });+ await userEvent.click(info);+ const permissionCode = await screen.findByText("qyapi_chat_manage", {+ selector: "code",+ });+ expect(permissionCode.closest('[data-slot="tooltip-content"]')?.textContent).toContain(+ "grant this bot's app the qyapi_chat_manage permission, then @mention the bot again in a DingTalk group where it has been added.",+ );+ });++ it("hides permission remediation from a read-only Agent viewer", () => {+ membersRef.current = [{ user_id: "user-1", role: "member" }];+ installationsRef.current = {+ installations: [+ { id: "inst-1", agent_id: "agent-1", status: "active" },+ ],+ configured: true,+ install_supported: true,+ };+ groupsRef.current.data.groups = [+ {+ conversation_id: "cid-unnamed",+ conversation_title: "Visible group",+ bots: [+ {+ installation_id: "inst-1",+ agent_id: "agent-1",+ bot_name: "",+ bot_identity_issue: "missing_qyapi_chat_manage",+ },+ ],+ },+ ];++ renderTab(<IntegrationsTab agent={{ ...agent, owner_id: "user-2" }} />);+ expect(screen.getByText("Identity unavailable")).toBeTruthy();+ expect(screen.queryByRole("button", { name: /qyapi_chat_manage/ })).toBeNull();+ });++ it("renders group loading, empty, and retryable error states", async () => {+ installationsRef.current = {+ installations: [+ { id: "inst-1", agent_id: "agent-1", status: "active" },+ ],+ configured: true,+ install_supported: true,+ };+ groupsRef.current.isLoading = true;+ groupsRef.current.data = undefined as never;+ const loading = renderTab(<IntegrationsTab agent={agent} />);+ expect(screen.getByText("Loading groups…")).toBeTruthy();+ loading.unmount();++ groupsRef.current.isLoading = false;+ groupsRef.current.data = {+ groups: [],+ group_discovery_supported: true,+ };+ const empty = renderTab(<IntegrationsTab agent={agent} />);+ expect(screen.getByText("No group messages observed yet.")).toBeTruthy();+ empty.unmount();++ groupsRef.current.isError = true;+ groupsRef.current.data = undefined as never;+ renderTab(<IntegrationsTab agent={agent} />);+ await userEvent.click(screen.getByRole("button", { name: "Retry" }));+ expect(groupsRef.current.refetch).toHaveBeenCalledOnce();+ });++ it("renders discovery UI only when the backend explicitly supports it", () => {+ installationsRef.current = {+ installations: [+ { id: "inst-1", agent_id: "agent-1", status: "active" },+ ],+ configured: true,+ install_supported: true,+ };+ groupsRef.current.data = {+ groups: [],+ group_discovery_supported: false,+ };++ renderTab(<IntegrationsTab agent={agent} />);+ expect(screen.getByText("Connected bot:")).toBeTruthy();+ expect(screen.queryByText("Identity unavailable")).toBeNull();+ expect(screen.queryByTestId("dingtalk-bot-groups")).toBeNull();});it("shows the coming-soon notice when the install transport is not wired", () => {@@ -223,7 +555,7 @@ describe("IntegrationsTab", () => {membersRef.current = [{ user_id: "user-1", role: "member" }];renderTab(<IntegrationsTab agent={{ ...agent, owner_id: "user-2" }} />);expect(- screen.getAllByText(/Only workspace owners and admins can connect an agent/i).length,+ screen.getAllByText(/Only workspace owners and admins can manage this connection/i).length,).toBeGreaterThanOrEqual(1);expect(screen.queryByTestId("lark-bind-button")).toBeNull();expect(screen.queryByTestId("slack-bind-button")).toBeNull();@@ -231,24 +563,23 @@ describe("IntegrationsTab", () => {expect(screen.queryByTestId("telegram-bind-button")).toBeNull();});- it("lets a non-admin agent owner bind Lark but keeps Slack admin-only", () => {- // The agent's owner (user-1) is only a plain workspace member. Lark- // authorizes the agent owner (canManageAgent), so the Lark bind entry- // renders and receives owner_id; Slack, DingTalk, WeCom and Telegram routes stay- // admin-only, so each shows the read-only note instead of a CTA (MUL-4213).+ it("lets a non-admin agent owner bind Lark and DingTalk", () => {+ // The agent's owner (user-1) is only a plain workspace member. Lark and+ // DingTalk both authorize the target agent's owner through canManageAgent;+ // Slack, WeCom and Telegram remain workspace owner/admin-only.membersRef.current = [{ user_id: "user-1", role: "member" }];renderTab(<IntegrationsTab agent={agent} />);const larkButton = screen.getByTestId("lark-bind-button");expect(larkButton.getAttribute("data-agent-id")).toBe("agent-1");expect(larkButton.getAttribute("data-agent-owner-id")).toBe("user-1");+ expect(screen.getByTestId("dingtalk-agent-connect")).toBeTruthy();expect(screen.queryByTestId("slack-bind-button")).toBeNull();expect(screen.queryByTestId("wecom-bind-button")).toBeNull();expect(screen.queryByTestId("telegram-bind-button")).toBeNull();- // The Slack, DingTalk, WeCom and Telegram sections each fall back to the shared- // members note.+ // The Slack, WeCom and Telegram sections fall back to the shared members note.expect(- screen.getAllByText(/Only workspace owners and admins can connect an agent/i),- ).toHaveLength(4);+ screen.getAllByText(/Only workspace owners and admins can manage this connection/i),+ ).toHaveLength(3);});it("renders the bind entry (not coming-soon) when installs are unavailable but the agent is already bound", () => {diff --git a/packages/views/agents/components/tabs/integrations-tab.tsx b/packages/views/agents/components/tabs/integrations-tab.tsxindex 91f792c6bc..ed6e908e6c 100644--- a/packages/views/agents/components/tabs/integrations-tab.tsx+++ b/packages/views/agents/components/tabs/integrations-tab.tsx@@ -6,7 +6,10 @@ import { useAuthStore } from "@multica/core/auth";import { useWorkspaceId } from "@multica/core/hooks";import { larkInstallationsOptions } from "@multica/core/lark";import { slackInstallationsOptions } from "@multica/core/slack";-import { dingtalkInstallationsOptions } from "@multica/core/dingtalk";+import {+ dingtalkAgentGroupsOptions,+ dingtalkInstallationsOptions,+} from "@multica/core/dingtalk";import { wecomInstallationsOptions } from "@multica/core/wecom";import { telegramInstallationsOptions } from "@multica/core/telegram";import { memberListOptions } from "@multica/core/workspace/queries";@@ -14,7 +17,12 @@ import { LarkAgentBindButton } from "../../../settings/components/lark-tab";import { LarkMark } from "../../../settings/components/lark-mark";import { SlackAgentBindButton } from "../../../settings/components/slack-tab";import { SlackMark } from "../../../settings/components/slack-mark";-import { DingTalkAgentBindButton } from "../../../settings/components/dingtalk-tab";+import {+ DingTalkAgentBindButton,+ DingTalkBotGroups,+ DingTalkConnectionLabel,+ getDingTalkBotIdentity,+} from "../../../settings/components/dingtalk-tab";import { DingTalkMark } from "../../../settings/components/dingtalk-mark";import { WecomAgentBindButton } from "../../../settings/components/wecom-tab";import { WecomMark } from "../../../settings/components/wecom-mark";@@ -75,7 +83,10 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {const isWorkspaceAdmin =currentMember?.role === "owner" || currentMember?.role === "admin";const isAgentOwner =- !!user?.id && agent.owner_id != null && agent.owner_id === user.id;+ currentMember != null &&+ !!user?.id &&+ agent.owner_id != null &&+ agent.owner_id === user.id;// Lark bind/manage is authorized for the agent's owner OR a workspace// owner/admin (server/internal/handler/lark.go canManageAgent, MUL-4213).// Slack's install/revoke routes are still workspace owner/admin-only, so@@ -98,9 +109,33 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {) ?? false;const dingtalkConfigured = dingtalkListing?.configured === true;- // DingTalk BYO install/revoke are workspace owner/admin-only at the router,- // matching Slack rather than Lark's owner-or-admin rule.- const canManageDingtalk = isWorkspaceAdmin;+ const dingtalkInstallation = dingtalkListing?.installations.find(+ (inst) => inst.agent_id === agent.id && inst.status === "active",+ );+ const dingtalkHasActiveInstall = !!dingtalkInstallation;+ const {+ data: dingtalkGroupsListing,+ isLoading: dingtalkGroupsLoading,+ isError: dingtalkGroupsError,+ refetch: retryDingtalkGroups,+ } = useQuery({+ ...dingtalkAgentGroupsOptions(wsId, agent.id),+ enabled: !!wsId && dingtalkHasActiveInstall,+ });+ const dingtalkGroups = dingtalkGroupsListing?.groups ?? [];+ const dingtalkGroupDiscoverySupported =+ dingtalkGroupsListing?.group_discovery_supported === true;+ const showDingtalkGroupDiscovery =+ dingtalkGroupDiscoverySupported ||+ dingtalkGroupsLoading ||+ dingtalkGroupsError;+ const dingtalkBotIdentity = dingtalkInstallation+ ? dingtalkGroupsListing?.bot_identities?.[dingtalkInstallation.id] ??+ getDingTalkBotIdentity(dingtalkGroups, dingtalkInstallation.id)+ : undefined;+ // DingTalk uses the same per-agent management rule as Lark: the target+ // agent's owner or a workspace owner/admin may connect and disconnect it.+ const canManageDingtalk = isWorkspaceAdmin || isAgentOwner;const wecomConfigured = wecomListing?.configured === true;const wecomInstallSupported = wecomListing?.install_supported === true;@@ -116,10 +151,10 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {(inst) => inst.agent_id === agent.id && inst.status === "active",) ?? false;- // A member who can manage no platform (not a workspace admin and not this- // agent's owner) gets the read-only note instead of the sections.- // Members can still view connected bots in the (member-visible)- // Settings → Integrations listing.+ // Preserve the established Integrations management gate: a member who can+ // manage no platform gets the read-only note instead of install controls.+ // The agent-scoped DingTalk relationship remains visible because reaching+ // this Agent detail already passed the server's Agent view permission gate.if (!canManageLark &&!canManageSlack &&@@ -132,9 +167,51 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {<p className="text-caption text-muted-foreground">{t(($) => $.tab_body.integrations.intro)}</p>- <p className="text-caption text-muted-foreground">- {t(($) => $.tab_body.integrations.members_note)}- </p>+ {dingtalkInstallation ? (+ <section className="rounded-lg border">+ <div className="flex items-start gap-3 p-4">+ <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border bg-muted/40 text-muted-foreground">+ <DingTalkMark className="h-5 w-5" />+ </span>+ <div className="min-w-0 flex-1 space-y-1">+ <h3 className="text-body font-medium">+ {ts(($) => $.dingtalk.section_title)}+ </h3>+ <p className="text-caption leading-relaxed text-muted-foreground">+ {ts(($) => $.dingtalk.agent_page_description)}+ </p>+ </div>+ </div>+ <div className="border-t px-4 py-3">+ <DingTalkConnectionLabel+ botName={dingtalkBotIdentity?.bot_name ?? ""}+ botIdentityIssue={dingtalkBotIdentity?.bot_identity_issue ?? ""}+ showBotIdentity={+ dingtalkGroupDiscoverySupported && !dingtalkGroupsLoading+ }+ showPermissionHelp={false}+ />+ </div>+ {showDingtalkGroupDiscovery && (+ <div className="border-t px-4 pb-4">+ <DingTalkBotGroups+ workspaceId={wsId}+ agentId={agent.id}+ installationId={dingtalkInstallation.id}+ groups={dingtalkGroups}+ inactiveCount={dingtalkGroupsListing?.inactive_group_counts?.[dingtalkInstallation.id] ?? 0}+ isLoading={dingtalkGroupsLoading}+ isError={dingtalkGroupsError}+ onRetry={() => void retryDingtalkGroups()}+ />+ </div>+ )}+ </section>+ ) : (+ <p className="text-caption text-muted-foreground">+ {t(($) => $.tab_body.integrations.members_note)}+ </p>+ )}</div>);}@@ -240,26 +317,64 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {<div className="min-w-0 flex-1 space-y-1"><h3 className="text-body font-medium">{ts(($) => $.dingtalk.section_title)}</h3><p className="text-caption leading-relaxed text-muted-foreground">- {ts(($) => $.dingtalk.page_description)}+ {ts(($) => $.dingtalk.agent_page_description)}</p></div></div><div className="border-t px-4 py-3">{!canManageDingtalk ? (- // DingTalk install/revoke stay workspace owner/admin-only, so an- // agent owner who is not an admin only gets the read-only note- // here (unlike Lark above). Reuses the shared members note.- <p className="text-caption text-muted-foreground">- {t(($) => $.tab_body.integrations.members_note)}- </p>+ // Viewers who cannot manage this agent still see its connected+ // DingTalk identity and discovered groups as read-only details.+ dingtalkInstallation ? (+ <DingTalkConnectionLabel+ botName={dingtalkBotIdentity?.bot_name ?? ""}+ botIdentityIssue={dingtalkBotIdentity?.bot_identity_issue ?? ""}+ showBotIdentity={+ dingtalkGroupDiscoverySupported && !dingtalkGroupsLoading+ }+ showPermissionHelp={false}+ />+ ) : (+ <p className="text-caption text-muted-foreground">+ {t(($) => $.tab_body.integrations.members_note)}+ </p>+ )) : !dingtalkConfigured ? (<p className="text-caption text-muted-foreground">{ts(($) => $.dingtalk.not_enabled_title)}</p>) : (- <DingTalkAgentBindButton agentId={agent.id} agentName={agent.name} />+ <DingTalkAgentBindButton+ agentId={agent.id}+ agentName={agent.name}+ agentOwnerId={agent.owner_id}+ botName={+ dingtalkGroupsLoading || !dingtalkGroupDiscoverySupported+ ? undefined+ : (dingtalkBotIdentity?.bot_name ?? "")+ }+ botIdentityIssue={+ dingtalkGroupsLoading || !dingtalkGroupDiscoverySupported+ ? undefined+ : (dingtalkBotIdentity?.bot_identity_issue ?? "")+ }+ />)}</div>+ {dingtalkInstallation && showDingtalkGroupDiscovery && (+ <div className="border-t px-4 pb-4">+ <DingTalkBotGroups+ workspaceId={wsId}+ agentId={agent.id}+ installationId={dingtalkInstallation.id}+ groups={dingtalkGroups}+ inactiveCount={dingtalkGroupsListing?.inactive_group_counts?.[dingtalkInstallation.id] ?? 0}+ isLoading={dingtalkGroupsLoading}+ isError={dingtalkGroupsError}+ onRetry={() => void retryDingtalkGroups()}+ />+ </div>+ )}</section><section className="rounded-lg border">diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex b873201e9a..b0ae090257 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -671,7 +671,7 @@},"integrations": {"intro": "Connect this agent to external chat platforms so people can work with it where they already are.",- "members_note": "Only workspace owners and admins can connect an agent to an external chat platform. You can view connected bots in Settings → Integrations."+ "members_note": "Only workspace owners and admins can manage this connection. You can view connected bots in Settings → Integrations."},"activity": {"status": {diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 34ab61629e..ee2247a091 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -910,29 +910,40 @@},"dingtalk": {"section_title": "DingTalk",- "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",+ "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.",+ "agent_page_description": "Use a dedicated DingTalk bot to DM this Agent, @mention it in a group, or type /issue to create a Multica issue.",+ "groups_title": "Recent groups",+ "groups_description": "A group appears after a workspace member links their DingTalk account and @mentions this bot there. Groups active in the last 90 days are shown by default.",+ "groups_overview_description": "Each connection shows its Agent, DingTalk bot, and recently observed groups.",+ "groups_loading": "Loading groups…",+ "groups_empty": "No group messages observed yet.",+ "groups_no_recent": "No groups were active in the last 90 days.",+ "groups_inactive": "Long inactive ({{count}})",+ "groups_load_more": "Load more",+ "groups_error": "Could not load DingTalk groups.",+ "groups_retry": "Retry",+ "group_untitled": "Untitled DingTalk group",+ "groups_count": "{{count}}",+ "conversation_id_label": "DingTalk group conversation ID",+ "group_last_active": "Last active {{time}}",+ "group_mentions_one": "{{count}} mention",+ "group_mentions_other": "{{count}} mentions",+ "group_forget": "Forget",+ "group_forget_title": "Forget this group?",+ "group_forget_description": "This removes the group from Multica's inventory without deleting conversations or messages. It will reappear after someone @mentions the bot again.",+ "group_forget_cancel": "Cancel",+ "group_forget_confirm": "Forget group",+ "group_forget_success": "Group removed from the inventory",+ "group_forget_failed": "Could not remove the group",+ "bot_identity_unavailable": "Identity unavailable",+ "bot_permission_tooltip_prefix": "In DingTalk Open Platform, grant this bot's app the",+ "bot_permission_tooltip_suffix": "permission, then @mention the bot again in a DingTalk group where it has been added.","not_enabled_title": "DingTalk integration not enabled","not_enabled_description_prefix": "Set","not_enabled_description_suffix": "on the server to enable DingTalk robot installations.","not_enabled_self_host_hint": "Self-hosters: see the project README for details.",- "connected_bots": "Connected bots",+ "connections_title": "Connections",+ "deleted_agent": "Deleted Agent","loading": "Loading…","empty_title": "No bots connected yet","empty_description_prefix": "Open an Agent in this workspace and click",@@ -940,7 +951,7 @@"empty_description_suffix": "to install a robot for it.","revoked_badge": "revoked","installed_at_label": "Installed {{when}}",- "identity_label": "Linked DingTalk identity: {{identity}}",+ "identity_label": "Linked staff ID: {{identity}}","disconnect": "Disconnect","disconnecting": "Disconnecting…","disconnect_confirm_title": "Disconnect this DingTalk bot?",@@ -950,7 +961,7 @@"toast_disconnect_failed": "Disconnect failed","bind_button": "Connect DingTalk","bind_button_title": "Connect {{agent}} to a DingTalk bot",- "agent_bot_connected_label": "Connected to DingTalk",+ "agent_bot_connected_label": "Connected bot:","agent_bot_disconnect_tooltip": "Unbind this DingTalk bot from the Agent. The bot will stop receiving DingTalk messages.","byo_dialog_title": "Connect a DingTalk bot","byo_docs_link": "Step-by-step: connect your Multica agent to DingTalk",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex 5f220c98ef..6457a13f98 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -552,7 +552,7 @@},"integrations": {"intro": "このエージェントを外部のチャットプラットフォームに接続し、普段使っているツールから直接やり取りできるようにします。",- "members_note": "エージェントを外部チャットプラットフォームに接続できるのはワークスペースのオーナーと管理者のみです。接続済みの Bot は「設定 → 連携」で確認できます。"+ "members_note": "この接続を管理できるのはワークスペースのオーナーと管理者のみです。接続済みの Bot は「設定 → 連携」で確認できます。"},"activity": {"status": {diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex e5a15cab79..015ec0494c 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -909,29 +909,39 @@},"dingtalk": {"section_title": "DingTalk",- "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": "グループのエージェントを更新できませんでした",+ "page_description": "各 Multica エージェントを専用の DingTalk ロボットに接続します。メンバーはボットに DM したり、グループで @メンションしたり、/issue と入力して新しい Multica タスクを作成できます。",+ "agent_page_description": "専用の DingTalk ロボットを使って、このエージェントに DM を送ったり、グループで @メンションしたり、/issue から Multica タスクを作成したりできます。",+ "groups_title": "最近のグループ",+ "groups_description": "ワークスペースのメンバーが DingTalk アカウントを連携し、グループでこのボットを @メンションすると表示されます。通常は直近 90 日間に利用されたグループだけを表示します。",+ "groups_overview_description": "各接続に、エージェント、DingTalk ロボット、最近やり取りしたグループを表示します。",+ "groups_loading": "グループを読み込み中…",+ "groups_empty": "グループからのメッセージはまだありません。",+ "groups_no_recent": "直近 90 日間に利用されたグループはありません。",+ "groups_inactive": "長期間未使用({{count}})",+ "groups_load_more": "さらに読み込む",+ "groups_error": "DingTalk グループを読み込めませんでした。",+ "groups_retry": "再試行",+ "group_untitled": "名称未設定の DingTalk グループ",+ "groups_count": "{{count}}",+ "conversation_id_label": "DingTalk グループ会話 ID",+ "group_last_active": "最終アクティブ {{time}}",+ "group_mentions_other": "{{count}} 件のメンション",+ "group_forget": "一覧から削除",+ "group_forget_title": "このグループを一覧から削除しますか?",+ "group_forget_description": "Multica の一覧からのみ削除します。会話やメッセージは残り、ボットが再度 @メンションされると一覧に戻ります。",+ "group_forget_cancel": "キャンセル",+ "group_forget_confirm": "一覧から削除",+ "group_forget_success": "グループを一覧から削除しました",+ "group_forget_failed": "グループを一覧から削除できませんでした",+ "bot_identity_unavailable": "識別情報を取得できません",+ "bot_permission_tooltip_prefix": "DingTalk オープンプラットフォームで、このボットのアプリに",+ "bot_permission_tooltip_suffix": "権限を付与し、このボットが追加されている DingTalk グループでもう一度 @メンションしてください。","not_enabled_title": "DingTalk 連携が有効になっていません","not_enabled_description_prefix": "サーバーで","not_enabled_description_suffix": "を設定すると DingTalk ロボットのインストールが有効になります。","not_enabled_self_host_hint": "セルフホストの場合: 詳細はプロジェクトの README を参照してください。",- "connected_bots": "接続済みのボット",+ "connections_title": "接続",+ "deleted_agent": "削除済みのエージェント","loading": "読み込み中…","empty_title": "まだボットが接続されていません","empty_description_prefix": "このワークスペースのエージェントを開き、",@@ -939,7 +949,7 @@"empty_description_suffix": "をクリックしてロボットをインストールします。","revoked_badge": "取り消し済み","installed_at_label": "{{when}} にインストール",- "identity_label": "連携済みの DingTalk ID:{{identity}}",+ "identity_label": "連携済みの Staff ID:{{identity}}","disconnect": "切断","disconnecting": "切断中…","disconnect_confirm_title": "この DingTalk ボットを切断しますか?",@@ -949,7 +959,7 @@"toast_disconnect_failed": "切断に失敗しました","bind_button": "DingTalk を接続","bind_button_title": "{{agent}} を DingTalk ボットに接続",- "agent_bot_connected_label": "DingTalk に接続済み",+ "agent_bot_connected_label": "接続済みボット:","agent_bot_disconnect_tooltip": "この DingTalk ボットをエージェントから解除します。ボットは DingTalk メッセージを受信しなくなります。","byo_dialog_title": "DingTalk ボットを接続","byo_docs_link": "Step-by-step:Multica エージェントを DingTalk に接続する",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex d46224608c..5f0d67b6a9 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -560,7 +560,7 @@},"integrations": {"intro": "이 에이전트를 외부 채팅 플랫폼에 연결해 팀원이 평소 사용하는 도구에서 바로 함께 작업할 수 있도록 합니다.",- "members_note": "에이전트를 외부 채팅 플랫폼에 연결할 수 있는 사람은 워크스페이스 소유자와 관리자뿐입니다. 연결된 봇은 설정 → 연동에서 확인할 수 있습니다."+ "members_note": "이 연결을 관리할 수 있는 사람은 워크스페이스 소유자와 관리자뿐입니다. 연결된 봇은 설정 → 연동에서 확인할 수 있습니다."},"activity": {"status": {diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 4d3bfd095a..30fd867204 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -1075,29 +1075,39 @@},"dingtalk": {"section_title": "DingTalk",- "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": "그룹 에이전트를 업데이트하지 못했어요",+ "page_description": "각 Multica 에이전트를 전용 DingTalk 로봇에 연결하세요. 멤버는 봇과 1:1로 대화하거나, 그룹에서 @ 멘션하거나, /issue 를 입력해 새 Multica 태스크를 만들 수 있습니다.",+ "agent_page_description": "전용 DingTalk 로봇을 통해 이 에이전트에게 DM을 보내거나, 그룹에서 @멘션하거나, /issue로 Multica 태스크를 만들 수 있습니다.",+ "groups_title": "최근 그룹",+ "groups_description": "워크스페이스 멤버가 DingTalk 계정을 연결하고 그룹에서 이 봇을 @멘션하면 표시됩니다. 기본 목록에는 최근 90일 동안 활동한 그룹만 표시됩니다.",+ "groups_overview_description": "각 연결에 에이전트, DingTalk 로봇, 최근에 상호작용한 그룹을 표시합니다.",+ "groups_loading": "그룹을 불러오는 중…",+ "groups_empty": "아직 그룹 메시지가 관찰되지 않았습니다.",+ "groups_no_recent": "최근 90일 동안 활동한 그룹이 없습니다.",+ "groups_inactive": "장기 미활동({{count}})",+ "groups_load_more": "더 불러오기",+ "groups_error": "DingTalk 그룹을 불러오지 못했습니다.",+ "groups_retry": "다시 시도",+ "group_untitled": "이름 없는 DingTalk 그룹",+ "groups_count": "{{count}}",+ "conversation_id_label": "DingTalk 그룹 대화 ID",+ "group_last_active": "마지막 활동 {{time}}",+ "group_mentions_other": "멘션 {{count}}회",+ "group_forget": "목록에서 삭제",+ "group_forget_title": "이 그룹을 목록에서 삭제할까요?",+ "group_forget_description": "Multica 목록에서만 삭제됩니다. 대화와 메시지는 유지되며 봇을 다시 @멘션하면 목록에 다시 나타납니다.",+ "group_forget_cancel": "취소",+ "group_forget_confirm": "목록에서 삭제",+ "group_forget_success": "그룹을 목록에서 삭제했습니다",+ "group_forget_failed": "그룹을 목록에서 삭제하지 못했습니다",+ "bot_identity_unavailable": "식별 정보를 불러올 수 없음",+ "bot_permission_tooltip_prefix": "DingTalk Open Platform에서 이 봇의 앱에",+ "bot_permission_tooltip_suffix": "권한을 부여한 다음 이 봇이 추가된 DingTalk 그룹에서 다시 @멘션하세요.","not_enabled_title": "DingTalk 연동이 활성화되지 않았어요","not_enabled_description_prefix": "서버에서","not_enabled_description_suffix": "를 설정하면 DingTalk 로봇 설치가 활성화됩니다.","not_enabled_self_host_hint": "셀프 호스팅: 자세한 내용은 프로젝트 README를 참고하세요.",- "connected_bots": "연결된 봇",+ "connections_title": "연결",+ "deleted_agent": "삭제된 에이전트","loading": "불러오는 중…","empty_title": "아직 연결된 봇이 없어요","empty_description_prefix": "이 워크스페이스의 에이전트를 열고",@@ -1105,7 +1115,7 @@"empty_description_suffix": "을(를) 클릭해 로봇을 설치하세요.","revoked_badge": "해제됨","installed_at_label": "{{when}}에 설치됨",- "identity_label": "연결된 DingTalk ID: {{identity}}",+ "identity_label": "연결된 Staff ID: {{identity}}","disconnect": "연결 해제","disconnecting": "연결 해제 중…","disconnect_confirm_title": "이 DingTalk 봇을 연결 해제할까요?",@@ -1115,7 +1125,7 @@"toast_disconnect_failed": "연결 해제에 실패했어요","bind_button": "DingTalk 연결","bind_button_title": "{{agent}}을(를) DingTalk 봇에 연결",- "agent_bot_connected_label": "DingTalk에 연결됨",+ "agent_bot_connected_label": "연결된 봇:","agent_bot_disconnect_tooltip": "이 DingTalk 봇을 에이전트에서 연결 해제합니다. 봇이 DingTalk 메시지를 받지 않게 됩니다.","byo_dialog_title": "DingTalk 봇 연결","byo_docs_link": "Step-by-step: Multica 에이전트를 DingTalk에 연결하기",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex 611e2a762e..2344e4064f 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -659,7 +659,7 @@},"integrations": {"intro": "把这个智能体连接到外部聊天平台,让大家在自己熟悉的工具里直接与它协作。",- "members_note": "只有工作区的所有者和管理员才能把智能体连接到外部聊天平台。你可以在\"设置 → 集成\"中查看已连接的 Bot。"+ "members_note": "只有工作区的所有者和管理员可以管理此连接。你可以在\"设置 → 集成\"中查看已连接的 Bot。"},"activity": {"status": {diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 3792fd8165..1f50d18a7b 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -909,29 +909,39 @@},"dingtalk": {"section_title": "钉钉",- "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": "无法更新群智能体",+ "page_description": "将每个 Multica 智能体连接到专属的钉钉机器人。成员可私聊机器人、在群里 @ 它,或输入 /issue 直接创建 Multica 任务。",+ "agent_page_description": "通过专属钉钉机器人私聊该智能体、在群内 @ 它,或输入 /issue 创建 Multica 任务。",+ "groups_title": "近期钉群",+ "groups_description": "工作区成员关联钉钉账号并在群内 @ 该机器人后,群会显示在这里。默认展示最近 90 天活跃的群。",+ "groups_overview_description": "每条连接显示智能体、钉钉机器人和近期有交互的群。",+ "groups_loading": "正在加载钉群…",+ "groups_empty": "尚未观察到群消息。",+ "groups_no_recent": "最近 90 天没有活跃群。",+ "groups_inactive": "长期未活跃({{count}})",+ "groups_load_more": "加载更多",+ "groups_error": "无法加载钉群。",+ "groups_retry": "重试",+ "group_untitled": "未命名钉群",+ "groups_count": "{{count}}",+ "conversation_id_label": "钉群会话 ID",+ "group_last_active": "最近活跃 {{time}}",+ "group_mentions_other": "被 @ {{count}} 次",+ "group_forget": "忘记",+ "group_forget_title": "忘记这个群?",+ "group_forget_description": "该群会从 Multica 的群列表中移除,对话和消息记录不会删除。以后再次 @ 机器人时,群会重新出现。",+ "group_forget_cancel": "取消",+ "group_forget_confirm": "忘记群",+ "group_forget_success": "已从群列表移除",+ "group_forget_failed": "无法移除该群",+ "bot_identity_unavailable": "身份暂不可用",+ "bot_permission_tooltip_prefix": "请在钉钉开放平台为此机器人的应用开通",+ "bot_permission_tooltip_suffix": "权限,然后在任一已添加该机器人的钉群中重新 @ 它。","not_enabled_title": "钉钉集成未启用","not_enabled_description_prefix": "在服务器上设置","not_enabled_description_suffix": "以启用钉钉机器人安装。","not_enabled_self_host_hint": "自部署用户:详见项目 README。",- "connected_bots": "已连接的机器人",+ "connections_title": "连接关系",+ "deleted_agent": "已删除的智能体","loading": "加载中…","empty_title": "尚未连接机器人","empty_description_prefix": "在本工作区打开一个 Agent,点击",@@ -939,7 +949,7 @@"empty_description_suffix": "为其安装机器人。","revoked_badge": "已撤销","installed_at_label": "安装于 {{when}}",- "identity_label": "钉钉绑定身份:{{identity}}",+ "identity_label": "已关联的 Staff ID:{{identity}}","disconnect": "断开连接","disconnecting": "正在断开…","disconnect_confirm_title": "断开此钉钉机器人?",@@ -949,7 +959,7 @@"toast_disconnect_failed": "断开失败","bind_button": "连接钉钉","bind_button_title": "把 {{agent}} 连接到钉钉机器人",- "agent_bot_connected_label": "已连接到钉钉",+ "agent_bot_connected_label": "已连接机器人:","agent_bot_disconnect_tooltip": "将此钉钉机器人从 Agent 解绑。机器人将停止接收钉钉消息。","byo_dialog_title": "连接钉钉机器人","byo_docs_link": "Step-by-step:把你的 Multica 智能体连接到钉钉",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.tsxdeleted file mode 100644index fc3f8db3a6..0000000000--- a/packages/views/settings/components/dingtalk-tab.group-routes-error.test.tsx+++ /dev/null@@ -1,403 +0,0 @@-// @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.tsxindex 7889242b37..5518fa98d8 100644--- a/packages/views/settings/components/dingtalk-tab.test.tsx+++ b/packages/views/settings/components/dingtalk-tab.test.tsx@@ -8,56 +8,66 @@ import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../../locales/en/common.json";import enSettings from "../../locales/en/settings.json";-type MemberRole = "owner" | "admin" | "member" | "guest";+type MemberRole = "owner" | "admin" | "member";const membersRef = vi.hoisted(() => ({current: [{ user_id: "user-1", role: "owner" as MemberRole }],}));+const agentsRef = vi.hoisted(() => ({+ current: [+ { id: "agent-1" },+ { id: "agent-7" },+ { id: "agent-8" },+ ],+}));const installationsRef = vi.hoisted(() => ({current: {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 groupsRef = vi.hoisted(() => ({+ current: {+ data: { groups: [], group_discovery_supported: true } as {+ groups: unknown[];+ group_discovery_supported: boolean;+ inactive_group_counts?: Record<string, number>;+ bot_identities?: Record<string, unknown>;+ },+ isLoading: false,+ isError: false,+ refetch: vi.fn(),+ },}));-const groupRoutesRef = vi.hoisted(() => ({- current: { routes: [] as unknown[] },+const inactiveGroupsRef = vi.hoisted(() => ({+ current: {+ data: undefined as undefined | { pages: Array<{ groups: unknown[]; next_offset: number | null }> },+ isLoading: false,+ isError: false,+ refetch: vi.fn(),+ hasNextPage: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ },}));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("agents")) return { data: agentsRef.current, isLoading: false };+ if (key.includes("groups")) return groupsRef.current;if (key.includes("installations")) return { data: installationsRef.current, isLoading: false };return { data: undefined, isLoading: false };},useQueryClient: () => ({ invalidateQueries: mockInvalidate }),+ useInfiniteQuery: () => inactiveGroupsRef.current,queryOptions: <T,>(opts: T) => opts,}));@@ -80,8 +90,18 @@ vi.mock("@multica/core/workspace/hooks", () => ({}));vi.mock("../../common/actor-avatar", () => ({- ActorAvatar: ({ actorId }: { actorId: string }) => (- <span data-testid="actor-avatar" data-actor-id={actorId} />+ ActorAvatar: ({+ actorId,+ profileLink,+ }: {+ actorId: string;+ profileLink?: boolean;+ }) => (+ <span+ data-testid="actor-avatar"+ data-actor-id={actorId}+ data-profile-link={String(profileLink)}+ />),}));@@ -90,13 +110,17 @@ vi.mock("@multica/core/dingtalk", () => ({queryKey: ["dingtalk", "installations"],queryFn: vi.fn(),}),- dingtalkGroupRoutesOptions: () => ({- queryKey: ["dingtalk", "group-routes"],+ dingtalkGroupsOptions: () => ({+ queryKey: ["dingtalk", "groups"],queryFn: vi.fn(),}),dingtalkKeys: {installations: (wsId: string) => ["dingtalk", "installations", wsId],- groupRoutes: (wsId: string) => ["dingtalk", "group-routes", wsId],+ groups: (wsId: string) => ["dingtalk", "groups", wsId],+ inactiveGroups: (wsId: string, installationId: string) =>+ ["dingtalk", "groups", wsId, "inactive", installationId],+ agentInactiveGroups: (wsId: string, agentId: string, installationId: string) =>+ ["dingtalk", "groups", wsId, "agent", agentId, "inactive", installationId],},}));@@ -104,7 +128,7 @@ vi.mock("@multica/core/api", () => ({api: {registerDingTalkBYO: mockRegisterBYO,deleteDingTalkInstallation: mockDeleteInstallation,- updateDingTalkGroupRoute: mockUpdateGroupRoute,+ forgetDingTalkGroup: vi.fn(),},}));@@ -118,7 +142,7 @@ vi.mock("@multica/core/auth", () => {});vi.mock("sonner", () => ({- toast: { success: mockToastSuccess, error: mockToastError, message: vi.fn() },+ toast: { success: vi.fn(), error: vi.fn(), message: vi.fn() },}));vi.mock("../../platform", () => ({ openExternal: mockOpenExternal }));@@ -140,34 +164,26 @@ function renderUI(children: ReactNode) {function resetFixtures() {vi.clearAllMocks();membersRef.current = [{ user_id: "user-1", role: "owner" }];- 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 },+ { id: "agent-1" },+ { id: "agent-7" },+ { id: "agent-8" },];- 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,+ installationsRef.current = { installations: [], configured: true, install_supported: true };+ groupsRef.current = {+ data: { groups: [], group_discovery_supported: true },+ isLoading: false,+ isError: false,+ refetch: vi.fn(),};- groupRoutesRef.current = {- routes: [{- id: "route-1",- installation_id: "i1",- conversation_id: "cid-platform",- conversation_title: "Platform team",- agent_id: "agent-2",- }],+ inactiveGroupsRef.current = {+ data: undefined,+ isLoading: false,+ isError: false,+ refetch: vi.fn(),+ hasNextPage: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),};}@@ -211,7 +227,6 @@ 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();@@ -219,34 +234,101 @@ describe("DingTalkAgentBindButton", () => {expect(screen.queryByTestId("dingtalk-agent-connect")).toBeNull();});- it("renders nothing for a non-manager", () => {- membersRef.current = [{ user_id: "user-1", role: "member" }];- const { container } = renderUI(<DingTalkAgentBindButton agentId="agent-1" />);- expect(container).toBeEmptyDOMElement();+ it.each([+ { role: "owner", ownsAgent: false, canManage: true },+ { role: "owner", ownsAgent: true, canManage: true },+ { role: "admin", ownsAgent: false, canManage: true },+ { role: "admin", ownsAgent: true, canManage: true },+ { role: "member", ownsAgent: false, canManage: false },+ { role: "member", ownsAgent: true, canManage: true },+ ] as const)(+ "applies the Agent Detail permission matrix: role=$role ownsAgent=$ownsAgent",+ ({ role, ownsAgent, canManage }) => {+ membersRef.current = [{ user_id: "user-1", role }];+ renderUI(+ <DingTalkAgentBindButton+ agentId="agent-1"+ agentOwnerId={ownsAgent ? "user-1" : "user-2"}+ />,+ );+ expect(screen.queryByTestId("dingtalk-agent-connect") !== null).toBe(canManage);+ },+ );++ it("renders no management entry for a user without workspace membership", () => {+ membersRef.current = [];+ const { container } = renderUI(+ <DingTalkAgentBindButton agentId="agent-1" agentOwnerId="user-1" />,+ );+ expect(container.firstChild).toBeNull();});it("renders nothing when install is unavailable and the agent is unbound", () => {- installationsRef.current = {- installations: [],- configured: true,- install_supported: false,- group_routing_supported: true,- };+ installationsRef.current = { installations: [], configured: true, install_supported: false };const { container } = renderUI(<DingTalkAgentBindButton agentId="agent-1" />);- expect(container).toBeEmptyDOMElement();+ expect(container.firstChild).toBeNull();});});describe("DingTalkTab", () => {beforeEach(resetFixtures);+ it.each([+ { role: "owner", canManage: true },+ { role: "admin", canManage: true },+ { role: "member", canManage: false },+ ] as const)(+ "applies the Settings permission matrix for role=$role",+ ({ role, canManage }) => {+ // Settings intentionally has no Agent-owner input: every plain member,+ // including someone who owns one of these Agents, stays read-only here.+ membersRef.current = [{ user_id: "user-1", role }];+ installationsRef.current = {+ installations: [{+ id: "i-role-matrix",+ agent_id: "agent-7",+ status: "active",+ installed_at: "2026-08-19T00:00:00Z",+ bound_dingtalk_user_ids: ["staff-role-matrix"],+ }],+ configured: true,+ install_supported: true,+ };+ groupsRef.current.data.groups = [{+ conversation_id: "cid-role-matrix",+ conversation_title: "Role matrix group",+ bots: [{+ installation_id: "i-role-matrix",+ agent_id: "agent-7",+ bot_name: "Role matrix bot",+ }],+ }];++ renderUI(<DingTalkTab />);+ expect(screen.queryByRole("button", { name: /Disconnect/i }) !== null).toBe(canManage);+ expect(+ screen.queryByRole("button", { name: "Role matrix bot" }) !== null,+ ).toBe(canManage);+ expect(screen.queryByText(/staff-role-matrix/)).toBeNull();+ expect(screen.getByText("Role matrix bot")).toBeTruthy();+ expect(screen.getByText("Role matrix group")).toBeTruthy();+ expect(+ screen.getByText(enSettings.dingtalk.groups_overview_description),+ ).toBeTruthy();+ expect(screen.getByTestId("dingtalk-installation-metadata").textContent).toContain(+ "Installed",+ );+ expect(+ screen.queryByRole("heading", {+ name: "Connections",+ level: 2,+ }),+ ).toBeTruthy();+ },+ );+it("surfaces the not-enabled notice when the deployment has no DingTalk key", () => {- installationsRef.current = {- installations: [],- configured: false,- install_supported: false,- group_routing_supported: false,- };+ installationsRef.current = { installations: [], configured: false, install_supported: false };renderUI(<DingTalkTab />);expect(screen.getByText(/DingTalk integration not enabled/i)).toBeTruthy();});@@ -256,7 +338,7 @@ describe("DingTalkTab", () => {expect(screen.getByText(/No bots connected yet/i)).toBeTruthy();});- it("lists a connected installation with its agent name and a disconnect control", () => {+ it("shows linked Staff IDs from the bot name without adding them to the row", async () => {installationsRef.current = {installations: [{id: "i1",@@ -266,12 +348,23 @@ describe("DingTalkTab", () => {}],configured: true,install_supported: true,- group_routing_supported: true,};+ groupsRef.current.data.groups = [{+ conversation_id: "cid-linked",+ conversation_title: "Linked group",+ bots: [{+ installation_id: "i1",+ agent_id: "agent-7",+ bot_name: "Linked Bot",+ }],+ }];renderUI(<DingTalkTab />);expect(screen.getByText("Agent agent-7")).toBeTruthy();+ const botName = screen.getByRole("button", { name: "Linked Bot" });+ expect(screen.queryByText(/Linked staff ID:/i)).toBeNull();+ await userEvent.hover(botName);expect(- screen.getByText(/Linked DingTalk identity: staff-1001, staff-1002 · Installed/),+ await screen.findByText("Linked staff ID: staff-1001, staff-1002"),).toBeTruthy();expect(screen.getByText(/Disconnect/i)).toBeTruthy();});@@ -281,10 +374,9 @@ describe("DingTalkTab", () => {installations: [{ id: "i1", agent_id: "agent-7", status: "active" }],configured: true,install_supported: true,- group_routing_supported: true,};renderUI(<DingTalkTab />);- expect(screen.queryByText(/Linked DingTalk identity:/i)).toBeNull();+ expect(screen.queryByText(/Linked staff ID:/i)).toBeNull();});it("hides linked DingTalk identities from a regular workspace member", () => {@@ -298,125 +390,385 @@ describe("DingTalkTab", () => {}],configured: true,install_supported: true,- group_routing_supported: true,};renderUI(<DingTalkTab />);expect(screen.getByText("Agent agent-7")).toBeTruthy();expect(screen.queryByText(/staff-must-stay-private/)).toBeNull();- expect(screen.queryByText(/Linked DingTalk identity:/i)).toBeNull();+ expect(screen.queryByText(/Linked staff ID:/i)).toBeNull();+ expect(screen.getByRole("heading", { name: "Connections", level: 2 })).toBeTruthy();+ const overviewDescription = screen.getByText(+ enSettings.dingtalk.groups_overview_description,+ );+ expect(overviewDescription.classList).toContain("text-caption");});- it("shows a placeholder instead of 'Invalid Date' when installed_at is missing or malformed", () => {+ it("shows every observed Agent → Bot → Group relationship to an admin", async () => {+ membersRef.current = [{ user_id: "user-1", role: "admin" }];installationsRef.current = {installations: [- { id: "i1", agent_id: "agent-7", status: "active", installed_at: "" },- { id: "i2", agent_id: "agent-8", status: "active", installed_at: "not-a-date" },+ {+ id: "i1",+ agent_id: "agent-7",+ status: "active",+ installed_at: "2026-08-19T00:00:00Z",+ bound_dingtalk_user_ids: ["staff-1001"],+ },],configured: true,install_supported: true,- group_routing_supported: true,};- renderUI(<DingTalkTab />);- expect(screen.queryByText(/Invalid Date/i)).toBeNull();- });+ groupsRef.current.data.groups = [+ {+ conversation_id: "cid-platform",+ conversation_title: "Platform team",+ bots: [+ {+ installation_id: "i1",+ agent_id: "agent-7",+ bot_name: "Release Bot",+ bot_identity_issue: "missing_qyapi_chat_manage",+ },+ ],+ },+ ];- 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();+ expect(screen.getByText("Agent agent-7")).toBeTruthy();+ expect(screen.getByRole("heading", { name: "Connections", level: 2 })).toBeTruthy();+ expect(screen.getByText("Release Bot")).toBeTruthy();+ expect(+ screen.getByRole("button", { name: /qyapi_chat_manage/i }),+ ).toBeTruthy();+ const connectedLabel = screen.getByText("Connected bot:");+ const connectedStatus = connectedLabel.parentElement?.parentElement;+ expect(connectedStatus?.classList).toContain(+ "text-caption",+ );+ expect(connectedStatus?.classList).not.toContain(+ "text-micro",+ );+ const metadata = screen.getByTestId("dingtalk-installation-metadata");+ expect(metadata.contains(connectedLabel)).toBe(false);+ expect(metadata.parentElement).toBe(connectedStatus?.parentElement);+ expect(metadata.textContent).toContain("Installed");+ expect(metadata.parentElement?.textContent).toContain(+ "Connected bot:Release Bot·Installed",+ );+ expect(metadata.parentElement?.textContent).not.toContain("Linked staff ID");+ expect(metadata.textContent).not.toContain("Release Bot");+ expect(metadata.textContent).not.toMatch(/\d{1,2}:\d{2}:\d{2}/);+ expect(screen.queryByText(/Connected to Agent/i)).toBeNull();+ const groupTitle = screen.getByText("Platform team");+ const forgetButton = screen.getByRole("button", { name: "Forget" });+ expect(groupTitle.parentElement?.contains(forgetButton)).toBe(true);+ expect(forgetButton.classList).toContain("opacity-0");+ expect(forgetButton.classList).toContain("group-hover:opacity-100");+ expect(forgetButton.classList).toContain("group-focus-within:opacity-100");+ expect(+ screen.getByRole("heading", { name: "Recent groups", level: 4 }),+ ).toBeTruthy();+ const overviewDescriptions = screen.getAllByText(+ enSettings.dingtalk.groups_overview_description,+ );+ expect(overviewDescriptions).toHaveLength(1);+ expect(overviewDescriptions[0]?.classList).toContain("text-caption");+ expect(overviewDescriptions[0]?.classList).not.toContain("text-micro");+ expect(screen.getByTestId("dingtalk-bot-groups").parentElement).toBe(+ screen.getByTestId("dingtalk-installation-row"),+ );+ expect(screen.getByTestId("dingtalk-installation-row").classList).toContain("py-6");+ expect(+ screen.getByTestId("dingtalk-installation-row").closest('[data-slot="card"]')?.classList,+ ).toContain("py-0");+ const conversationId = screen.getByLabelText(+ "DingTalk group conversation ID cid-platform",+ );+ expect(conversationId.textContent).toBe("cid-platform");+ expect(conversationId.classList).toContain("text-faint-foreground");+ expect(conversationId.classList).toContain("group-hover:text-muted-foreground");+ await userEvent.hover(conversationId);+ await waitFor(() =>+ expect(document.querySelector('[data-slot="tooltip-content"]')).toBeTruthy(),+ );+ const tooltip = document.querySelector('[data-slot="tooltip-content"]');+ expect(tooltip?.textContent).toBe("DingTalk group conversation ID");+ expect(tooltip?.textContent).not.toContain("cid-platform");+ expect(screen.getAllByText("cid-platform")).toHaveLength(1);});- 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" }));+ it("sorts active groups by recency, then inactive groups by title and conversation ID", () => {+ installationsRef.current = {+ installations: [{ id: "i1", agent_id: "agent-7", status: "active" }],+ configured: true,+ install_supported: true,+ };+ groupsRef.current.data.groups = [+ {+ conversation_id: "cid-alpha-b",+ conversation_title: "Alpha",+ bots: [{ installation_id: "i1", agent_id: "agent-7" }],+ },+ {+ conversation_id: "cid-old",+ conversation_title: "Zulu",+ bots: [{+ installation_id: "i1",+ agent_id: "agent-7",+ last_active_at: "2026-08-19T08:00:00Z",+ }],+ },+ {+ conversation_id: "cid-untitled",+ conversation_title: "",+ bots: [{ installation_id: "i1", agent_id: "agent-7" }],+ },+ {+ conversation_id: "cid-recent",+ conversation_title: "Beta",+ bots: [{+ installation_id: "i1",+ agent_id: "agent-7",+ last_active_at: "2026-08-19T09:00:00Z",+ }],+ },+ {+ conversation_id: "cid-alpha-a",+ conversation_title: "Alpha",+ bots: [{ installation_id: "i1", agent_id: "agent-7" }],+ },+ ];- 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();+ renderUI(<DingTalkTab />);+ expect(+ screen.getAllByTestId("dingtalk-group-item").map((item) =>+ item.querySelector("code")?.textContent,+ ),+ ).toEqual([+ "cid-recent",+ "cid-old",+ "cid-alpha-a",+ "cid-alpha-b",+ "cid-untitled",+ ]);});- it("disables every route selector while one route update is pending", async () => {- setConnectedGroupRoute();- groupRoutesRef.current = {- routes: [- ...groupRoutesRef.current.routes,+ it("globally sorts inactive groups after merging loaded pages", async () => {+ installationsRef.current = {+ installations: [{ id: "i1", agent_id: "agent-7", status: "active" }],+ configured: true,+ install_supported: true,+ };+ groupsRef.current.data = {+ groups: [],+ group_discovery_supported: true,+ inactive_group_counts: { i1: 4 },+ };+ inactiveGroupsRef.current.data = {+ pages: [{- id: "route-2",- installation_id: "i1",- conversation_id: "cid-security",- conversation_title: "Security team",- agent_id: "agent-2",+ groups: [+ {+ conversation_id: "cid-zulu",+ conversation_title: "Zulu",+ bots: [{ installation_id: "i1", agent_id: "agent-7" }],+ },+ {+ conversation_id: "cid-bravo-b",+ conversation_title: "Bravo",+ bots: [{ installation_id: "i1", agent_id: "agent-7" }],+ },+ ],+ next_offset: 2,+ },+ {+ groups: [+ {+ conversation_id: "cid-alpha",+ conversation_title: "Alpha",+ bots: [{ installation_id: "i1", agent_id: "agent-7" }],+ },+ {+ conversation_id: "cid-bravo-a",+ conversation_title: "Bravo",+ bots: [{ installation_id: "i1", agent_id: "agent-7" }],+ },+ ],+ next_offset: null,},],};- mockUpdateGroupRoute.mockImplementation(() => new Promise(() => {}));- const user = userEvent.setup();+renderUI(<DingTalkTab />);+ await userEvent.click(screen.getByRole("button", { name: /long inactive/i }));+ expect(+ screen.getAllByTestId("dingtalk-group-item").map((item) =>+ item.querySelector("code")?.textContent,+ ),+ ).toEqual(["cid-alpha", "cid-bravo-a", "cid-bravo-b", "cid-zulu"]);+ });- 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" }));+ it("renders discovery UI only when the backend explicitly supports it", () => {+ installationsRef.current = {+ installations: [{ id: "i1", agent_id: "agent-7", status: "active" }],+ configured: true,+ install_supported: true,+ };+ groupsRef.current.data = {+ groups: [],+ group_discovery_supported: false,+ };- await waitFor(() => expect(mockUpdateGroupRoute).toHaveBeenCalledTimes(1));- const pendingSelectors = screen.getAllByRole("combobox", { name: "Agent for this group" });- expect(pendingSelectors[0]).toBeDisabled();- expect(pendingSelectors[1]).toBeDisabled();+ renderUI(<DingTalkTab />);+ expect(screen.getByText("Connected bot:")).toBeTruthy();+ expect(screen.queryByText("Identity unavailable")).toBeNull();+ expect(screen.queryByTestId("dingtalk-bot-groups")).toBeNull();+ expect(+ screen.queryByText(enSettings.dingtalk.groups_overview_description),+ ).toBeNull();});- it("renders group routing read-only for a non-manager", () => {- setConnectedGroupRoute();- membersRef.current = [{ user_id: "user-1", role: "member" }];+ it("keeps loading and retryable error states visible before capability data arrives", async () => {+ installationsRef.current = {+ installations: [{ id: "i1", agent_id: "agent-7", status: "active" }],+ configured: true,+ install_supported: true,+ };+ groupsRef.current.isLoading = true;+ groupsRef.current.data = undefined as never;++ const loading = renderUI(<DingTalkTab />);+ expect(screen.getByText("Loading groups…")).toBeTruthy();+ loading.unmount();++ groupsRef.current.isLoading = false;+ groupsRef.current.isError = true;+ groupsRef.current.data = undefined as never;renderUI(<DingTalkTab />);- expect(screen.getByText("Agent Two")).toBeTruthy();- expect(- screen.queryByRole("combobox", { name: "Agent for this group" }),- ).toBeNull();+ await userEvent.click(screen.getByRole("button", { name: "Retry" }));+ expect(groupsRef.current.refetch).toHaveBeenCalledOnce();});- 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" },+ it("shows only the server-filtered Agent, bot, groups, and install time to a regular member", () => {+ membersRef.current = [{ user_id: "user-1", role: "member" }];+ installationsRef.current = {+ installations: [+ { id: "i1", agent_id: "agent-7", status: "active", installed_at: "" },+ ],+ configured: true,+ install_supported: true,+ };+ groupsRef.current.data.groups = [+ {+ conversation_id: "cid-private",+ conversation_title: "Visible group",+ bots: [+ {+ installation_id: "i1",+ agent_id: "agent-7",+ bot_name: "Visible Bot",+ bot_identity_issue: "missing_qyapi_chat_manage",+ },+ ],+ },];+renderUI(<DingTalkTab />);+ expect(screen.getByText("Agent agent-7")).toBeTruthy();+ expect(screen.getByText("Visible Bot")).toBeTruthy();+ expect(screen.getByText("Visible group")).toBeTruthy();+ expect(screen.getByTestId("dingtalk-bot-groups")).toBeTruthy();+ expect(screen.getByTestId("dingtalk-installation-metadata").textContent).toContain(+ "Installed —",+ );+ expect(screen.queryByRole("button", { name: /Disconnect/i })).toBeNull();+ expect(screen.queryByRole("button", { name: /qyapi_chat_manage/i })).toBeNull();+ });- expect(- screen.getByRole("combobox", { name: "Agent for this group" }).textContent,- ).toContain("Agent Two");+ it("shows an unavailable bot identity without admin remediation to a regular member", () => {+ membersRef.current = [{ user_id: "user-1", role: "member" }];+ installationsRef.current = {+ installations: [+ { id: "i1", agent_id: "agent-7", status: "active", installed_at: "" },+ ],+ configured: true,+ install_supported: true,+ };+ groupsRef.current.data.groups = [+ {+ conversation_id: "cid-visible",+ conversation_title: "Visible group",+ bots: [+ {+ installation_id: "i1",+ agent_id: "agent-7",+ bot_name: "",+ bot_identity_issue: "missing_qyapi_chat_manage",+ },+ ],+ },+ ];++ renderUI(<DingTalkTab />);+ expect(screen.getByText("Identity unavailable")).toBeTruthy();+ expect(screen.queryByRole("button", { name: /qyapi_chat_manage/i })).toBeNull();});- it("reports reassignment failures without invalidating successful data", async () => {- setConnectedGroupRoute();- mockUpdateGroupRoute.mockRejectedValue(new Error("route update failed"));- const user = userEvent.setup();+ it("filters a legacy server row when the member cannot see its Agent", () => {+ membersRef.current = [{ user_id: "user-1", role: "member" }];+ agentsRef.current = [{ id: "agent-7" }];+ installationsRef.current = {+ installations: [+ {+ id: "i-private",+ agent_id: "agent-private",+ status: "active",+ installed_at: "2026-08-19T00:00:00Z",+ },+ ],+ configured: true,+ install_supported: true,+ };+renderUI(<DingTalkTab />);+ expect(screen.queryByText("Agent agent-private")).toBeNull();+ expect(screen.queryByTestId("dingtalk-installation-row")).toBeNull();+ expect(screen.getByText("No bots connected yet")).toBeTruthy();+ });++ it("labels an orphaned admin-only installation without linking to a missing Agent", () => {+ installationsRef.current = {+ installations: [+ {+ id: "i-orphan",+ agent_id: "agent-deleted",+ agent_available: false,+ status: "active",+ installed_at: "2026-08-19T00:00:00Z",+ },+ ],+ configured: true,+ install_supported: true,+ };- await user.click(screen.getByRole("combobox", { name: "Agent for this group" }));- await user.click(await screen.findByRole("option", { name: "Agent One" }));+ renderUI(<DingTalkTab />);+ expect(screen.getByText("Deleted Agent")).toBeTruthy();+ expect(screen.getByTestId("actor-avatar").getAttribute("data-profile-link")).toBe(+ "false",+ );+ expect(screen.getByRole("button", { name: /Disconnect/i })).toBeTruthy();+ });- await waitFor(() => {- expect(mockToastError).toHaveBeenCalledWith("route update failed");- });- expect(mockInvalidate).not.toHaveBeenCalledWith({- queryKey: ["dingtalk", "group-routes", "workspace-1"],- });+ it("shows a placeholder instead of 'Invalid Date' when installed_at is missing or malformed", () => {+ installationsRef.current = {+ installations: [+ { id: "i1", agent_id: "agent-7", status: "active", installed_at: "" },+ { id: "i2", agent_id: "agent-8", status: "active", installed_at: "not-a-date" },+ ],+ configured: true,+ install_supported: true,+ };+ renderUI(<DingTalkTab />);+ expect(screen.queryByText(/Invalid Date/i)).toBeNull();});});diff --git a/packages/views/settings/components/dingtalk-tab.tsx b/packages/views/settings/components/dingtalk-tab.tsxindex 92570b57aa..1095f50188 100644--- a/packages/views/settings/components/dingtalk-tab.tsx+++ b/packages/views/settings/components/dingtalk-tab.tsx@@ -1,9 +1,9 @@"use client";import { useState } from "react";-import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";-import { ChevronRight, ExternalLink, Trash2 } from "lucide-react";+import { ChevronDown, ChevronRight, ExternalLink, Info, Trash2 } from "lucide-react";import { cn } from "@multica/ui/lib/utils";import { Button } from "@multica/ui/components/ui/button";import { Card, CardContent } from "@multica/ui/components/ui/card";@@ -15,13 +15,6 @@ 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,@@ -32,41 +25,491 @@ import {AlertDialogHeader,AlertDialogTitle,} from "@multica/ui/components/ui/alert-dialog";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";import { useAuthStore } from "@multica/core/auth";import { useWorkspaceId } from "@multica/core/hooks";-import { agentListOptions, 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 {- dingtalkGroupRoutesOptions,+ dingtalkGroupsOptions,dingtalkInstallationsOptions,dingtalkKeys,} from "@multica/core/dingtalk";import { api } from "@multica/core/api";-import type { DingTalkGroupRoute, DingTalkInstallation } from "@multica/core/types";+import type {+ DingTalkGroup,+ DingTalkGroupBot,+ DingTalkInstallation,+} from "@multica/core/types";import { ActorAvatar } from "../../common/actor-avatar";import { openExternal } from "../../platform";-import { useT } from "../../i18n";+import { useT, useTimeAgo } from "../../i18n";++const dingTalkChatManagePermission = "qyapi_chat_manage";// formatInstalledAt renders the install timestamp defensively: the schema// defaults installed_at to "" and the backend can emit a zero-value timestamp// (0001-01-01T…) for a never-set time, either of which would otherwise surface// as "Invalid Date" or a year-1 date. Fall back to a neutral placeholder.-function formatInstalledAt(value: string): string {+function formatInstalledAt(value: string, locale: string): string {const t = Date.parse(value);if (!value || Number.isNaN(t) || t <= 0) return "—";- return new Date(t).toLocaleString();+ return new Intl.DateTimeFormat(locale, {+ dateStyle: "medium",+ timeStyle: "short",+ }).format(new Date(t));+}++export function getDingTalkBotIdentity(+ groups: DingTalkGroup[],+ installationId: string,+): DingTalkGroupBot | undefined {+ const bots = groups.flatMap((group) =>+ group.bots.filter((bot) => bot.installation_id === installationId),+ );+ const identity = bots.find((bot) => bot.bot_name) ?? bots[0];+ const issue = bots.find((bot) => bot.bot_identity_issue)?.bot_identity_issue;+ return identity+ ? { ...identity, bot_identity_issue: issue ?? identity.bot_identity_issue }+ : undefined;+}++export function DingTalkConnectionLabel({+ botName,+ botIdentityIssue,+ linkedIdentityIDs = [],+ showBotIdentity = true,+ showPermissionHelp = true,+ className,+}: {+ botName?: string;+ botIdentityIssue?: string;+ linkedIdentityIDs?: string[];+ showBotIdentity?: boolean;+ showPermissionHelp?: boolean;+ className?: string;+}) {+ const { t } = useT("settings");+ const botIdentityText =+ botName || t(($) => $.dingtalk.bot_identity_unavailable);+ const linkedIdentityLabel =+ linkedIdentityIDs.length > 0+ ? t(($) => $.dingtalk.identity_label, {+ identity: linkedIdentityIDs.join(", "),+ })+ : "";+ const missingChatManagePermission =+ botIdentityIssue === "missing_qyapi_chat_manage";+ const permissionTooltipPrefix = t(+ ($) => $.dingtalk.bot_permission_tooltip_prefix,+ );+ const permissionTooltipSuffix = t(+ ($) => $.dingtalk.bot_permission_tooltip_suffix,+ );+ const permissionTooltip = `${permissionTooltipPrefix} ${dingTalkChatManagePermission} ${permissionTooltipSuffix}`;+ const [permissionTooltipOpen, setPermissionTooltipOpen] = useState(false);++ return (+ <span+ className={cn(+ "inline-flex min-w-0 items-center gap-2 text-caption text-muted-foreground",+ className,+ )}+ >+ <span+ className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500"+ aria-hidden="true"+ />+ <span className="inline-flex min-w-0 items-center">+ <span className="shrink-0">+ {t(($) => $.dingtalk.agent_bot_connected_label)}+ </span>+ {showBotIdentity && (+ <>+ {linkedIdentityLabel ? (+ <TooltipProvider delay={0}>+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ className="ml-1 min-w-0 cursor-help truncate rounded-sm text-left text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {botIdentityText}+ </button>+ }+ />+ <TooltipContent+ side="top"+ className="max-w-80 whitespace-normal break-all"+ translate="no"+ >+ {linkedIdentityLabel}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ ) : (+ <span className="ml-1 truncate text-foreground">+ {botIdentityText}+ </span>+ )}+ {missingChatManagePermission && showPermissionHelp && (+ <TooltipProvider delay={0}>+ <Tooltip+ open={permissionTooltipOpen}+ onOpenChange={setPermissionTooltipOpen}+ >+ <TooltipTrigger+ closeOnClick={false}+ onClick={() => setPermissionTooltipOpen(true)}+ render={+ <button+ type="button"+ className="-my-1 ml-0.5 inline-flex size-6 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ aria-label={permissionTooltip}+ >+ <Info className="size-3.5" aria-hidden="true" />+ </button>+ }+ />+ <TooltipContent+ side="top"+ align="start"+ className="max-w-80 items-start whitespace-normal border-0 bg-surface-raised px-3 py-2 text-popover-foreground shadow-[var(--menu-shadow)] ring-1 ring-surface-border"+ >+ <span className="leading-relaxed">+ {permissionTooltipPrefix}{" "}+ <code+ className="rounded bg-muted px-1.5 py-0.5 font-mono text-micro text-foreground ring-1 ring-border"+ translate="no"+ >+ {dingTalkChatManagePermission}+ </code>{" "}+ {permissionTooltipSuffix}+ </span>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ )}+ </>+ )}+ </span>+ </span>+ );+}++export function DingTalkBotGroups({+ workspaceId,+ agentId,+ installationId,+ groups,+ inactiveCount = 0,+ canForget = false,+ isLoading,+ isError,+ onRetry,+ showDescription = true,+ className,+}: {+ workspaceId: string;+ agentId?: string;+ installationId: string;+ groups: DingTalkGroup[];+ inactiveCount?: number;+ canForget?: boolean;+ isLoading: boolean;+ isError: boolean;+ onRetry: () => void;+ showDescription?: boolean;+ className?: string;+}) {+ const { t } = useT("settings");+ const timeAgo = useTimeAgo();+ const qc = useQueryClient();+ const [inactiveExpanded, setInactiveExpanded] = useState(false);+ const [forgetTarget, setForgetTarget] = useState<DingTalkGroup | null>(null);+ const [forgetting, setForgetting] = useState(false);+ const inactiveQuery = useInfiniteQuery({+ queryKey: agentId+ ? dingtalkKeys.agentInactiveGroups(workspaceId, agentId, installationId)+ : dingtalkKeys.inactiveGroups(workspaceId, installationId),+ initialPageParam: 0,+ queryFn: ({ pageParam }) => {+ const params = {+ activity: "inactive" as const,+ installationId,+ offset: pageParam,+ };+ return agentId+ ? api.listAgentDingTalkGroups(agentId, params)+ : api.listDingTalkGroups(workspaceId, params);+ },+ getNextPageParam: (page) => page.next_offset,+ enabled: inactiveExpanded && inactiveCount > 0,+ });++ const collectObserved = (source: DingTalkGroup[]) => source+ .flatMap((group) => {+ const bot = group.bots.find(+ (candidate) => candidate.installation_id === installationId,+ );+ return bot ? [{ group, bot }] : [];+ })+ .sort((left, right) => {+ const leftActiveAt = Date.parse(left.bot.last_active_at ?? "");+ const rightActiveAt = Date.parse(right.bot.last_active_at ?? "");+ const leftIsActive = !Number.isNaN(leftActiveAt);+ const rightIsActive = !Number.isNaN(rightActiveAt);++ if (leftIsActive && rightIsActive && leftActiveAt !== rightActiveAt) {+ return rightActiveAt - leftActiveAt;+ }+ if (leftIsActive !== rightIsActive) return leftIsActive ? -1 : 1;++ const leftTitle = left.group.conversation_title;+ const rightTitle = right.group.conversation_title;+ if (leftTitle !== rightTitle) {+ if (!leftTitle) return 1;+ if (!rightTitle) return -1;+ return leftTitle < rightTitle ? -1 : 1;+ }+ if (left.group.conversation_id === right.group.conversation_id) return 0;+ return left.group.conversation_id < right.group.conversation_id ? -1 : 1;+ });+ const observed = collectObserved(groups);+ const inactiveObserved = collectObserved(+ inactiveQuery.data?.pages.flatMap((page) => page.groups) ?? [],+ );++ async function handleForget() {+ if (!forgetTarget || forgetting) return;+ setForgetting(true);+ try {+ await api.forgetDingTalkGroup(+ workspaceId,+ installationId,+ forgetTarget.conversation_id,+ );+ await qc.invalidateQueries({ queryKey: dingtalkKeys.groups(workspaceId) });+ toast.success(t(($) => $.dingtalk.group_forget_success));+ setForgetTarget(null);+ } catch (error) {+ toast.error(+ error instanceof Error+ ? error.message+ : t(($) => $.dingtalk.group_forget_failed),+ );+ } finally {+ setForgetting(false);+ }+ }++ const renderObserved = (+ entries: Array<{ group: DingTalkGroup; bot: DingTalkGroupBot }>,+ ) => (+ <div>+ {entries.map(({ group, bot }) => (+ <div+ key={group.conversation_id}+ className="group space-y-1.5 border-t py-2.5"+ data-testid="dingtalk-group-item"+ >+ <div className="flex min-w-0 items-baseline justify-between gap-3">+ <div className="flex min-w-0 flex-1 items-baseline gap-3">+ <p className="min-w-0 truncate text-caption font-medium">+ {group.conversation_title || t(($) => $.dingtalk.group_untitled)}+ </p>+ {canForget && (+ <button+ type="button"+ className="pointer-events-none shrink-0 text-micro text-muted-foreground opacity-0 underline-offset-2 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 hover:text-foreground hover:underline focus-visible:pointer-events-auto focus-visible:opacity-100"+ onClick={() => setForgetTarget(group)}+ >+ {t(($) => $.dingtalk.group_forget)}+ </button>+ )}+ </div>+ <div className="flex min-w-0 max-w-[60%] items-center">+ <TooltipProvider delay={0}>+ <Tooltip>+ <TooltipTrigger+ render={+ <code+ tabIndex={0}+ translate="no"+ aria-label={`${t(($) => $.dingtalk.conversation_id_label)} ${group.conversation_id}`}+ className="block min-w-0 truncate font-mono text-micro text-faint-foreground transition-colors group-hover:text-muted-foreground focus-visible:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {group.conversation_id}+ </code>+ }+ />+ <TooltipContent side="top">+ {t(($) => $.dingtalk.conversation_id_label)}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ </div>+ {bot.last_active_at && (+ <p+ className="text-micro tabular-nums text-muted-foreground"+ data-testid="dingtalk-group-activity"+ >+ {t(($) => $.dingtalk.group_last_active, {+ time: timeAgo(bot.last_active_at),+ })}+ <span className="mx-1.5" aria-hidden="true">·</span>+ {t(($) => $.dingtalk.group_mentions, {+ count: bot.mention_count ?? 0,+ })}+ </p>+ )}+ </div>+ ))}+ </div>+ );++ return (+ <div+ className={cn("space-y-2 pt-3", className)}+ data-testid="dingtalk-bot-groups"+ >+ <div className="flex items-center gap-2">+ <h4 className="text-body font-medium text-pretty">+ {t(($) => $.dingtalk.groups_title)}+ </h4>+ {!isLoading && !isError && (+ <span className="rounded-full bg-muted px-2 py-0.5 text-micro tabular-nums text-muted-foreground">+ {t(($) => $.dingtalk.groups_count, { count: observed.length })}+ </span>+ )}+ </div>+ {showDescription && (+ <p className="text-caption leading-relaxed text-muted-foreground">+ {t(($) => $.dingtalk.groups_description)}+ </p>+ )}+ {isLoading ? (+ <p className="text-caption text-muted-foreground">+ {t(($) => $.dingtalk.groups_loading)}+ </p>+ ) : isError ? (+ <div className="flex items-center justify-between gap-3" role="alert">+ <p className="text-caption text-muted-foreground">+ {t(($) => $.dingtalk.groups_error)}+ </p>+ <button+ type="button"+ className="shrink-0 text-caption font-medium underline-offset-2 hover:underline"+ onClick={onRetry}+ >+ {t(($) => $.dingtalk.groups_retry)}+ </button>+ </div>+ ) : observed.length === 0 ? (+ <p className="text-caption text-muted-foreground">+ {inactiveCount > 0+ ? t(($) => $.dingtalk.groups_no_recent)+ : t(($) => $.dingtalk.groups_empty)}+ </p>+ ) : (+ renderObserved(observed)+ )}+ {!isLoading && !isError && inactiveCount > 0 && (+ <div className="border-t pt-2">+ <button+ type="button"+ className="flex w-full items-center gap-1.5 py-1 text-caption font-medium text-muted-foreground hover:text-foreground"+ onClick={() => setInactiveExpanded((value) => !value)}+ aria-expanded={inactiveExpanded}+ >+ {inactiveExpanded+ ? <ChevronDown className="h-3.5 w-3.5" aria-hidden="true" />+ : <ChevronRight className="h-3.5 w-3.5" aria-hidden="true" />}+ {t(($) => $.dingtalk.groups_inactive, { count: inactiveCount })}+ </button>+ {inactiveExpanded && (+ <div className="pt-1">+ {inactiveQuery.isLoading ? (+ <p className="py-2 text-caption text-muted-foreground">+ {t(($) => $.dingtalk.groups_loading)}+ </p>+ ) : inactiveQuery.isError ? (+ <button+ type="button"+ className="py-2 text-caption font-medium underline-offset-2 hover:underline"+ onClick={() => void inactiveQuery.refetch()}+ >+ {t(($) => $.dingtalk.groups_retry)}+ </button>+ ) : (+ <>+ {renderObserved(inactiveObserved)}+ {inactiveQuery.hasNextPage && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ disabled={inactiveQuery.isFetchingNextPage}+ onClick={() => void inactiveQuery.fetchNextPage()}+ >+ {inactiveQuery.isFetchingNextPage+ ? t(($) => $.dingtalk.groups_loading)+ : t(($) => $.dingtalk.groups_load_more)}+ </Button>+ )}+ </>+ )}+ </div>+ )}+ </div>+ )}+ <AlertDialog+ open={!!forgetTarget}+ onOpenChange={(open) => {+ if (!open && !forgetting) setForgetTarget(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t(($) => $.dingtalk.group_forget_title)}</AlertDialogTitle>+ <AlertDialogDescription>+ {t(($) => $.dingtalk.group_forget_description)}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={forgetting}>+ {t(($) => $.dingtalk.group_forget_cancel)}+ </AlertDialogCancel>+ <AlertDialogAction onClick={handleForget} disabled={forgetting}>+ {t(($) => $.dingtalk.group_forget_confirm)}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );}// DingTalkTab is the workspace settings panel for DingTalk robot installations.-// Listing is member-visible; the disconnect action is admin-only (the backend-// enforces it; the UI hides the button for non-admins to match).+// Installation rows and group metadata follow Agent view permissions on the+// server. Disconnect, linked Staff IDs, and permission remediation remain+// workspace owner/admin-only in Settings.//// Adding a new installation flows through the Agent detail page: the install-// 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.+// 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.export function DingTalkTab() {const { t } = useT("settings");const wsId = useWorkspaceId();@@ -74,14 +517,6 @@ 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";@@ -90,27 +525,42 @@ export function DingTalkTab() {...dingtalkInstallationsOptions(wsId),});const installations = data?.installations ?? [];+ const { data: visibleAgents = [], isLoading: agentsLoading } = useQuery({+ ...agentListOptions(wsId),+ enabled: !canManage && !!wsId,+ });+ const visibleAgentIDs = new Set(visibleAgents.map((agent) => agent.id));+ // New servers already filter this response. Keep the client-side join as a+ // compatibility guard for older servers that returned every workspace+ // installation to members, which otherwise creates Unknown Agent dead links.+ const displayedInstallations = canManage+ ? installations+ : installations.filter(+ (installation) =>+ installation.agent_available !== false &&+ visibleAgentIDs.has(installation.agent_id),+ );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,+ data: groupsData,+ isLoading: groupsLoading,+ isError: groupsError,+ refetch: retryGroups,} = useQuery({- ...dingtalkGroupRoutesOptions(wsId),- enabled: configured && groupRoutingSupported && hasActiveInstallation && !!wsId,+ ...dingtalkGroupsOptions(wsId),+ enabled:+ configured &&+ displayedInstallations.some(+ (installation) => installation.status === "active",+ ),});- const groupRoutes = groupRouteData?.routes ?? [];- const activeAgents = (agents ?? []).filter((agent) => !agent.archived_at);+ const groupDiscoverySupported =+ groupsData?.group_discovery_supported === true;+ const showGroupDiscovery =+ groupDiscoverySupported || groupsLoading || groupsError;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;@@ -129,22 +579,6 @@ 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 ? (@@ -162,15 +596,26 @@ export function DingTalkTab() {</CardContent></Card>) : (- <section className="space-y-3">- <h2 className="text-body font-semibold">{t(($) => $.dingtalk.connected_bots)}</h2>- {isLoading ? (+ <section className="space-y-4">+ <div className="space-y-1.5">+ <h2 className="text-body font-semibold">+ {t(($) => $.dingtalk.connections_title)}+ </h2>+ {!isLoading &&+ displayedInstallations.length > 0 &&+ groupDiscoverySupported && (+ <p className="max-w-3xl text-caption leading-relaxed text-muted-foreground">+ {t(($) => $.dingtalk.groups_overview_description)}+ </p>+ )}+ </div>+ {isLoading || (!canManage && agentsLoading) ? (<Card><CardContent><p className="text-body text-muted-foreground">{t(($) => $.dingtalk.loading)}</p></CardContent></Card>- ) : installations.length === 0 ? (+ ) : displayedInstallations.length === 0 ? (<Card><CardContent className="space-y-2"><p className="text-body font-medium">{t(($) => $.dingtalk.empty_title)}</p>@@ -182,122 +627,23 @@ export function DingTalkTab() {</CardContent></Card>) : (- <Card>- <CardContent className="divide-y">- {installations.map((inst) => (+ <Card className="py-0">+ <CardContent className="divide-y divide-border/70">+ {displayedInstallations.map((inst) => (<InstallationRowkey={inst.id}+ workspaceId={wsId}installation={inst}canManage={canManage}onDisconnect={() => setDisconnectTarget(inst.id)}- />- ))}- </CardContent>- </Card>- )}- </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)}+ groups={groupsData?.groups ?? []}+ botIdentity={groupsData?.bot_identities?.[inst.id]}+ inactiveCount={groupsData?.inactive_group_counts?.[inst.id] ?? 0}+ groupsLoading={groupsLoading}+ groupsError={groupsError}+ groupDiscoverySupported={groupDiscoverySupported}+ showGroupDiscovery={showGroupDiscovery}+ onRetryGroups={() => void retryGroups()}/>))}</CardContent>@@ -337,128 +683,118 @@ 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({+ workspaceId,installation,canManage,onDisconnect,+ groups,+ botIdentity: suppliedBotIdentity,+ inactiveCount,+ groupsLoading,+ groupsError,+ groupDiscoverySupported,+ showGroupDiscovery,+ onRetryGroups,}: {+ workspaceId: string;installation: DingTalkInstallation;canManage: boolean;onDisconnect: () => void;+ groups: DingTalkGroup[];+ botIdentity?: DingTalkGroupBot;+ inactiveCount: number;+ groupsLoading: boolean;+ groupsError: boolean;+ groupDiscoverySupported: boolean;+ showGroupDiscovery: boolean;+ onRetryGroups: () => void;}) {- const { t } = useT("settings");+ const { t, i18n } = useT("settings");const { getAgentName } = useActorName();const isActive = installation.status === "active";- const agentName = getAgentName(installation.agent_id);+ const agentAvailable = installation.agent_available !== false;+ const agentName = agentAvailable+ ? getAgentName(installation.agent_id)+ : t(($) => $.dingtalk.deleted_agent);const linkedIdentityIDs = canManage? (installation.bound_dingtalk_user_ids ?? []): [];+ const botIdentity = suppliedBotIdentity ?? getDingTalkBotIdentity(groups, installation.id);return (- <div className="flex items-start justify-between gap-4 py-3 first:pt-0 last:pb-0">- <div className="flex min-w-0 items-start gap-3">- <ActorAvatar- actorType="agent"- actorId={installation.agent_id}- size="lg"- enableHoverCard- profileLink- />- <div className="min-w-0 space-y-1">- <p className="text-body font-medium">- {agentName}- {!isActive && (- <span className="ml-2 rounded bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">- {t(($) => $.dingtalk.revoked_badge)}- </span>- )}- </p>- <p- className="max-w-full truncate text-micro text-muted-foreground"- title={linkedIdentityIDs.length > 0 ? linkedIdentityIDs.join(", ") : undefined}- >- {linkedIdentityIDs.length > 0 && (- <>- {t(($) => $.dingtalk.identity_label, {- identity: linkedIdentityIDs.join(", "),+ <div+ className="py-6"+ data-testid="dingtalk-installation-row"+ >+ <div className="flex items-start justify-between gap-6">+ <div className="flex min-w-0 items-start gap-3">+ <ActorAvatar+ actorType="agent"+ actorId={installation.agent_id}+ size="lg"+ enableHoverCard={agentAvailable}+ profileLink={agentAvailable}+ />+ <div className="min-w-0 space-y-1.5">+ <h3 className="truncate text-title-sm font-medium text-pretty">+ {agentName}+ {!isActive && (+ <span className="ml-2 rounded bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">+ {t(($) => $.dingtalk.revoked_badge)}+ </span>+ )}+ </h3>+ <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">+ {isActive && (+ <>+ <DingTalkConnectionLabel+ botName={botIdentity?.bot_name ?? ""}+ botIdentityIssue={botIdentity?.bot_identity_issue ?? ""}+ linkedIdentityIDs={linkedIdentityIDs}+ showBotIdentity={+ groupDiscoverySupported && !groupsLoading+ }+ showPermissionHelp={canManage}+ />+ <span+ className="text-micro text-muted-foreground"+ aria-hidden="true"+ >+ ·+ </span>+ </>+ )}+ <span+ className="text-micro text-muted-foreground"+ data-testid="dingtalk-installation-metadata"+ >+ {t(($) => $.dingtalk.installed_at_label, {+ when: formatInstalledAt(installation.installed_at, i18n.language),})}- {" · "}- </>- )}- {t(($) => $.dingtalk.installed_at_label, {- when: formatInstalledAt(installation.installed_at),- })}- </p>+ </span>+ </div>+ </div></div>+ {canManage && isActive && (+ <Button variant="outline" size="sm" onClick={onDisconnect}>+ <Trash2 className="h-3 w-3" aria-hidden="true" />+ {t(($) => $.dingtalk.disconnect)}+ </Button>+ )}</div>- {canManage && isActive && (- <Button variant="outline" size="sm" onClick={onDisconnect}>- <Trash2 className="h-3 w-3" />- {t(($) => $.dingtalk.disconnect)}- </Button>+ {isActive && showGroupDiscovery && (+ <DingTalkBotGroups+ workspaceId={workspaceId}+ installationId={installation.id}+ groups={groups}+ inactiveCount={inactiveCount}+ canForget={canManage}+ isLoading={groupsLoading}+ isError={groupsError}+ onRetry={onRetryGroups}+ showDescription={false}+ className="space-y-3 pt-5"+ />)}</div>);@@ -481,20 +817,28 @@ function dingtalkDocsUrl(lang: string | undefined): string {// DingTalkAgentBindButton is the per-agent CTA exposed from the agent detail// page. DingTalk uses the bring-your-own-app model: the button opens a dialog-// where the admin pastes the AppKey (client id) + AppSecret (client secret) of-// the DingTalk robot they created (the backend validates both). Visibility:-// 1. Non-owner/admin viewers see nothing (the backend gates install/revoke).+// where an authorized manager pastes the AppKey (client id) + AppSecret (client+// secret) of the DingTalk robot they created (the backend validates both).+// Visibility:+// 1. Only the agent's owner or a workspace owner/admin sees management UI.// 2. If this agent already has an active installation, show the connected// badge (already-installed robots stay manageable).// 3. Otherwise the Connect CTA shows whenever install is available.export function DingTalkAgentBindButton({agentId,agentName,+ agentOwnerId,+ botName,+ botIdentityIssue,className,onShowConnectedDetails,}: {agentId: string;agentName?: string;+ /** Mirrors the backend canManageAgent rule for the per-agent entry point. */+ agentOwnerId?: string | null;+ botName?: string;+ botIdentityIssue?: string;className?: string;/*** When set, the connected state renders as a compact read-only status row@@ -524,8 +868,14 @@ export function DingTalkAgentBindButton({enabled: !!wsId,});const currentMember = members.find((m) => m.user_id === user?.id) ?? null;- const canManage =+ const isWorkspaceAdmin =currentMember?.role === "owner" || currentMember?.role === "admin";+ const isAgentOwner =+ currentMember != null &&+ !!user?.id &&+ agentOwnerId != null &&+ agentOwnerId === user.id;+ const canManage = isWorkspaceAdmin || isAgentOwner;if (!canManage) return null;@@ -539,7 +889,12 @@ export function DingTalkAgentBindButton({className={className}/>) : (- <DingTalkAgentBotConnectedBadge installation={existing} className={className} />+ <DingTalkAgentBotConnectedBadge+ installation={existing}+ botName={botName}+ botIdentityIssue={botIdentityIssue}+ className={className}+ />);}@@ -618,7 +973,7 @@ export function DingTalkAgentBindButton({className="inline-flex w-fit items-center gap-1.5 text-caption text-muted-foreground underline-offset-2 transition-colors hover:text-foreground hover:underline"data-testid="dingtalk-byo-docs-link">- <ExternalLink className="h-3.5 w-3.5" />+ <ExternalLink className="h-3.5 w-3.5" aria-hidden="true" />{t(($) => $.dingtalk.byo_docs_link)}</button></DialogHeader>@@ -696,7 +1051,6 @@ function DingTalkAgentBotStatusRow({onClick: () => void;className?: string;}) {- const { t } = useT("settings");return (<buttontype="button"@@ -707,9 +1061,11 @@ function DingTalkAgentBotStatusRow({)}data-testid="dingtalk-agent-bot-status">- <span className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500" />- <span className="truncate">{t(($) => $.dingtalk.agent_bot_connected_label)}</span>- <ChevronRight className="ml-auto h-3.5 w-3.5 shrink-0" />+ <DingTalkConnectionLabel showBotIdentity={false} />+ <ChevronRight+ className="ml-auto h-3.5 w-3.5 shrink-0"+ aria-hidden="true"+ /></button>);}@@ -719,9 +1075,13 @@ function DingTalkAgentBotStatusRow({// soft-destructive Disconnect. Only owners/admins ever reach this component.function DingTalkAgentBotConnectedBadge({installation,+ botName,+ botIdentityIssue,className,}: {installation: DingTalkInstallation;+ botName?: string;+ botIdentityIssue?: string;className?: string;}) {const { t } = useT("settings");@@ -754,10 +1114,11 @@ function DingTalkAgentBotConnectedBadge({data-testid="dingtalk-agent-bot-connected"><div className="flex items-center justify-between gap-3">- <span className="inline-flex min-w-0 items-center gap-2 text-caption text-muted-foreground">- <span className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500" />- <span className="truncate">{t(($) => $.dingtalk.agent_bot_connected_label)}</span>- </span>+ <DingTalkConnectionLabel+ botName={botName}+ botIdentityIssue={botIdentityIssue}+ showBotIdentity={botName !== undefined || botIdentityIssue !== undefined}+ /><Buttonvariant="destructive"size="sm"@@ -767,7 +1128,7 @@ function DingTalkAgentBotConnectedBadge({aria-label={t(($) => $.dingtalk.disconnect)}data-testid="dingtalk-agent-bot-disconnect">- <Trash2 className="h-3 w-3" />+ <Trash2 className="h-3 w-3" aria-hidden="true" />{disconnecting? t(($) => $.dingtalk.disconnecting): t(($) => $.dingtalk.disconnect)}diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 9de0124ed8..4e60376b77 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -207,6 +207,9 @@ var concurrentIndexCleanups = map[string]string{"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",+ "384_create_dingtalk_group_presence_identity_index": "idx_dingtalk_group_presence_installation_conversation",+ "385_create_dingtalk_group_presence_activity_index": "idx_dingtalk_group_presence_workspace_activity",+ "388_create_dingtalk_bot_identity_installation_index": "idx_dingtalk_bot_identity_installation","309_agent_runtime_id_index": "idx_agent_runtime_id","311_plugin_identity_scoped_key_index": "idx_plugin_identity_scoped_key","316_workspace_mcp_server_name_unique": "idx_workspace_mcp_server_workspace_name",diff --git a/server/cmd/server/integration_test.go b/server/cmd/server/integration_test.goindex e62cc9943a..c0e039951e 100644--- a/server/cmd/server/integration_test.go+++ b/server/cmd/server/integration_test.go@@ -782,6 +782,205 @@ func TestDeleteWorkspaceRequiresOwner(t *testing.T) {}}+func TestDingTalkGroupsThroughRouterSupportsFilteredWorkspaceAndAgentScopes(t *testing.T) {+ removedRouteResp := authRequest(t, http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/dingtalk/group-routes", nil)+ removedRouteResp.Body.Close()+ if removedRouteResp.StatusCode != http.StatusNotFound {+ t.Fatalf("removed DingTalk group-routes status = %d, want 404", removedRouteResp.StatusCode)+ }++ resp := authRequest(t, http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/dingtalk/groups", nil)+ if resp.StatusCode != http.StatusOK {+ resp.Body.Close()+ t.Fatalf("member DingTalk groups status = %d, want 200", resp.StatusCode)+ }+ var result struct {+ Groups []any `json:"groups"`+ }+ readJSON(t, resp, &result)+ if result.Groups == nil || len(result.Groups) != 0 {+ t.Fatalf("disabled DingTalk groups = %#v, want stable empty list", result.Groups)+ }++ var agentID string+ if err := testPool.QueryRow(context.Background(), `+SELECT id FROM agent WHERE workspace_id = $1 ORDER BY created_at LIMIT 1+`, testWorkspaceID).Scan(&agentID); err != nil {+ t.Fatalf("load fixture agent: %v", err)+ }+ resp = authRequest(t, http.MethodGet, "/api/agents/"+agentID+"/dingtalk/groups", nil)+ if resp.StatusCode != http.StatusOK {+ resp.Body.Close()+ t.Fatalf("visible Agent DingTalk groups status = %d, want 200", resp.StatusCode)+ }+ readJSON(t, resp, &result)+ if result.Groups == nil || len(result.Groups) != 0 {+ t.Fatalf("disabled Agent DingTalk groups = %#v, want stable empty list", result.Groups)+ }++ var memberUserID string+ if err := testPool.QueryRow(context.Background(), `+INSERT INTO "user" (name, email) VALUES ('DingTalk group member', $1) RETURNING id+`, "dingtalk-groups-member-"+time.Now().Format("150405.000000000")+"@example.test").Scan(&memberUserID); err != nil {+ t.Fatalf("create member user: %v", err)+ }+ if _, err := testPool.Exec(context.Background(), `+INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')+`, testWorkspaceID, memberUserID); err != nil {+ t.Fatalf("create workspace member: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, memberUserID)+ _, _ = testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, memberUserID)+ })+ memberToken, err := generateTestJWT(memberUserID, "[email protected]", "DingTalk group member")+ if err != nil {+ t.Fatalf("generate member token: %v", err)+ }+ req, err := http.NewRequest(http.MethodGet, testServer.URL+"/api/workspaces/"+testWorkspaceID+"/dingtalk/groups", nil)+ if err != nil {+ t.Fatalf("build member request: %v", err)+ }+ req.Header.Set("Authorization", "Bearer "+memberToken)+ req.Header.Set("X-Workspace-ID", testWorkspaceID)+ resp, err = http.DefaultClient.Do(req)+ if err != nil {+ t.Fatalf("member request failed: %v", err)+ }+ resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("member filtered DingTalk groups status = %d, want 200", resp.StatusCode)+ }++ // Mutation routes admit workspace members to the handler, where the target+ // agent's ownership is checked. Temporarily make this member the agent owner;+ // a router-level admin gate would return 403 before the disabled/validation+ // response below.+ var originalOwnerID string+ if err := testPool.QueryRow(context.Background(), `+SELECT owner_id FROM agent WHERE id = $1+`, agentID).Scan(&originalOwnerID); err != nil {+ t.Fatalf("load fixture Agent owner: %v", err)+ }+ if _, err := testPool.Exec(context.Background(), `+UPDATE agent SET owner_id = $2 WHERE id = $1+`, agentID, memberUserID); err != nil {+ t.Fatalf("assign fixture Agent owner: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `UPDATE agent SET owner_id = $2 WHERE id = $1`, agentID, originalOwnerID)+ })+ req, err = http.NewRequest(http.MethodPost,+ testServer.URL+"/api/workspaces/"+testWorkspaceID+"/dingtalk/install/byo?agent_id="+agentID,+ strings.NewReader(`{}`))+ if err != nil {+ t.Fatalf("build member DingTalk install request: %v", err)+ }+ req.Header.Set("Authorization", "Bearer "+memberToken)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("X-Workspace-ID", testWorkspaceID)+ resp, err = http.DefaultClient.Do(req)+ if err != nil {+ t.Fatalf("member DingTalk install request failed: %v", err)+ }+ resp.Body.Close()+ if resp.StatusCode != http.StatusBadRequest && resp.StatusCode != http.StatusServiceUnavailable {+ t.Fatalf("agent-owner DingTalk install status = %d, want 400 or 503", resp.StatusCode)+ }+ if _, err := testPool.Exec(context.Background(), `+UPDATE agent SET owner_id = $2 WHERE id = $1+`, agentID, originalOwnerID); err != nil {+ t.Fatalf("restore fixture Agent owner: %v", err)+ }++ var originalPermissionMode, originalVisibility string+ if err := testPool.QueryRow(context.Background(), `+SELECT permission_mode, visibility FROM agent WHERE id = $1+`, agentID).Scan(&originalPermissionMode, &originalVisibility); err != nil {+ t.Fatalf("load fixture Agent access mode: %v", err)+ }+ if _, err := testPool.Exec(context.Background(), `+UPDATE agent SET permission_mode = 'public_to', visibility = 'workspace' WHERE id = $1+`, agentID); err != nil {+ t.Fatalf("make fixture Agent public_to: %v", err)+ }+ targetInsert, err := testPool.Exec(context.Background(), `+INSERT INTO agent_invocation_target (agent_id, target_type, target_id)+VALUES ($1, 'workspace', $2)+ON CONFLICT (agent_id, target_type, target_id) DO NOTHING+`, agentID, testWorkspaceID)+ if err != nil {+ t.Fatalf("make fixture agent workspace-visible: %v", err)+ }+ insertedTarget := targetInsert.RowsAffected() == 1+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `+UPDATE agent SET permission_mode = $2, visibility = $3 WHERE id = $1+`, agentID, originalPermissionMode, originalVisibility)+ if !insertedTarget {+ return+ }+ _, _ = testPool.Exec(context.Background(), `+DELETE FROM agent_invocation_target WHERE agent_id = $1 AND target_type = 'workspace' AND target_id = $2+`, agentID, testWorkspaceID)+ })+ req, err = http.NewRequest(http.MethodGet, testServer.URL+"/api/agents/"+agentID+"/dingtalk/groups", nil)+ if err != nil {+ t.Fatalf("build member Agent request: %v", err)+ }+ req.Header.Set("Authorization", "Bearer "+memberToken)+ req.Header.Set("X-Workspace-ID", testWorkspaceID)+ resp, err = http.DefaultClient.Do(req)+ if err != nil {+ t.Fatalf("member Agent request failed: %v", err)+ }+ resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("member visible-Agent DingTalk groups status = %d, want 200", resp.StatusCode)+ }++ var runtimeID, privateAgentID string+ if err := testPool.QueryRow(context.Background(), `+SELECT runtime_id FROM agent WHERE id = $1+`, agentID).Scan(&runtimeID); err != nil {+ t.Fatalf("load fixture runtime: %v", err)+ }+ if err := testPool.QueryRow(context.Background(), `+INSERT INTO agent (+ workspace_id, name, description, runtime_mode, runtime_config, runtime_id,+ visibility, permission_mode, max_concurrent_tasks, owner_id+) VALUES ($1, 'DingTalk private groups fixture', '', 'cloud', '{}'::jsonb, $2,+ 'private', 'private', 1, $3)+RETURNING id+`, testWorkspaceID, runtimeID, testUserID).Scan(&privateAgentID); err != nil {+ t.Fatalf("create private Agent: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, privateAgentID)+ })+ req, err = http.NewRequest(http.MethodGet, testServer.URL+"/api/agents/"+privateAgentID+"/dingtalk/groups", nil)+ if err != nil {+ t.Fatalf("build private Agent request: %v", err)+ }+ req.Header.Set("Authorization", "Bearer "+memberToken)+ req.Header.Set("X-Workspace-ID", testWorkspaceID)+ resp, err = http.DefaultClient.Do(req)+ if err != nil {+ t.Fatalf("private Agent request failed: %v", err)+ }+ resp.Body.Close()+ if resp.StatusCode != http.StatusForbidden {+ t.Fatalf("member private-Agent DingTalk groups status = %d, want 403", resp.StatusCode)+ }++ const outsideWorkspaceID = "d1474000-0000-4000-8000-000000000001"+ resp = authRequest(t, http.MethodGet, "/api/workspaces/"+outsideWorkspaceID+"/dingtalk/groups", nil)+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusNotFound {+ t.Fatalf("non-member DingTalk groups status = %d, want 404", resp.StatusCode)+ }+}+// ---- Inbox through full router ----func TestInboxThroughRouter(t *testing.T) {diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 14dc227bc8..4a6c4fe4dc 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -777,7 +777,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busslog.Default(),)}- channelRouter.Register(dingtalk.TypeDingTalk, dingtalk.NewDingTalkResolverSet(queries, pool, replier, ack, media))+ botNames := dingtalk.NewBotNameResolver(dingtalkClient, box.Open)+ channelRouter.Register(dingtalk.TypeDingTalk, dingtalk.NewDingTalkResolverSet(queries, pool, replier, ack, media, botNames))dingtalk.NewOutbound(queries, box.Open, dingtalkClient, slog.Default()).Register(bus)dingtalk.RegisterDingTalk(channelRegistry, dingtalk.ChannelDeps{Decrypt: box.Open,@@ -1575,13 +1576,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.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.Get("/dingtalk/groups", h.ListDingTalkGroups)+ r.Delete("/dingtalk/installations/{installationId}/groups/{conversationId}", h.ForgetDingTalkGroup)r.Delete("/dingtalk/installations/{installationId}", h.RevokeDingTalkInstallation)r.Post("/dingtalk/install/byo", h.RegisterDingTalkBYO)- r.Patch("/dingtalk/group-routes/{routeId}", h.UpdateDingTalkGroupRoute)})// Telegram integration. Same admin/member split as Slack:@@ -1940,6 +1938,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/restore", h.RestoreAgent)r.Post("/cancel-tasks", h.CancelAgentTasks)r.Get("/tasks", h.ListAgentTasks)+ r.Get("/dingtalk/groups", h.ListDingTalkGroupsForAgent)r.Get("/skills", h.ListAgentSkills)r.Put("/skills", h.SetAgentSkills)r.Post("/skills/add", h.AddAgentSkills)diff --git a/server/internal/handler/dingtalk.go b/server/internal/handler/dingtalk.goindex 2cab60a05c..099490ee5b 100644--- a/server/internal/handler/dingtalk.go+++ b/server/internal/handler/dingtalk.go@@ -1,9 +1,13 @@package handlerimport (+ "context""encoding/json""errors""net/http"+ "net/url"+ "sort"+ "strconv""strings""time"@@ -12,7 +16,6 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/integrations/dingtalk"- "github.com/multica-ai/multica/server/internal/middleware"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -30,24 +33,44 @@ type DingTalkInstallationResponse struct {InstalledAt string `json:"installed_at"`CreatedAt string `json:"created_at"`UpdatedAt string `json:"updated_at"`+ AgentAvailable bool `json:"agent_available"`BoundDingTalkUserIDs []string `json:"bound_dingtalk_user_ids,omitempty"`}-// 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"`+// DingTalkGroupBotResponse identifies one connected Multica bot observed in a+// DingTalk group. AgentID is the product-facing identity; BotName is the+// readable DingTalk identity when the app has qyapi_chat_manage permission.+type DingTalkGroupBotResponse struct {+ InstallationID string `json:"installation_id"`+ AgentID string `json:"agent_id"`+ BotName string `json:"bot_name"`+ BotIdentityIssue string `json:"bot_identity_issue"`+ LastActiveAt string `json:"last_active_at"`+ MentionCount int64 `json:"mention_count"`}+// DingTalkGroupResponse groups every connected bot observed under the same+// DingTalk openConversationId.+type DingTalkGroupResponse struct {+ ConversationID string `json:"conversation_id"`+ ConversationTitle string `json:"conversation_title"`+ Bots []DingTalkGroupBotResponse `json:"bots"`+}++type ListDingTalkGroupsResponse struct {+ Groups []DingTalkGroupResponse `json:"groups"`+ GroupDiscoverySupported bool `json:"group_discovery_supported"`+ InactiveGroupCounts map[string]int64 `json:"inactive_group_counts"`+ BotIdentities map[string]DingTalkGroupBotResponse `json:"bot_identities"`+ NextOffset *int `json:"next_offset,omitempty"`+}++const (+ dingTalkActiveGroupWindow = 90 * 24 * time.Hour+ dingTalkInactivePageSize = 20+ dingTalkInactiveMaxPage = 100+)+func dingtalkInstallationToResponse(row db.ChannelInstallation) DingTalkInstallationResponse {return DingTalkInstallationResponse{ID: uuidToString(row.ID),@@ -58,231 +81,478 @@ func dingtalkInstallationToResponse(row db.ChannelInstallation) DingTalkInstallaInstalledAt: row.InstalledAt.Time.UTC().Format(time.RFC3339),CreatedAt: row.CreatedAt.Time.UTC().Format(time.RFC3339),UpdatedAt: row.UpdatedAt.Time.UTC().Format(time.RFC3339),+ AgentAvailable: true,}}-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),+// dingtalkAgentVisibility resolves the Agent side of the Settings inventory in+// one batch. The available set distinguishes an orphaned installation from an+// inaccessible Agent for admins. The visible set enforces the same owner / role+// / invocation-target rules as the Agent list for ordinary members.+func (h *Handler) dingtalkAgentVisibility(+ ctx context.Context,+ workspaceID pgtype.UUID,+ userID string,+ member db.Member,+) (available map[string]struct{}, visible map[string]struct{}, ok bool) {+ agents, err := h.Queries.ListAllAgents(ctx, workspaceID)+ if err != nil {+ return nil, nil, false+ }+ available = make(map[string]struct{}, len(agents))+ visible = make(map[string]struct{}, len(agents))+ for _, agent := range agents {+ agentID := uuidToString(agent.ID)+ available[agentID] = struct{}{}+ if roleAllowed(member.Role, "owner", "admin") {+ visible[agentID] = struct{}{}+ }+ }+ if roleAllowed(member.Role, "owner", "admin") {+ return available, visible, true}+ targetsByAgent, loaded := h.loadInvocationTargetsByAgent(ctx, agents)+ if !loaded {+ return nil, nil, false+ }+ for _, agent := range agents {+ agentID := uuidToString(agent.ID)+ if memberAllowedToViewAgent(agent, targetsByAgent[agentID], userID, member.Role) {+ visible[agentID] = struct{}{}+ }+ }+ return available, visible, true}-// 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) {+// 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.+func (h *Handler) ListDingTalkInstallations(w http.ResponseWriter, r *http.Request) {if h.DingTalkInstall == nil {- writeJSON(w, http.StatusOK, map[string]any{"routes": []DingTalkGroupRouteResponse{}})+ writeJSON(w, http.StatusOK, map[string]any{+ "installations": []DingTalkInstallationResponse{},+ "configured": false,+ "install_supported": false,+ })return}wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")if !ok {return}- rows, err := h.Queries.ListDingTalkGroupRoutesByWorkspace(r.Context(), wsUUID)+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ member, ok := h.workspaceMember(w, r, uuidToString(wsUUID))+ if !ok {+ return+ }+ availableAgentIDs, visibleAgentIDs, loaded := h.dingtalkAgentVisibility(+ r.Context(), wsUUID, userID, member,+ )+ if !loaded {+ writeError(w, http.StatusInternalServerError, "failed to resolve dingtalk installation visibility")+ return+ }+ rows, err := h.DingTalkInstall.ListByWorkspace(r.Context(), wsUUID)if err != nil {- writeError(w, http.StatusInternalServerError, "failed to list dingtalk group routes")+ writeError(w, http.StatusInternalServerError, "failed to list dingtalk installations")return}- out := make([]DingTalkGroupRouteResponse, 0, len(rows))+ bindingsByInstallation := map[pgtype.UUID][]string{}+ canViewAll := roleAllowed(member.Role, "owner", "admin")+ canViewAccountBindings := canViewAll+ if canViewAccountBindings {+ userUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")+ if !ok {+ return+ }+ bindings, err := h.Queries.ListDingTalkUserBindingsForMember(r.Context(), db.ListDingTalkUserBindingsForMemberParams{+ WorkspaceID: wsUUID,+ MulticaUserID: userUUID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list dingtalk user bindings")+ return+ }+ for _, binding := range bindings {+ bindingsByInstallation[binding.InstallationID] = append(+ bindingsByInstallation[binding.InstallationID],+ binding.ChannelUserID,+ )+ }+ }+ out := make([]DingTalkInstallationResponse, 0, len(rows))for _, row := range rows {- out = append(out, dingtalkGroupRouteToResponse(row))+ agentID := uuidToString(row.AgentID)+ if !canViewAll {+ if _, canView := visibleAgentIDs[agentID]; !canView {+ continue+ }+ }+ response := dingtalkInstallationToResponse(row)+ _, response.AgentAvailable = availableAgentIDs[agentID]+ response.BoundDingTalkUserIDs = bindingsByInstallation[row.ID]+ out = append(out, response)}- 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"`+ writeJSON(w, http.StatusOK, map[string]any{+ "installations": out,+ "configured": true,+ "install_supported": true,+ })}-// 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) {+// ListDingTalkGroups (GET /api/workspaces/{id}/dingtalk/groups) returns the+// Settings inventory of observed groups and connected Multica bots. Workspace+// owners/admins see the full inventory; ordinary members only receive bots for+// Agents they can open, matching ListAgents and Agent Detail.+func (h *Handler) ListDingTalkGroups(w http.ResponseWriter, r *http.Request) {if h.DingTalkInstall == nil {- writeError(w, http.StatusServiceUnavailable, "dingtalk integration not configured")+ writeJSON(w, http.StatusOK, ListDingTalkGroupsResponse{+ Groups: []DingTalkGroupResponse{},+ GroupDiscoverySupported: true,+ InactiveGroupCounts: map[string]int64{},+ BotIdentities: map[string]DingTalkGroupBotResponse{},+ })+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")+ if !ok {return}userID, ok := requireUserID(w, r)if !ok {return}- wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")+ member, ok := h.workspaceMember(w, r, uuidToString(wsUUID))if !ok {return}- routeUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "routeId"), "route id")+ var visibleAgentIDs map[string]struct{}+ if !roleAllowed(member.Role, "owner", "admin") {+ _, visible, loaded := h.dingtalkAgentVisibility(r.Context(), wsUUID, userID, member)+ if !loaded {+ writeError(w, http.StatusInternalServerError, "failed to resolve dingtalk group visibility")+ return+ }+ visibleAgentIDs = visible+ }+ h.listDingTalkGroups(w, r, wsUUID, "", visibleAgentIDs)+}++// ListDingTalkGroupsForAgent (GET /api/agents/{id}/dingtalk/groups) exposes+// only the selected agent's 1:1 bot and its observed groups. It deliberately+// reuses the Agent detail view gate: if the caller cannot open this Agent,+// they cannot infer its DingTalk group activity either.+func (h *Handler) ListDingTalkGroupsForAgent(w http.ResponseWriter, r *http.Request) {+ agentID := chi.URLParam(r, "id")+ agent, ok := h.loadAgentForUser(w, r, agentID)if !ok {return}- var body UpdateDingTalkGroupRouteRequest- if err := json.NewDecoder(r.Body).Decode(&body); err != nil {- writeError(w, http.StatusBadRequest, "invalid request body")+ workspaceID := uuidToString(agent.WorkspaceID)+ actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)+ if !h.canAccessPrivateAgent(r.Context(), agent, actorType, actorID, workspaceID) {+ writeError(w, http.StatusForbidden, "you do not have access to this agent")return}- agentUUID, ok := parseUUIDOrBadRequest(w, strings.TrimSpace(body.AgentID), "agent_id")- if !ok {+ if h.DingTalkInstall == nil {+ writeJSON(w, http.StatusOK, ListDingTalkGroupsResponse{+ Groups: []DingTalkGroupResponse{},+ GroupDiscoverySupported: true,+ InactiveGroupCounts: map[string]int64{},+ BotIdentities: map[string]DingTalkGroupBotResponse{},+ })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")+ h.listDingTalkGroups(w, r, agent.WorkspaceID, agentID, nil)+}++func (h *Handler) listDingTalkGroups(+ w http.ResponseWriter,+ r *http.Request,+ workspaceID pgtype.UUID,+ agentID string,+ visibleAgentIDs map[string]struct{},+) {+ filterByAgent := agentID != ""+ var agentUUID pgtype.UUID+ if filterByAgent {+ agentUUID = parseUUID(agentID)+ }+ activeSince := pgtype.Timestamptz{Time: time.Now().UTC().Add(-dingTalkActiveGroupWindow), Valid: true}+ activity := strings.TrimSpace(r.URL.Query().Get("activity"))+ if activity != "" && activity != "inactive" {+ writeError(w, http.StatusBadRequest, "activity must be inactive when provided")+ return+ }+ includeInactive := activity == "inactive"+ installationID := strings.TrimSpace(r.URL.Query().Get("installation_id"))+ var installationUUID pgtype.UUID+ if includeInactive {+ if installationID == "" {+ writeError(w, http.StatusBadRequest, "installation_id is required for inactive groups")+ return+ }+ var ok bool+ installationUUID, ok = parseUUIDOrBadRequest(w, installationID, "installation_id")+ if !ok {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")+ pageOffset := 0+ pageLimit := 0+ if includeInactive {+ pageLimit = dingTalkInactivePageSize+ if raw := strings.TrimSpace(r.URL.Query().Get("limit")); raw != "" {+ parsed, err := strconv.Atoi(raw)+ if err != nil || parsed < 1 || parsed > dingTalkInactiveMaxPage {+ writeError(w, http.StatusBadRequest, "limit must be between 1 and 100")+ return+ }+ pageLimit = parsed+ }+ if raw := strings.TrimSpace(r.URL.Query().Get("offset")); raw != "" {+ parsed, err := strconv.Atoi(raw)+ if err != nil || parsed < 0 {+ writeError(w, http.StatusBadRequest, "offset must be a non-negative integer")+ return+ }+ pageOffset = parsed+ }+ }+ mayListPresence := true+ if includeInactive {+ var err error+ mayListPresence, err = h.mayListInactiveDingTalkInstallation(+ r.Context(), workspaceID, installationUUID, filterByAgent, agentUUID, visibleAgentIDs,+ )+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to authorize dingtalk group installation")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+ rows := []db.ListDingTalkGroupPresencesByWorkspaceRow{}+ if mayListPresence {+ var err error+ rows, err = h.Queries.ListDingTalkGroupPresencesByWorkspace(r.Context(), db.ListDingTalkGroupPresencesByWorkspaceParams{+ WorkspaceID: workspaceID,+ FilterByAgent: filterByAgent,+ AgentID: agentUUID,+ FilterByInstallation: includeInactive,+ FilterInstallationID: installationUUID,+ IncludeInactive: includeInactive,+ ActiveSince: activeSince,+ PageOffset: int32(pageOffset),+ PageLimit: int32(pageLimit + boolToInt(includeInactive)),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list dingtalk groups")+ return+ }}- if agent.Kind != "user" {- writeError(w, http.StatusBadRequest, "only user agents can handle a DingTalk group")+ var nextOffset *int+ if includeInactive && len(rows) > pageLimit {+ rows = rows[:pageLimit]+ next := pageOffset + pageLimit+ nextOffset = &next+ }+ inactiveRows, err := h.Queries.CountInactiveDingTalkGroupPresencesByWorkspace(r.Context(), db.CountInactiveDingTalkGroupPresencesByWorkspaceParams{+ WorkspaceID: workspaceID,+ ActiveSince: activeSince,+ FilterByAgent: filterByAgent,+ AgentID: agentUUID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to count inactive dingtalk groups")return}- if agent.ArchivedAt.Valid {- writeError(w, http.StatusConflict, "an archived agent cannot handle a DingTalk group")- return+ inactiveCounts := make(map[string]int64, len(inactiveRows))+ for _, row := range inactiveRows {+ rowAgentID := uuidToString(row.AgentID)+ if visibleAgentIDs != nil {+ if _, visible := visibleAgentIDs[rowAgentID]; !visible {+ continue+ }+ }+ inactiveCounts[uuidToString(row.InstallationID)] = row.GroupCount}- row, err := h.Queries.ReassignDingTalkGroupRoute(r.Context(), db.ReassignDingTalkGroupRouteParams{- ID: routeUUID, WorkspaceID: wsUUID, AgentID: agentUUID,+ identityRows, err := h.Queries.ListDingTalkBotIdentitiesByWorkspace(r.Context(), db.ListDingTalkBotIdentitiesByWorkspaceParams{+ WorkspaceID: workspaceID,+ FilterByAgent: filterByAgent,+ 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+ writeError(w, http.StatusInternalServerError, "failed to list dingtalk bot identities")+ return+ }+ botIdentities := make(map[string]DingTalkGroupBotResponse, len(identityRows))+ for _, row := range identityRows {+ rowAgentID := uuidToString(row.AgentID)+ if visibleAgentIDs != nil {+ if _, visible := visibleAgentIDs[rowAgentID]; !visible {+ continue}- if agentErr != nil && !errors.Is(agentErr, pgx.ErrNoRows) {- writeError(w, http.StatusInternalServerError, "failed to load agent")- return+ }+ installationID := uuidToString(row.InstallationID)+ botIdentities[installationID] = DingTalkGroupBotResponse{+ InstallationID: installationID,+ AgentID: rowAgentID,+ BotName: row.BotName,+ BotIdentityIssue: row.BotIdentityIssue,+ }+ }++ groupIndexByID := make(map[string]int, len(rows))+ groups := make([]DingTalkGroupResponse, 0, len(rows))+ for _, row := range rows {+ rowAgentID := uuidToString(row.AgentID)+ if agentID != "" && rowAgentID != agentID {+ continue+ }+ if visibleAgentIDs != nil {+ if _, visible := visibleAgentIDs[rowAgentID]; !visible {+ continue}- writeError(w, http.StatusConflict, "the selected agent is no longer available")- return}- writeError(w, http.StatusInternalServerError, "failed to update dingtalk group route")- return+ groupIndex, exists := groupIndexByID[row.ConversationID]+ if !exists {+ groups = append(groups, DingTalkGroupResponse{+ ConversationID: row.ConversationID,+ ConversationTitle: row.ConversationTitle,+ Bots: []DingTalkGroupBotResponse{},+ })+ groupIndex = len(groups) - 1+ groupIndexByID[row.ConversationID] = groupIndex+ } else if groups[groupIndex].ConversationTitle == "" && row.ConversationTitle != "" {+ groups[groupIndex].ConversationTitle = row.ConversationTitle+ }+ lastActiveAt := ""+ if row.LastActiveAt.Valid {+ lastActiveAt = row.LastActiveAt.Time.UTC().Format(time.RFC3339)+ }+ groups[groupIndex].Bots = append(groups[groupIndex].Bots, DingTalkGroupBotResponse{+ InstallationID: uuidToString(row.InstallationID),+ AgentID: rowAgentID,+ BotName: row.BotName,+ BotIdentityIssue: row.BotIdentityIssue,+ LastActiveAt: lastActiveAt,+ MentionCount: row.MentionCount,+ })}- h.publish(protocol.EventDingTalkGroupRouteUpdated, uuidToString(wsUUID), "user", userID, map[string]any{- "id": uuidToString(row.ID),+ for index := range groups {+ sort.SliceStable(groups[index].Bots, func(i, j int) bool {+ return groups[index].Bots[i].InstallationID < groups[index].Bots[j].InstallationID+ })+ }+ sort.SliceStable(groups, func(i, j int) bool {+ left := groups[i].ConversationTitle+ right := groups[j].ConversationTitle+ if left == right {+ return groups[i].ConversationID < groups[j].ConversationID+ }+ if left == "" {+ return false+ }+ if right == "" {+ return true+ }+ return left < right+ })+ writeJSON(w, http.StatusOK, ListDingTalkGroupsResponse{+ Groups: groups,+ GroupDiscoverySupported: true,+ InactiveGroupCounts: inactiveCounts,+ BotIdentities: botIdentities,+ NextOffset: nextOffset,})- 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,- "group_routing_supported": false,- })- return+// mayListInactiveDingTalkInstallation resolves the requested installation at+// the server boundary before pagination can derive a cursor from its rows.+// Missing, inactive, cross-workspace, and inaccessible installations all return+// false so callers cannot distinguish them through group data or next_offset.+func (h *Handler) mayListInactiveDingTalkInstallation(+ ctx context.Context,+ workspaceID pgtype.UUID,+ installationID pgtype.UUID,+ filterByAgent bool,+ agentID pgtype.UUID,+ visibleAgentIDs map[string]struct{},+) (bool, error) {+ installation, err := h.Queries.GetChannelInstallationInWorkspace(ctx, db.GetChannelInstallationInWorkspaceParams{+ ID: installationID,+ WorkspaceID: workspaceID,+ ChannelType: string(dingtalk.TypeDingTalk),+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return false, nil+ }+ return false, err+ }+ if installation.Status != "active" {+ return false, nil+ }+ if filterByAgent {+ return installation.AgentID == agentID, nil+ }+ if visibleAgentIDs == nil {+ return true, nil+ }+ _, visible := visibleAgentIDs[uuidToString(installation.AgentID)]+ return visible, nil+}++func boolToInt(value bool) int {+ if value {+ return 1}+ return 0+}++// ForgetDingTalkGroup removes one observation from the Settings inventory.+// Sessions and message history are retained. A later successfully addressed+// message from the same group observes it again automatically.+func (h *Handler) ForgetDingTalkGroup(w http.ResponseWriter, r *http.Request) {wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")if !ok {return}- userID, ok := requireUserID(w, r)+ if _, ok := h.requireWorkspaceRole(w, r, uuidToString(wsUUID), "dingtalk group not found", "owner", "admin"); !ok {+ return+ }+ installationUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "installationId"), "installation id")if !ok {return}- rows, err := h.DingTalkInstall.ListByWorkspace(r.Context(), wsUUID)+ conversationID, err := url.PathUnescape(chi.URLParam(r, "conversationId"))if err != nil {- writeError(w, http.StatusInternalServerError, "failed to list dingtalk installations")+ writeError(w, http.StatusBadRequest, "invalid conversation id")return}- bindingsByInstallation := map[pgtype.UUID][]string{}- member, hasMemberContext := middleware.MemberFromContext(r.Context())- canViewAccountBindings := hasMemberContext && (member.Role == "owner" || member.Role == "admin")- if canViewAccountBindings {- userUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")- if !ok {- return- }- bindings, err := h.Queries.ListDingTalkUserBindingsForMember(r.Context(), db.ListDingTalkUserBindingsForMemberParams{- WorkspaceID: wsUUID,- MulticaUserID: userUUID,- })- if err != nil {- writeError(w, http.StatusInternalServerError, "failed to list dingtalk user bindings")- return- }- for _, binding := range bindings {- bindingsByInstallation[binding.InstallationID] = append(- bindingsByInstallation[binding.InstallationID],- binding.ChannelUserID,- )- }+ conversationID = strings.TrimSpace(conversationID)+ if conversationID == "" {+ writeError(w, http.StatusBadRequest, "conversation id is required")+ return}- out := make([]DingTalkInstallationResponse, 0, len(rows))- for _, row := range rows {- response := dingtalkInstallationToResponse(row)- response.BoundDingTalkUserIDs = bindingsByInstallation[row.ID]- out = append(out, response)+ if _, err = h.Queries.ForgetDingTalkGroupPresence(r.Context(), db.ForgetDingTalkGroupPresenceParams{+ WorkspaceID: wsUUID,+ InstallationID: installationUUID,+ ConversationID: conversationID,+ }); err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusNotFound, "dingtalk group not found")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to forget dingtalk group")+ }+ return}- writeJSON(w, http.StatusOK, map[string]any{- "installations": out,- "configured": true,- "install_supported": true,- "group_routing_supported": true,- })+ w.WriteHeader(http.StatusNoContent)}// RegisterDingTalkBYORequest is the body for a bring-your-own-app install: the@@ -295,8 +565,9 @@ type RegisterDingTalkBYORequest struct {// RegisterDingTalkBYO (POST /api/workspaces/{id}/dingtalk/install/byo?agent_id=…)// installs a user-supplied ("bring your own") DingTalk robot for an agent, so// several agents can each have their own bot identity in the SAME DingTalk-// organization. Admin-only at the router. Like Slack's BYO path this needs only-// the at-rest key configured (DingTalkInstall != nil).+// organization. The router requires workspace membership; this handler then+// authorizes the target agent's owner or a workspace owner/admin. Like Slack's+// BYO path this needs only the at-rest key configured (DingTalkInstall != nil).func (h *Handler) RegisterDingTalkBYO(w http.ResponseWriter, r *http.Request) {if h.DingTalkInstall == nil {writeError(w, http.StatusServiceUnavailable, "dingtalk integration not enabled")@@ -319,14 +590,19 @@ func (h *Handler) RegisterDingTalkBYO(w http.ResponseWriter, r *http.Request) {if !ok {return}- // Ownership pre-check at the boundary so a wrong agent_id is a clear 404.- if _, err := h.Queries.GetAgentInWorkspace(r.Context(), db.GetAgentInWorkspaceParams{+ // Resolve and authorize the target agent at the boundary so a wrong agent_id+ // is a clear 404 and an unrelated member cannot connect a bot to it.+ agent, err := h.Queries.GetAgentInWorkspace(r.Context(), db.GetAgentInWorkspaceParams{ID: agentUUID,WorkspaceID: wsUUID,- }); err != nil {+ })+ if err != nil {writeError(w, http.StatusNotFound, "agent not found in this workspace")return}+ if !h.canManageAgent(w, r, agent) {+ return+ }initiatorUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")if !ok {return@@ -382,9 +658,11 @@ func (h *Handler) publishDingTalkInstallationCreated(row db.ChannelInstallation,}// RevokeDingTalkInstallation (DELETE /api/workspaces/{id}/dingtalk/installations/{installationId})-// flips status to 'revoked'. Admin-only at the router. The row is preserved for-// audit; a re-install (re-pasting the robot's credentials) flips status back to-// 'active'.+// flips status to 'revoked'. The router requires workspace membership; this+// handler authorizes the bound agent's owner or a workspace owner/admin. The row+// is preserved for audit; a re-install (re-pasting the robot's credentials)+// flips status back to 'active'. An orphaned installation falls back to+// workspace owner/admin-only cleanup because there is no agent owner to resolve.func (h *Handler) RevokeDingTalkInstallation(w http.ResponseWriter, r *http.Request) {if h.DingTalkInstall == nil {writeError(w, http.StatusServiceUnavailable, "dingtalk integration not configured")@@ -404,7 +682,8 @@ func (h *Handler) RevokeDingTalkInstallation(w http.ResponseWriter, r *http.Requ}// Workspace-scoped lookup so one workspace cannot revoke another's// installation by guessing the UUID.- if _, err := h.DingTalkInstall.GetInWorkspace(r.Context(), instUUID, wsUUID); err != nil {+ inst, err := h.DingTalkInstall.GetInWorkspace(r.Context(), instUUID, wsUUID)+ if err != nil {if errors.Is(err, dingtalk.ErrInstallationNotFound) {writeError(w, http.StatusNotFound, "dingtalk installation not found")return@@ -412,6 +691,17 @@ func (h *Handler) RevokeDingTalkInstallation(w http.ResponseWriter, r *http.RequwriteError(w, http.StatusInternalServerError, "failed to load installation")return}+ agent, agentErr := h.Queries.GetAgentInWorkspace(r.Context(), db.GetAgentInWorkspaceParams{+ ID: inst.AgentID,+ WorkspaceID: wsUUID,+ })+ if agentErr != nil {+ if _, ok := h.requireWorkspaceRole(w, r, uuidToString(wsUUID), "dingtalk installation not found", "owner", "admin"); !ok {+ return+ }+ } else if !h.canManageAgent(w, r, agent) {+ return+ }if err := h.DingTalkInstall.Revoke(r.Context(), instUUID); err != nil {writeError(w, http.StatusInternalServerError, "failed to revoke installation")returndiff --git a/server/internal/handler/dingtalk_group_routes_test.go b/server/internal/handler/dingtalk_group_routes_test.godeleted file mode 100644index a9fa2a87f2..0000000000--- a/server/internal/handler/dingtalk_group_routes_test.go+++ /dev/null@@ -1,790 +0,0 @@-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 channel_user_binding WHERE installation_id = $1`, installationID)- _, _ = testPool.Exec(context.Background(), `DELETE FROM channel_binding_token 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) {- fx := 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- var regularMemberID string- if err := testPool.QueryRow(context.Background(), `- INSERT INTO "user" (name, email)- VALUES ('DingTalk installation list member', '[email protected]')- RETURNING id- `).Scan(®ularMemberID); err != nil {- t.Fatalf("create regular member for DingTalk installation listing: %v", err)- }- if _, err := testPool.Exec(context.Background(), `- INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')- `, testWorkspaceID, regularMemberID); err != nil {- t.Fatalf("add regular member for DingTalk installation listing: %v", err)- }- var adminMemberID string- if err := testPool.QueryRow(context.Background(), `- INSERT INTO "user" (name, email)- VALUES ('DingTalk installation list admin', '[email protected]')- RETURNING id- `).Scan(&adminMemberID); err != nil {- t.Fatalf("create admin for DingTalk installation listing: %v", err)- }- if _, err := testPool.Exec(context.Background(), `- INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'admin')- `, testWorkspaceID, adminMemberID); err != nil {- t.Fatalf("add admin for DingTalk installation listing: %v", err)- }- t.Cleanup(func() {- _, _ = testPool.Exec(context.Background(), `DELETE FROM member WHERE workspace_id = $1 AND user_id IN ($2, $3)`, testWorkspaceID, regularMemberID, adminMemberID)- _, _ = testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id IN ($1, $2)`, regularMemberID, adminMemberID)- })- if _, err := testPool.Exec(context.Background(), `- INSERT INTO channel_user_binding (- workspace_id, multica_user_id, installation_id,- channel_type, channel_user_id- ) VALUES- ($1, $2, $3, 'dingtalk', 'staff-current-member'),- ($1, $4, $3, 'dingtalk', 'staff-regular-member'),- ($1, $5, $3, 'dingtalk', 'staff-admin-member')- `, testWorkspaceID, testUserID, fx.installationID, regularMemberID, adminMemberID); err != nil {- t.Fatalf("seed member-scoped DingTalk bindings: %v", err)- }-- req := requestWithRouteParams(- newRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/dingtalk/installations", nil),- testWorkspaceID,- "",- )- ownerMember, err := testHandler.Queries.GetMemberByUserAndWorkspace(context.Background(), db.GetMemberByUserAndWorkspaceParams{- UserID: parseUUID(testUserID),- WorkspaceID: parseUUID(testWorkspaceID),- })- if err != nil {- t.Fatalf("load owner member context: %v", err)- }- req = req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, ownerMember))- 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"`- Installations []DingTalkInstallationResponse `json:"installations"`- }- 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")- }- var found *DingTalkInstallationResponse- for i := range body.Installations {- if body.Installations[i].ID == fx.installationID {- found = &body.Installations[i]- break- }- }- if found == nil {- t.Fatalf("configured installations omitted fixture %s: %+v", fx.installationID, body.Installations)- }- if len(found.BoundDingTalkUserIDs) != 1 || found.BoundDingTalkUserIDs[0] != "staff-current-member" {- t.Fatalf("member-scoped DingTalk ids = %v, want [staff-current-member]", found.BoundDingTalkUserIDs)- }-- lockTx, err := testPool.Begin(context.Background())- if err != nil {- t.Fatalf("begin controlled DingTalk binding-query failure: %v", err)- }- t.Cleanup(func() { _ = lockTx.Rollback(context.Background()) })- if _, err := lockTx.Exec(context.Background(), `LOCK TABLE channel_user_binding IN ACCESS EXCLUSIVE MODE`); err != nil {- _ = lockTx.Rollback(context.Background())- t.Fatalf("lock DingTalk bindings for controlled query failure: %v", err)- }- errorReq := requestWithRouteParams(- newRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/dingtalk/installations", nil),- testWorkspaceID,- "",- )- errorReq = errorReq.WithContext(middleware.SetMemberContext(errorReq.Context(), testWorkspaceID, ownerMember))- errorCtx, cancelErrorRequest := context.WithTimeout(errorReq.Context(), 250*time.Millisecond)- errorReq = errorReq.WithContext(errorCtx)- errorRec := httptest.NewRecorder()- testHandler.ListDingTalkInstallations(errorRec, errorReq)- cancelErrorRequest()- if err := lockTx.Rollback(context.Background()); err != nil {- t.Fatalf("release controlled DingTalk binding lock: %v", err)- }- if errorRec.Code != http.StatusInternalServerError || !strings.Contains(errorRec.Body.String(), "failed to list dingtalk user bindings") {- t.Fatalf("binding query failure status = %d, want 500 without fallback: %s", errorRec.Code, errorRec.Body.String())- }-- router := chi.NewRouter()- router.Route("/api/workspaces/{id}", func(r chi.Router) {- r.Use(middleware.RequireWorkspaceMemberFromURL(testHandler.Queries, "id"))- r.Get("/dingtalk/installations", testHandler.ListDingTalkInstallations)- })- memberReq := httptest.NewRequest(- http.MethodGet,- "/api/workspaces/"+testWorkspaceID+"/dingtalk/installations",- nil,- )- memberReq.Header.Set("X-User-ID", regularMemberID)- memberRec := httptest.NewRecorder()- router.ServeHTTP(memberRec, memberReq)- if memberRec.Code != http.StatusOK {- t.Fatalf("regular member installations status = %d: %s", memberRec.Code, memberRec.Body.String())- }- if !strings.Contains(memberRec.Body.String(), fx.installationID) {- t.Fatalf("regular member could not see connected bot: %s", memberRec.Body.String())- }- for _, forbidden := range []string{"bound_dingtalk_user_ids", "staff-regular-member"} {- if strings.Contains(memberRec.Body.String(), forbidden) {- t.Fatalf("regular member installation response leaked %q: %s", forbidden, memberRec.Body.String())- }- }-- adminReq := httptest.NewRequest(- http.MethodGet,- "/api/workspaces/"+testWorkspaceID+"/dingtalk/installations",- nil,- )- adminReq.Header.Set("X-User-ID", adminMemberID)- adminRec := httptest.NewRecorder()- router.ServeHTTP(adminRec, adminReq)- if adminRec.Code != http.StatusOK {- t.Fatalf("admin installations status = %d: %s", adminRec.Code, adminRec.Body.String())- }- if !strings.Contains(adminRec.Body.String(), `"bound_dingtalk_user_ids":["staff-admin-member"]`) {- t.Fatalf("admin installation response omitted its DingTalk identity: %s", adminRec.Body.String())- }- })-}--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/dingtalk_test.go b/server/internal/handler/dingtalk_test.goindex 6293e5de65..b81ddf271a 100644--- a/server/internal/handler/dingtalk_test.go+++ b/server/internal/handler/dingtalk_test.go@@ -2,16 +2,761 @@ package handlerimport ("context"+ "encoding/json""net/http""net/http/httptest""testing"+ "time"++ "github.com/go-chi/chi/v5""github.com/multica-ai/multica/server/internal/events"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/testutil"+ "github.com/multica-ai/multica/server/internal/util/secretbox"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")+func wireDingTalkInstallService(t *testing.T) {+ t.Helper()+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ box, err := secretbox.New(make([]byte, secretbox.KeySize))+ if err != nil {+ t.Fatalf("secretbox.New: %v", err)+ }+ service, err := dingtalkintegration.NewInstallService(testHandler.Queries, testPool, box, nil)+ if err != nil {+ t.Fatalf("NewInstallService: %v", err)+ }+ previous := testHandler.DingTalkInstall+ testHandler.DingTalkInstall = service+ t.Cleanup(func() { testHandler.DingTalkInstall = previous })+}++type dingTalkAgentPermissionCase struct {+ name string+ userID string+ ownsAgent bool+ denyStatus int+}++func createDingTalkNonMember(t *testing.T, email string) string {+ t.Helper()+ var userID string+ if err := testPool.QueryRow(context.Background(), `+INSERT INTO "user" (name, email) VALUES ('DingTalk non-member', $1) RETURNING id+`, email).Scan(&userID); err != nil {+ t.Fatalf("create DingTalk non-member: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID)+ })+ return userID+}++func dingTalkAgentPermissionCases(t *testing.T, prefix, agentOwnerID, memberID string) []dingTalkAgentPermissionCase {+ t.Helper()+ adminID := createPermissionTestAdmin(t, prefix+"[email protected]")+ nonMemberID := createDingTalkNonMember(t, prefix+"[email protected]")+ return []dingTalkAgentPermissionCase{+ {name: "workspace owner, not agent owner", userID: testUserID},+ {name: "workspace owner, agent owner", userID: testUserID, ownsAgent: true},+ {name: "workspace admin, not agent owner", userID: adminID},+ {name: "workspace admin, agent owner", userID: adminID, ownsAgent: true},+ {name: "workspace member, agent owner", userID: agentOwnerID, ownsAgent: true},+ {name: "workspace member, not agent owner", userID: memberID, denyStatus: http.StatusForbidden},+ {name: "non-member, agent owner", userID: nonMemberID, ownsAgent: true, denyStatus: http.StatusNotFound},+ {name: "non-member, not agent owner", userID: nonMemberID, denyStatus: http.StatusNotFound},+ {name: "unauthenticated", denyStatus: http.StatusUnauthorized},+ }+}++func setDingTalkAgentPermissionFixture(t *testing.T, agentID, permissionMode, ownerID string) {+ t.Helper()+ visibility := "private"+ if permissionMode == "public_to" {+ visibility = "workspace"+ }+ if _, err := testPool.Exec(context.Background(), `+UPDATE agent SET owner_id = $2, permission_mode = $3, visibility = $4 WHERE id = $1+`, agentID, ownerID, permissionMode, visibility); err != nil {+ t.Fatalf("update DingTalk permission fixture: %v", err)+ }+}++func setDingTalkAgentViewFixture(t *testing.T, agentID, accessModel, targetMemberID string) {+ t.Helper()+ if _, err := testPool.Exec(context.Background(), `DELETE FROM agent_invocation_target WHERE agent_id = $1`, agentID); err != nil {+ t.Fatalf("clear DingTalk Agent targets: %v", err)+ }+ permissionMode := "private"+ visibility := "private"+ if accessModel != "private" {+ permissionMode = "public_to"+ visibility = "workspace"+ }+ if _, err := testPool.Exec(context.Background(), `+UPDATE agent SET permission_mode = $2, visibility = $3 WHERE id = $1+`, agentID, permissionMode, visibility); err != nil {+ t.Fatalf("update DingTalk Agent access model: %v", err)+ }+ switch accessModel {+ case "public_to_workspace":+ if _, err := testPool.Exec(context.Background(), `+INSERT INTO agent_invocation_target (agent_id, target_type, target_id) VALUES ($1, 'workspace', $2)+`, agentID, testWorkspaceID); err != nil {+ t.Fatalf("add DingTalk workspace target: %v", err)+ }+ case "public_to_member":+ if _, err := testPool.Exec(context.Background(), `+INSERT INTO agent_invocation_target (agent_id, target_type, target_id) VALUES ($1, 'member', $2)+`, agentID, targetMemberID); err != nil {+ t.Fatalf("add DingTalk member target: %v", err)+ }+ }+}++func TestListDingTalkGroupsForAgent_FollowsAgentViewPermissionMatrix(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ agentID, ownerID, unrelatedMemberID := privateAgentTestFixture(t)+ adminID := createPermissionTestAdmin(t, "[email protected]")+ targetMemberID := createPermissionTestMember(t, "[email protected]")+ nonMemberID := createDingTalkNonMember(t, "[email protected]")+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_invocation_target WHERE agent_id = $1`, agentID)+ })++ previousInstall := testHandler.DingTalkInstall+ testHandler.DingTalkInstall = nil+ t.Cleanup(func() { testHandler.DingTalkInstall = previousInstall })++ actors := []struct {+ name string+ userID string+ ownsAgent bool+ }{+ {name: "workspace owner, not agent owner", userID: testUserID},+ {name: "workspace owner, agent owner", userID: testUserID, ownsAgent: true},+ {name: "workspace admin, not agent owner", userID: adminID},+ {name: "workspace admin, agent owner", userID: adminID, ownsAgent: true},+ {name: "workspace member, agent owner", userID: ownerID, ownsAgent: true},+ {name: "targeted member", userID: targetMemberID},+ {name: "unrelated member", userID: unrelatedMemberID},+ {name: "non-member", userID: nonMemberID},+ {name: "unauthenticated"},+ }+ accessModels := []struct {+ name string+ want map[string]int+ }{+ {+ name: "private",+ want: map[string]int{+ "workspace owner, not agent owner": http.StatusOK, "workspace owner, agent owner": http.StatusOK,+ "workspace admin, not agent owner": http.StatusOK, "workspace admin, agent owner": http.StatusOK,+ "workspace member, agent owner": http.StatusOK, "targeted member": http.StatusForbidden,+ "unrelated member": http.StatusForbidden, "non-member": http.StatusForbidden,+ "unauthenticated": http.StatusUnauthorized,+ },+ },+ {+ name: "public_to_workspace",+ want: map[string]int{+ "workspace owner, not agent owner": http.StatusOK, "workspace owner, agent owner": http.StatusOK,+ "workspace admin, not agent owner": http.StatusOK, "workspace admin, agent owner": http.StatusOK,+ "workspace member, agent owner": http.StatusOK, "targeted member": http.StatusOK,+ "unrelated member": http.StatusOK, "non-member": http.StatusForbidden,+ "unauthenticated": http.StatusUnauthorized,+ },+ },+ {+ name: "public_to_member",+ want: map[string]int{+ "workspace owner, not agent owner": http.StatusOK, "workspace owner, agent owner": http.StatusOK,+ "workspace admin, not agent owner": http.StatusOK, "workspace admin, agent owner": http.StatusOK,+ "workspace member, agent owner": http.StatusOK, "targeted member": http.StatusOK,+ "unrelated member": http.StatusForbidden, "non-member": http.StatusForbidden,+ "unauthenticated": http.StatusUnauthorized,+ },+ },+ }++ for _, accessModel := range accessModels {+ setDingTalkAgentViewFixture(t, agentID, accessModel.name, targetMemberID)+ for _, actor := range actors {+ t.Run(accessModel.name+"/"+actor.name, func(t *testing.T) {+ targetOwnerID := ownerID+ if actor.ownsAgent && actor.userID != "" {+ targetOwnerID = actor.userID+ }+ if _, err := testPool.Exec(context.Background(), `UPDATE agent SET owner_id = $2 WHERE id = $1`, agentID, targetOwnerID); err != nil {+ t.Fatalf("update DingTalk Agent owner: %v", err)+ }+ req := newRequestAs(actor.userID, http.MethodGet, "/api/agents/"+agentID+"/dingtalk/groups", nil)+ req = withURLParams(req, "id", agentID)+ w := httptest.NewRecorder()+ testHandler.ListDingTalkGroupsForAgent(w, req)+ if want := accessModel.want[actor.name]; w.Code != want {+ t.Fatalf("ListDingTalkGroupsForAgent: want %d, got %d: %s", want, w.Code, w.Body.String())+ }+ })+ }+ }+}++func TestListDingTalkSettingsData_FollowsAgentViewPermissionMatrix(t *testing.T) {+ wireDingTalkInstallService(t)+ agentID, ownerID, unrelatedMemberID := privateAgentTestFixture(t)+ adminID := createPermissionTestAdmin(t, "[email protected]")+ targetMemberID := createPermissionTestMember(t, "[email protected]")+ nonMemberID := createDingTalkNonMember(t, "[email protected]")+ installationID := dbfx.Insert(t, "channel_installation", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "agent_id": agentID,+ "channel_type": "dingtalk",+ "config": []byte(`{"app_id":"dingtalk-settings-view","group_titles":{"cid-settings-view":"Settings group"},"group_bot_names":{"cid-settings-view":"Settings Bot"}}`),+ "installer_user_id": testUserID,+ "status": "active",+ })+ if _, err := testPool.Exec(context.Background(), `+INSERT INTO dingtalk_group_presence (+ workspace_id, installation_id, conversation_id, conversation_title,+ bot_name, last_active_at, mention_count+) VALUES ($1, $2, 'cid-settings-view', 'Settings group', 'Settings Bot', $3, 1)+`, testWorkspaceID, installationID, time.Now().UTC()); err != nil {+ t.Fatalf("seed DingTalk presence: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM dingtalk_group_presence WHERE installation_id = $1`, installationID)+ _, _ = testPool.Exec(context.Background(), `DELETE FROM dingtalk_bot_identity WHERE installation_id = $1`, installationID)+ })++ actors := []struct {+ name string+ userID string+ ownsAgent bool+ }{+ {name: "workspace owner, not agent owner", userID: testUserID},+ {name: "workspace owner, agent owner", userID: testUserID, ownsAgent: true},+ {name: "workspace admin, not agent owner", userID: adminID},+ {name: "workspace admin, agent owner", userID: adminID, ownsAgent: true},+ {name: "workspace member, agent owner", userID: ownerID, ownsAgent: true},+ {name: "targeted member", userID: targetMemberID},+ {name: "unrelated member", userID: unrelatedMemberID},+ {name: "non-member", userID: nonMemberID},+ {name: "unauthenticated"},+ }+ accessModels := []struct {+ name string+ visible map[string]bool+ }{+ {+ name: "private",+ visible: map[string]bool{+ "workspace owner, not agent owner": true, "workspace owner, agent owner": true,+ "workspace admin, not agent owner": true, "workspace admin, agent owner": true,+ "workspace member, agent owner": true,+ },+ },+ {+ name: "public_to_workspace",+ visible: map[string]bool{+ "workspace owner, not agent owner": true, "workspace owner, agent owner": true,+ "workspace admin, not agent owner": true, "workspace admin, agent owner": true,+ "workspace member, agent owner": true, "targeted member": true,+ "unrelated member": true,+ },+ },+ {+ name: "public_to_member",+ visible: map[string]bool{+ "workspace owner, not agent owner": true, "workspace owner, agent owner": true,+ "workspace admin, not agent owner": true, "workspace admin, agent owner": true,+ "workspace member, agent owner": true, "targeted member": true,+ },+ },+ }++ for _, accessModel := range accessModels {+ setDingTalkAgentViewFixture(t, agentID, accessModel.name, targetMemberID)+ for _, actor := range actors {+ t.Run(accessModel.name+"/"+actor.name, func(t *testing.T) {+ targetOwnerID := ownerID+ if actor.ownsAgent && actor.userID != "" {+ targetOwnerID = actor.userID+ }+ if _, err := testPool.Exec(context.Background(), `UPDATE agent SET owner_id = $2 WHERE id = $1`, agentID, targetOwnerID); err != nil {+ t.Fatalf("update DingTalk Agent owner: %v", err)+ }++ installReq := newRequestAs(actor.userID, http.MethodGet,+ "/api/workspaces/"+testWorkspaceID+"/dingtalk/installations", nil)+ installReq = withURLParams(installReq, "id", testWorkspaceID)+ installRec := httptest.NewRecorder()+ testHandler.ListDingTalkInstallations(installRec, installReq)++ groupReq := newRequestAs(actor.userID, http.MethodGet,+ "/api/workspaces/"+testWorkspaceID+"/dingtalk/groups", nil)+ groupReq = withURLParams(groupReq, "id", testWorkspaceID)+ groupRec := httptest.NewRecorder()+ testHandler.ListDingTalkGroups(groupRec, groupReq)++ wantStatus := http.StatusOK+ if actor.userID == "" {+ wantStatus = http.StatusUnauthorized+ } else if actor.name == "non-member" {+ wantStatus = http.StatusNotFound+ }+ if installRec.Code != wantStatus || groupRec.Code != wantStatus {+ t.Fatalf("Settings status: installations=%d groups=%d, want %d", installRec.Code, groupRec.Code, wantStatus)+ }+ if wantStatus != http.StatusOK {+ return+ }++ var installations struct {+ Installations []DingTalkInstallationResponse `json:"installations"`+ }+ if err := json.Unmarshal(installRec.Body.Bytes(), &installations); err != nil {+ t.Fatal(err)+ }+ var groups ListDingTalkGroupsResponse+ if err := json.Unmarshal(groupRec.Body.Bytes(), &groups); err != nil {+ t.Fatal(err)+ }+ wantCount := 0+ if accessModel.visible[actor.name] {+ wantCount = 1+ }+ if len(installations.Installations) != wantCount || len(groups.Groups) != wantCount {+ t.Fatalf("Settings visibility: installations=%+v groups=%+v, want count %d", installations.Installations, groups.Groups, wantCount)+ }+ if wantCount == 1 && installations.Installations[0].ID != installationID {+ t.Fatalf("installation id = %s, want %s", installations.Installations[0].ID, installationID)+ }+ })+ }+ }+}++func TestListDingTalkGroupsInactivePaginationAuthorizesInstallationBeforeCursor(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ wireDingTalkInstallService(t)+ agentID, agentOwnerID, unrelatedMemberID := privateAgentTestFixture(t)+ installationID := dbfx.Insert(t, "channel_installation", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "agent_id": agentID,+ "channel_type": "dingtalk",+ "config": []byte(`{"app_id":"dingtalk-private-inactive-pagination"}`),+ "installer_user_id": testUserID,+ "status": "active",+ })+ for _, group := range []struct {+ conversationID string+ conversationTitle string+ }{+ {conversationID: "cid-private-inactive-a", conversationTitle: "Private inactive A"},+ {conversationID: "cid-private-inactive-b", conversationTitle: "Private inactive B"},+ } {+ dbfx.InsertNoID(t, "dingtalk_group_presence", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "installation_id": installationID,+ "conversation_id": group.conversationID,+ "conversation_title": group.conversationTitle,+ "last_active_at": testutil.Raw("now() - interval '91 days'"),+ "mention_count": 1,+ }, "installation_id = $1 AND conversation_id = $2", installationID, group.conversationID)+ }+ otherAgentID := dbfx.Agent(t, "dingtalk-private-pagination-other-agent", handlerTestRuntimeID(t), testutil.Cols{+ "owner_id": testUserID,+ })+ otherInstallationID := dbfx.Insert(t, "channel_installation", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "agent_id": otherAgentID,+ "channel_type": "dingtalk",+ "config": []byte(`{"app_id":"dingtalk-private-pagination-other-installation"}`),+ "installer_user_id": testUserID,+ "status": "active",+ })+ for _, conversationID := range []string{"cid-private-other-a", "cid-private-other-b"} {+ dbfx.InsertNoID(t, "dingtalk_group_presence", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "installation_id": otherInstallationID,+ "conversation_id": conversationID,+ "conversation_title": conversationID,+ "last_active_at": testutil.Raw("now() - interval '91 days'"),+ "mention_count": 1,+ }, "installation_id = $1 AND conversation_id = $2", otherInstallationID, conversationID)+ }+ revokedAgentID := dbfx.Agent(t, "dingtalk-private-pagination-revoked-agent", handlerTestRuntimeID(t), testutil.Cols{+ "owner_id": agentOwnerID,+ })+ revokedInstallationID := dbfx.Insert(t, "channel_installation", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "agent_id": revokedAgentID,+ "channel_type": "dingtalk",+ "config": []byte(`{"app_id":"dingtalk-private-pagination-revoked"}`),+ "installer_user_id": testUserID,+ "status": "revoked",+ })++ request := func(userID, requestedInstallationID, suffix string) *http.Request {+ path := "/api/workspaces/" + testWorkspaceID + "/dingtalk/groups?activity=inactive&installation_id=" + requestedInstallationID + suffix+ return testutil.WithURLParams(newRequestAs(userID, http.MethodGet, path, nil), "id", testWorkspaceID)+ }++ inaccessible := testutil.Call(t, testHandler.ListDingTalkGroups,+ request(unrelatedMemberID, installationID, "&limit=1&offset=0")).Want(http.StatusOK)+ var inaccessibleBody ListDingTalkGroupsResponse+ inaccessible.JSON(&inaccessibleBody)+ if len(inaccessibleBody.Groups) != 0 || inaccessibleBody.NextOffset != nil {+ t.Fatalf("inaccessible private installation leaked pagination: %+v", inaccessibleBody)+ }+ if _, leaked := inaccessibleBody.InactiveGroupCounts[installationID]; leaked {+ t.Fatalf("inaccessible private installation leaked inactive count: %+v", inaccessibleBody.InactiveGroupCounts)+ }+ if _, leaked := inaccessibleBody.BotIdentities[installationID]; leaked {+ t.Fatalf("inaccessible private installation leaked bot identity: %+v", inaccessibleBody.BotIdentities)+ }+ if _, leaked := inaccessible.Map()["next_offset"]; leaked {+ t.Fatalf("inaccessible private installation serialized next_offset: %s", inaccessible.Text())+ }++ const missingInstallationID = "d1473000-0000-4000-8000-000000000099"+ missing := testutil.Call(t, testHandler.ListDingTalkGroups,+ request(unrelatedMemberID, missingInstallationID, "&limit=1&offset=0")).Want(http.StatusOK)+ if inaccessible.Text() != missing.Text() {+ t.Fatalf("inaccessible and nonexistent installations must be indistinguishable:\ninaccessible: %s\nnonexistent: %s",+ inaccessible.Text(), missing.Text())+ }++ firstPage := testutil.Decode[ListDingTalkGroupsResponse](t, testHandler.ListDingTalkGroups,+ request(agentOwnerID, installationID, "&limit=1&offset=0"), http.StatusOK)+ if len(firstPage.Groups) != 1 || firstPage.NextOffset == nil || *firstPage.NextOffset != 1 {+ t.Fatalf("visible private installation first page = %+v, want one group and next_offset=1", firstPage)+ }+ if firstPage.InactiveGroupCounts[installationID] != 2 {+ t.Fatalf("visible private installation inactive counts = %+v, want %s=2",+ firstPage.InactiveGroupCounts, installationID)+ }++ secondPage := testutil.Decode[ListDingTalkGroupsResponse](t, testHandler.ListDingTalkGroups,+ request(agentOwnerID, installationID, "&limit=1&offset=1"), http.StatusOK)+ if len(secondPage.Groups) != 1 || secondPage.NextOffset != nil {+ t.Fatalf("visible private installation second page = %+v, want one terminal group", secondPage)+ }++ visibleMissing := testutil.Call(t, testHandler.ListDingTalkGroups,+ request(agentOwnerID, missingInstallationID, "&limit=1&offset=0")).Want(http.StatusOK)+ revoked := testutil.Call(t, testHandler.ListDingTalkGroups,+ request(agentOwnerID, revokedInstallationID, "&limit=1&offset=0")).Want(http.StatusOK)+ if revoked.Text() != visibleMissing.Text() {+ t.Fatalf("revoked and nonexistent installations must be indistinguishable:\nrevoked: %s\nnonexistent: %s",+ revoked.Text(), visibleMissing.Text())+ }++ agentRequest := func(requestedInstallationID string) *http.Request {+ path := "/api/agents/" + agentID + "/dingtalk/groups?activity=inactive&installation_id=" + requestedInstallationID + "&limit=1&offset=0"+ return testutil.WithURLParams(newRequestAs(agentOwnerID, http.MethodGet, path, nil), "id", agentID)+ }+ agentPage := testutil.Decode[ListDingTalkGroupsResponse](t, testHandler.ListDingTalkGroupsForAgent,+ agentRequest(installationID), http.StatusOK)+ if len(agentPage.Groups) != 1 || agentPage.NextOffset == nil || *agentPage.NextOffset != 1 {+ t.Fatalf("Agent-scoped own installation page = %+v, want one group and next_offset=1", agentPage)+ }+ wrongAgentInstallation := testutil.Call(t, testHandler.ListDingTalkGroupsForAgent,+ agentRequest(otherInstallationID)).Want(http.StatusOK)+ missingAgentInstallation := testutil.Call(t, testHandler.ListDingTalkGroupsForAgent,+ agentRequest(missingInstallationID)).Want(http.StatusOK)+ if wrongAgentInstallation.Text() != missingAgentInstallation.Text() {+ t.Fatalf("another Agent's installation and a nonexistent installation must be indistinguishable:\nother Agent: %s\nnonexistent: %s",+ wrongAgentInstallation.Text(), missingAgentInstallation.Text())+ }+}++func TestListDingTalkInstallations_OrphanIsAdminOnlyAndMarkedUnavailable(t *testing.T) {+ wireDingTalkInstallService(t)+ agentID, _, memberID := privateAgentTestFixture(t)+ installationID := dbfx.Insert(t, "channel_installation", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "agent_id": agentID,+ "channel_type": "dingtalk",+ "config": []byte(`{"app_id":"dingtalk-orphan"}`),+ "installer_user_id": testUserID,+ "status": "active",+ })+ if _, err := testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agentID); err != nil {+ t.Fatalf("delete DingTalk Agent fixture: %v", err)+ }++ list := func(userID string) []DingTalkInstallationResponse {+ req := newRequestAs(userID, http.MethodGet,+ "/api/workspaces/"+testWorkspaceID+"/dingtalk/installations", nil)+ req = withURLParams(req, "id", testWorkspaceID)+ rec := httptest.NewRecorder()+ testHandler.ListDingTalkInstallations(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("ListDingTalkInstallations status = %d: %s", rec.Code, rec.Body.String())+ }+ var response struct {+ Installations []DingTalkInstallationResponse `json:"installations"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ return response.Installations+ }++ adminRows := list(testUserID)+ found := false+ for _, row := range adminRows {+ if row.ID == installationID {+ found = true+ if row.AgentAvailable {+ t.Fatal("orphaned installation was marked as having an available Agent")+ }+ }+ }+ if !found {+ t.Fatal("workspace owner could not see orphaned installation for cleanup")+ }+ for _, row := range list(memberID) {+ if row.ID == installationID {+ t.Fatal("ordinary member could see orphaned installation")+ }+ }+}++func TestRegisterDingTalkBYO_AuthorizesAgentOwnerAndAdmins(t *testing.T) {+ wireDingTalkInstallService(t)+ agentID, ownerID, memberID := privateAgentTestFixture(t)+ cases := dingTalkAgentPermissionCases(t, "dingtalk-register", ownerID, memberID)++ register := func(userID string) *httptest.ResponseRecorder {+ req := newRequestAs(userID, http.MethodPost,+ "/api/workspaces/"+testWorkspaceID+"/dingtalk/install/byo?agent_id="+agentID, nil)+ req = withURLParams(req, "id", testWorkspaceID)+ w := httptest.NewRecorder()+ testHandler.RegisterDingTalkBYO(w, req)+ return w+ }++ for _, permissionMode := range []string{"private", "public_to"} {+ for _, tc := range cases {+ t.Run(permissionMode+"/"+tc.name, func(t *testing.T) {+ targetOwnerID := ownerID+ if tc.ownsAgent && tc.userID != "" {+ targetOwnerID = tc.userID+ }+ setDingTalkAgentPermissionFixture(t, agentID, permissionMode, targetOwnerID)+ want := tc.denyStatus+ if want == 0 {+ // Authorized requests reach body validation; the empty body is+ // deliberate so this test never contacts DingTalk.+ want = http.StatusBadRequest+ }+ w := register(tc.userID)+ if w.Code != want {+ t.Fatalf("RegisterDingTalkBYO: want %d, got %d: %s", want, w.Code, w.Body.String())+ }+ })+ }+ }+}++func TestForgetDingTalkGroup_AdminOnlyAndKeepsInstallation(t *testing.T) {+ wireDingTalkInstallService(t)+ agentID, _, memberID := privateAgentTestFixture(t)+ installationID := dbfx.Insert(t, "channel_installation", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "agent_id": agentID,+ "channel_type": "dingtalk",+ "config": []byte(`{"app_id":"dingtalk-forget"}`),+ "installer_user_id": testUserID,+ "status": "active",+ })+ if _, err := testPool.Exec(context.Background(), `+INSERT INTO dingtalk_group_presence (+ workspace_id, installation_id, conversation_id, conversation_title+) VALUES ($1, $2, 'cid/forget', 'Forget me')+`, testWorkspaceID, installationID); err != nil {+ t.Fatal(err)+ }+ if _, err := testPool.Exec(context.Background(), `+INSERT INTO dingtalk_bot_identity (+ workspace_id, installation_id, bot_name+) VALUES ($1, $2, 'Persistent Bot')+`, testWorkspaceID, installationID); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM dingtalk_group_presence WHERE installation_id = $1`, installationID)+ _, _ = testPool.Exec(context.Background(), `DELETE FROM dingtalk_bot_identity WHERE installation_id = $1`, installationID)+ })++ forget := func(userID string) int {+ router := chi.NewRouter()+ router.Delete(+ "/api/workspaces/{id}/dingtalk/installations/{installationId}/groups/{conversationId}",+ testHandler.ForgetDingTalkGroup,+ )+ req := newRequestAs(userID, http.MethodDelete,+ "/api/workspaces/"+testWorkspaceID+"/dingtalk/installations/"+installationID+"/groups/cid%2Fforget", nil)+ rec := httptest.NewRecorder()+ router.ServeHTTP(rec, req)+ return rec.Code+ }+ if got := forget(memberID); got != http.StatusForbidden {+ t.Fatalf("member forget status = %d, want 403", got)+ }+ if got := forget(testUserID); got != http.StatusNoContent {+ t.Fatalf("owner forget status = %d, want 204", got)+ }+ var presenceCount, identityCount, installationCount int+ var botName string+ if err := testPool.QueryRow(context.Background(), `+SELECT+ (SELECT count(*) FROM dingtalk_group_presence WHERE installation_id = $1),+ (SELECT count(*) FROM dingtalk_bot_identity WHERE installation_id = $1),+ (SELECT bot_name FROM dingtalk_bot_identity WHERE installation_id = $1),+ (SELECT count(*) FROM channel_installation WHERE id = $1)+`, installationID).Scan(&presenceCount, &identityCount, &botName, &installationCount); err != nil {+ t.Fatal(err)+ }+ if presenceCount != 0 || identityCount != 1 || botName != "Persistent Bot" || installationCount != 1 {+ t.Fatalf("forget state = presence %d identity %d/%q installation %d", presenceCount, identityCount, botName, installationCount)+ }++ listReq := newRequestAs(testUserID, http.MethodGet,+ "/api/workspaces/"+testWorkspaceID+"/dingtalk/groups", nil)+ listReq = withURLParams(listReq, "id", testWorkspaceID)+ listRec := httptest.NewRecorder()+ testHandler.ListDingTalkGroups(listRec, listReq)+ if listRec.Code != http.StatusOK {+ t.Fatalf("list groups after forget status = %d: %s", listRec.Code, listRec.Body.String())+ }+ var listing ListDingTalkGroupsResponse+ if err := json.Unmarshal(listRec.Body.Bytes(), &listing); err != nil {+ t.Fatal(err)+ }+ forgottenGroupPresent := false+ for _, group := range listing.Groups {+ for _, bot := range group.Bots {+ forgottenGroupPresent = forgottenGroupPresent || bot.InstallationID == installationID+ }+ }+ if forgottenGroupPresent || listing.BotIdentities[installationID].BotName != "Persistent Bot" {+ t.Fatalf("listing after forget = groups %+v identities %+v", listing.Groups, listing.BotIdentities)+ }+}++func TestRevokeDingTalkInstallation_AuthorizesAgentOwnerAndAdmins(t *testing.T) {+ wireDingTalkInstallService(t)+ agentID, ownerID, memberID := privateAgentTestFixture(t)+ cases := dingTalkAgentPermissionCases(t, "dingtalk-revoke", ownerID, memberID)++ seedInstallation := func(agentID, appID string) string {+ if _, err := testPool.Exec(context.Background(),+ `DELETE FROM channel_installation WHERE workspace_id = $1 AND agent_id = $2 AND channel_type = 'dingtalk'`,+ testWorkspaceID, agentID); err != nil {+ t.Fatalf("clear prior DingTalk installation: %v", err)+ }+ return dbfx.Insert(t, "channel_installation", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "agent_id": agentID,+ "channel_type": "dingtalk",+ "config": []byte(`{"app_id":"` + appID + `"}`),+ "installer_user_id": testUserID,+ "status": "active",+ })+ }+ revoke := func(userID, installationID string) int {+ req := newRequestAs(userID, http.MethodDelete,+ "/api/workspaces/"+testWorkspaceID+"/dingtalk/installations/"+installationID, nil)+ req = withURLParams(req, "id", testWorkspaceID, "installationId", installationID)+ w := httptest.NewRecorder()+ testHandler.RevokeDingTalkInstallation(w, req)+ return w.Code+ }++ for _, permissionMode := range []string{"private", "public_to"} {+ for _, tc := range cases {+ t.Run(permissionMode+"/"+tc.name, func(t *testing.T) {+ targetOwnerID := ownerID+ if tc.ownsAgent && tc.userID != "" {+ targetOwnerID = tc.userID+ }+ setDingTalkAgentPermissionFixture(t, agentID, permissionMode, targetOwnerID)+ want := tc.denyStatus+ if want == 0 {+ want = http.StatusNoContent+ }+ if code := revoke(tc.userID, seedInstallation(agentID, "dingtalk-permission-matrix")); code != want {+ t.Fatalf("RevokeDingTalkInstallation: want %d, got %d", want, code)+ }+ })+ }+ }+}++func TestRevokeDingTalkInstallation_OrphanCleanableByAdminNotMember(t *testing.T) {+ wireDingTalkInstallService(t)+ _, _, memberID := privateAgentTestFixture(t)+ adminID := createPermissionTestAdmin(t, "[email protected]")+ nonMemberID := createDingTalkNonMember(t, "[email protected]")+ const orphanAgentID = "d1473000-0000-4000-8000-0000000000aa"++ seedOrphan := func(appID string) string {+ if _, err := testPool.Exec(context.Background(),+ `DELETE FROM channel_installation WHERE workspace_id = $1 AND agent_id = $2 AND channel_type = 'dingtalk'`,+ testWorkspaceID, orphanAgentID); err != nil {+ t.Fatalf("clear prior orphan DingTalk installation: %v", err)+ }+ return dbfx.Insert(t, "channel_installation", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "agent_id": orphanAgentID,+ "channel_type": "dingtalk",+ "config": []byte(`{"app_id":"` + appID + `"}`),+ "installer_user_id": testUserID,+ "status": "active",+ })+ }+ revoke := func(userID, installationID string) int {+ req := newRequestAs(userID, http.MethodDelete,+ "/api/workspaces/"+testWorkspaceID+"/dingtalk/installations/"+installationID, nil)+ req = withURLParams(req, "id", testWorkspaceID, "installationId", installationID)+ w := httptest.NewRecorder()+ testHandler.RevokeDingTalkInstallation(w, req)+ return w.Code+ }++ for _, tc := range []struct {+ name string+ userID string+ want int+ }{+ {name: "workspace owner", userID: testUserID, want: http.StatusNoContent},+ {name: "workspace admin", userID: adminID, want: http.StatusNoContent},+ {name: "workspace member", userID: memberID, want: http.StatusForbidden},+ {name: "non-member", userID: nonMemberID, want: http.StatusNotFound},+ {name: "unauthenticated", want: http.StatusUnauthorized},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if code := revoke(tc.userID, seedOrphan("dingtalk-orphan-permission-matrix")); code != tc.want {+ t.Fatalf("orphan revoke: want %d, got %d", tc.want, code)+ }+ })+ }+}+func TestPublishDingTalkInstallationCreated(t *testing.T) {bus := events.New()h := &Handler{Bus: bus}@@ -50,12 +795,22 @@ func TestRedeemDingTalkBindingTokenPublishesAccountBindingUpdateAfterCommit(t *tt.Skip("database not available")}- fx := newDingTalkGroupRouteHandlerFixture(t)+ agentID := createHandlerTestAgent(t, "DingTalk binding event Agent", nil)+ installationID := dbfx.Insert(t, "channel_installation", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "agent_id": agentID,+ "channel_type": "dingtalk",+ "config": []byte(`{"app_id":"handler-binding-event"}`),+ "installer_user_id": testUserID,+ })+ dbfx.Cleanup(t, `DELETE FROM channel_user_binding WHERE installation_id = $1`, installationID)+ dbfx.Cleanup(t, `DELETE FROM channel_binding_token WHERE installation_id = $1`, installationID)+bindingService := dingtalkintegration.NewBindingTokenService(testHandler.Queries, testPool)token, err := bindingService.Mint(context.Background(),parseUUID(testWorkspaceID),- parseUUID(fx.installationID),+ parseUUID(installationID),"staff-binding-event",)if err != nil {@@ -82,7 +837,7 @@ func TestRedeemDingTalkBindingTokenPublishesAccountBindingUpdateAfterCommit(t *tbindingAtEvent, queryErr = testHandler.Queries.GetChannelUserBindingByUserID(context.Background(),db.GetChannelUserBindingByUserIDParams{- InstallationID: parseUUID(fx.installationID),+ InstallationID: parseUUID(installationID),ChannelUserID: "staff-binding-event",},)@@ -111,7 +866,171 @@ func TestRedeemDingTalkBindingTokenPublishesAccountBindingUpdateAfterCommit(t *tt.Errorf("event envelope = %+v", published)}payload, ok := published.Payload.(map[string]any)- if !ok || payload["id"] != fx.installationID {- t.Errorf("payload = %v, want installation id %s", published.Payload, fx.installationID)+ if !ok || payload["id"] != installationID {+ t.Errorf("payload = %v, want installation id %s", published.Payload, installationID)+ }+}++func TestListDingTalkGroupsAggregatesConnectedBots(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("handler database unavailable")+ }+ const (+ installOne = "d1473000-0000-4000-8000-000000000011"+ installTwo = "d1473000-0000-4000-8000-000000000012"+ agentOne = "d1473000-0000-4000-8000-000000000021"+ agentTwo = "d1473000-0000-4000-8000-000000000022"+ sessionID = "d1473000-0000-4000-8000-000000000031"+ )+ previousInstall := testHandler.DingTalkInstall+ testHandler.DingTalkInstall = &dingtalkintegration.InstallService{}+ t.Cleanup(func() { testHandler.DingTalkInstall = previousInstall })+ clean := func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM dingtalk_group_presence WHERE installation_id = ANY($1::uuid[])`, []string{installOne, installTwo})+ _, _ = testPool.Exec(context.Background(), `DELETE FROM dingtalk_bot_identity WHERE installation_id = ANY($1::uuid[])`, []string{installOne, installTwo})+ _, _ = testPool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, sessionID)+ _, _ = testPool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = ANY($1::uuid[])`, []string{installOne, installTwo})+ }+ clean()+ t.Cleanup(clean)+ for _, fixture := range []struct {+ id string+ agentID string+ appID string+ name string+ title string+ status string+ }{+ {id: installOne, agentID: agentOne, appID: "handler-group-one", name: "Release Bot", title: "", status: "active"},+ {id: installTwo, agentID: agentTwo, appID: "handler-group-two", name: "Support Bot", title: "Platform", status: "active"},+ } {+ if _, err := testPool.Exec(context.Background(), `+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+)+`, fixture.id, testWorkspaceID, fixture.agentID, fixture.appID, testUserID, fixture.status); err != nil {+ t.Fatalf("seed group bot: %v", err)+ }+ if _, err := testPool.Exec(context.Background(), `+INSERT INTO dingtalk_group_presence (+ workspace_id, installation_id, conversation_id, conversation_title,+ bot_name, last_active_at, mention_count+) VALUES ($1, $2, 'cid-shared', $3, $4, now(), $5)+`, testWorkspaceID, fixture.id, fixture.title, fixture.name, map[string]int64{installOne: 2, installTwo: 1}[fixture.id]); err != nil {+ t.Fatalf("seed group presence: %v", err)+ }+ }+ if _, err := testPool.Exec(context.Background(), `+INSERT INTO dingtalk_group_presence (+ workspace_id, installation_id, conversation_id, conversation_title+) VALUES+ ($1, $2, 'cid-z', 'Platform'),+ ($1, $2, 'cid-untitled', '')+`, testWorkspaceID, installOne); err != nil {+ t.Fatalf("seed additional groups: %v", err)+ }++ rctx := chi.NewRouteContext()+ rctx.URLParams.Add("id", testWorkspaceID)+ req := newRequestAs(testUserID, http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/dingtalk/groups", nil)+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))+ rec := httptest.NewRecorder()+ testHandler.ListDingTalkGroups(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("list groups status = %d: %s", rec.Code, rec.Body.String())+ }+ var response struct {+ Groups []DingTalkGroupResponse `json:"groups"`+ GroupDiscoverySupported bool `json:"group_discovery_supported"`+ InactiveGroupCounts map[string]int64 `json:"inactive_group_counts"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if !response.GroupDiscoverySupported || len(response.Groups) != 1 || response.Groups[0].ConversationID != "cid-shared" ||+ response.Groups[0].ConversationTitle != "Platform" || len(response.Groups[0].Bots) != 2 {+ t.Fatalf("group response = %+v", response.Groups)}+ if response.Groups[0].Bots[0].BotName != "Release Bot" || response.Groups[0].Bots[1].BotName != "Support Bot" {+ t.Fatalf("group bots = %+v", response.Groups[0].Bots)+ }+ if response.Groups[0].Bots[0].MentionCount != 2 || response.Groups[0].Bots[0].LastActiveAt == "" {+ t.Fatalf("release bot activity = %+v", response.Groups[0].Bots[0])+ }+ if response.Groups[0].Bots[1].MentionCount != 1 || response.Groups[0].Bots[1].LastActiveAt == "" {+ t.Fatalf("support bot activity = %+v", response.Groups[0].Bots[1])+ }+ if response.InactiveGroupCounts[installOne] != 2 {+ t.Fatalf("inactive counts = %+v, want %s=2", response.InactiveGroupCounts, installOne)+ }++ inactiveReq := newRequestAs(testUserID, http.MethodGet,+ "/api/workspaces/"+testWorkspaceID+"/dingtalk/groups?activity=inactive&installation_id="+installOne, nil)+ inactiveReq = inactiveReq.WithContext(context.WithValue(inactiveReq.Context(), chi.RouteCtxKey, rctx))+ inactiveRec := httptest.NewRecorder()+ testHandler.ListDingTalkGroups(inactiveRec, inactiveReq)+ if inactiveRec.Code != http.StatusOK {+ t.Fatalf("list inactive groups status = %d: %s", inactiveRec.Code, inactiveRec.Body.String())+ }+ if err := json.Unmarshal(inactiveRec.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if len(response.Groups) != 2 || response.Groups[0].ConversationID != "cid-z" ||+ response.Groups[1].ConversationID != "cid-untitled" {+ t.Fatalf("inactive groups = %+v", response.Groups)+ }++ agentRec := httptest.NewRecorder()+ testHandler.listDingTalkGroups(agentRec, req, parseUUID(testWorkspaceID), agentOne, nil)+ if agentRec.Code != http.StatusOK {+ t.Fatalf("list Agent groups status = %d: %s", agentRec.Code, agentRec.Body.String())+ }+ if err := json.Unmarshal(agentRec.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if len(response.Groups) != 1 || len(response.Groups[0].Bots) != 1 ||+ response.Groups[0].Bots[0].AgentID != agentOne {+ t.Fatalf("Agent-scoped group response leaked another bot: %+v", response.Groups)+ }+}++func TestListDingTalkGroupsDisabledDeploymentReturnsStableEmptyShape(t *testing.T) {+ rec := httptest.NewRecorder()+ (&Handler{}).ListDingTalkGroups(rec, httptest.NewRequest(http.MethodGet, "/api/workspaces/bad/dingtalk/groups", nil))+ if rec.Code != http.StatusOK || rec.Body.String() != "{\"groups\":[],\"group_discovery_supported\":true,\"inactive_group_counts\":{},\"bot_identities\":{}}\n" {+ t.Fatalf("disabled groups response = %d %q", rec.Code, rec.Body.String())+ }+}++func TestListDingTalkGroupsReturnsInternalErrorOnDatabaseFailure(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("handler database unavailable")+ }+ previousInstall := testHandler.DingTalkInstall+ testHandler.DingTalkInstall = &dingtalkintegration.InstallService{}+ t.Cleanup(func() { testHandler.DingTalkInstall = previousInstall })++ rctx := chi.NewRouteContext()+ rctx.URLParams.Add("id", testWorkspaceID)+ ctx, cancel := context.WithCancel(context.Background())+ ctx = middleware.SetMemberContext(ctx, testWorkspaceID, db.Member{Role: "owner"})+ cancel()+ req := newRequestAs(testUserID, http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/dingtalk/groups", nil)+ req = req.WithContext(context.WithValue(ctx, chi.RouteCtxKey, rctx))+ rec := httptest.NewRecorder()+ testHandler.ListDingTalkGroups(rec, req)+ if rec.Code != http.StatusInternalServerError {+ t.Fatalf("database failure status = %d, want 500: %s", rec.Code, rec.Body.String())+ }++ inactiveReq := newRequestAs(testUserID, http.MethodGet,+ "/api/workspaces/"+testWorkspaceID+"/dingtalk/groups?activity=inactive&installation_id=d1473000-0000-4000-8000-000000000099", nil)+ inactiveReq = inactiveReq.WithContext(ctx)+ testutil.Call(t, func(w http.ResponseWriter, r *http.Request) {+ testHandler.listDingTalkGroups(w, r, parseUUID(testWorkspaceID), "", nil)+ }, inactiveReq).Want(http.StatusInternalServerError)}diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex e8d821521b..522a85cf89 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -54,6 +54,8 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"contact_sales_inquiry": workspaceDeleteKeep,"daemon_connection": workspaceDelete,"daemon_token": workspaceDelete,+ "dingtalk_group_presence": workspaceDelete,+ "dingtalk_bot_identity": workspaceDelete,"dingtalk_group_route": workspaceDelete,"feedback": workspaceDeleteDetach,"github_installation": workspaceDelete,diff --git a/server/internal/integrations/channel/engine/resolvers.go b/server/internal/integrations/channel/engine/resolvers.goindex 729bdf0395..e2bade266c 100644--- a/server/internal/integrations/channel/engine/resolvers.go+++ b/server/internal/integrations/channel/engine/resolvers.go@@ -78,12 +78,9 @@ 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- // RouteRevision is an adapter-owned optimistic fence for platforms that- // route one installation to multiple agents. Zero means no such fence.- RouteRevision int64+ ID pgtype.UUID+ WorkspaceID pgtype.UUID+ AgentID pgtype.UUIDInstallerUserID pgtype.UUIDActive boolPlatform any@@ -113,8 +110,6 @@ type AppendParams struct {SessionID pgtype.UUIDSender pgtype.UUIDInstallationID pgtype.UUID- AgentID pgtype.UUID- RouteRevision int64Message channel.InboundMessageClaimToken pgtype.UUIDMediaPendingSeconds float64@@ -169,15 +164,6 @@ 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")@@ -201,15 +187,6 @@ 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).@@ -338,7 +315,6 @@ type TypingNotifier interface {type ResolverSet struct {Installation InstallationResolverIdentity IdentityResolver- Validated ValidatedInboundResolverDedup DeduperSession SessionBinderMedia MediaResolverdiff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.goindex 90b565c154..ffddc34199 100644--- a/server/internal/integrations/channel/engine/router.go+++ b/server/internal/integrations/channel/engine/router.go@@ -115,10 +115,9 @@ func NewRouter(issues IssueCreator, tasks TaskEnqueuer, reader SessionReader, cfconst 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.+// selected a terminal outcome. The request context may already be cancelled,+// so preserve its values while giving Mark/Release a bounded opportunity to+// commit instead of stranding a claim until stale reclaim.const dedupFinalizeTimeout = time.Secondtype mediaQueueEntry struct {@@ -331,52 +330,37 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe}}- // 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.+ // 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.sessionCreator := identity.UserIDif msg.Source.ChatType == channel.ChatTypeGroup {sessionCreator = inst.InstallerUserID}- refreshChangedRoute := func() (Result, bool, error) {- if set.Validated == nil {- return Result{}, false, ErrRouteChanged- }- 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)+ 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)}- return Result{}, false, nil- }-+ 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.// 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@@ -401,70 +385,19 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channeif resolveMedia {mediaPendingSeconds = r.mediaTimeout.Seconds()}-- 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)+ 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}- break+ return Result{}, finalizeRelease, fmt.Errorf("append user message: %w", err)}// Post-append paths must NOT Release (chat_message + Mark alreadydiff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.goindex 3f7c05e66d..a83c22c6a1 100644--- a/server/internal/integrations/channel/engine/router_test.go+++ b/server/internal/integrations/channel/engine/router_test.go@@ -37,39 +37,6 @@ 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.Mutextoken pgtype.UUID@@ -90,12 +57,9 @@ func (f *fakeDedup) Claim(_ context.Context, _ pgtype.UUID, _ string) (pgtype.UU}return f.token, nil}-func (f *fakeDedup) Mark(ctx context.Context, _ pgtype.UUID, _ string, _ pgtype.UUID) error {+func (f *fakeDedup) Mark(_ 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}@@ -121,17 +85,9 @@ type fakeBinder struct {mu sync.MutexensureID pgtype.UUIDensureErr error- ensureErrs []error- ensureCalls int- ensureParams []EnsureSessionParams- ensureHook func(int)appendResult AppendResultparseIssue boolappendErr error- appendErrs []error- appendCalls int- appended []AppendParams- appendHook func(int)appendDelay time.DurationbindErr errorlastEnsure EnsureSessionParams@@ -139,24 +95,15 @@ type fakeBinder struct {lastBind BindMediaParamspendingFresh intpendingErr error+ ensureHook func()}func (f *fakeBinder) EnsureSession(_ context.Context, p EnsureSessionParams) (pgtype.UUID, error) {- f.mu.Lock()f.lastEnsure = p- 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)+ if f.ensureHook != nil {+ f.ensureHook()}- return f.ensureID, err+ return f.ensureID, f.ensureErr}func (f *fakeBinder) MarkPendingFresh(_ context.Context, _ pgtype.UUID) error {f.mu.Lock()@@ -168,12 +115,7 @@ func (f *fakeBinder) AppendMessage(_ context.Context, p AppendParams) (AppendResf.mu.Lock()delay := f.appendDelayf.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.CommandTextif commandSource == "" {@@ -181,40 +123,12 @@ 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.appendHookf.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()@@ -467,28 +381,26 @@ func p2pMessage(t *testing.T) channel.InboundMessage {}type harness struct {- 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+ router *Router+ inst *fakeInstaller+ ident *fakeIdentity+ 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")}},- validated: &fakeValidatedInbound{},- 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")}},+ dedup: &fakeDedup{token: uuidFromString(t, "55555555-5555-5555-5555-555555555555")},binder: &fakeBinder{ensureID: uuidFromString(t, "66666666-6666-6666-6666-666666666666"),appendResult: AppendResult{@@ -505,15 +417,9 @@ 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,@@ -522,6 +428,7 @@ func (h *harness) register(validated ValidatedInboundResolver) {Media: h.media,OriginType: "lark_chat",})+ return h}func TestRouter_NoResolverSet_ReturnsError(t *testing.T) {@@ -592,9 +499,6 @@ 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) {@@ -612,9 +516,6 @@ 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" {@@ -639,267 +540,36 @@ 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) {+func TestRouter_EnsureSessionError_Releases(t *testing.T) {h := newHarness(t)- h.register(nil)- h.binder.ensureErr = ErrRouteChanged-+ h.binder.ensureErr = errors.New("db down")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 err == nil {+ t.Fatal("ensure-session infra error must surface to the caller")}- if got := len(h.binder.successfulAppends()); got != 0 {- t.Fatalf("old route received %d successful appends, want 0", got)+ if h.dedup.releases() != 1 {+ t.Fatalf("ensure-session error must Release the claim (1), got %d", h.dedup.releases())}}-func TestRouter_SessionAppendLockFailureReleasesClaimWithoutAppending(t *testing.T) {+func TestRouter_CancelledRequestStillReleasesClaim(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())- }- })- }-}+ h.dedup.respectCtx = true+ ctx, cancel := context.WithCancel(context.Background())+ h.binder.ensureHook = cancel+ h.binder.ensureErr = errors.New("session lookup cancelled")-func TestRouter_EnsureSessionError_Releases(t *testing.T) {- h := newHarness(t)- h.binder.ensureErr = errors.New("db down")- err := h.router.Handle(context.Background(), p2pMessage(t))+ err := h.router.Handle(ctx, p2pMessage(t))if err == nil {- t.Fatal("ensure-session infra error must surface to the caller")+ t.Fatal("ensure-session error must surface to the caller")}if h.dedup.releases() != 1 {- t.Fatalf("ensure-session error must Release the claim (1), got %d", h.dedup.releases())+ t.Fatalf("cancelled request must still release its claim, got %d releases", h.dedup.releases())+ }+ if err := h.dedup.releaseError(); err != nil {+ t.Fatalf("dedup Release inherited the cancelled request context: %v", err)}}diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.goindex f6272effce..815157fd18 100644--- a/server/internal/integrations/channel/engine/session.go+++ b/server/internal/integrations/channel/engine/session.go@@ -47,7 +47,6 @@ 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) errorLockIssueForChannelMediaBind(ctx context.Context, arg db.LockIssueForChannelMediaBindParams) (pgtype.UUID, error)@@ -82,9 +81,6 @@ func (a dbSessionQueries) CreateChatSession(ctx context.Context, arg db.CreateChfunc (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)}@@ -291,10 +287,6 @@ type AppendInput struct {ClaimToken pgtype.UUIDMediaPendingSeconds float64ForceFresh 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@@ -333,17 +325,6 @@ 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.CommandTextif commandSource == "" {diff --git a/server/internal/integrations/channel/engine/session_test.go b/server/internal/integrations/channel/engine/session_test.goindex 26dfb1ca02..1cb0dbca66 100644--- a/server/internal/integrations/channel/engine/session_test.go+++ b/server/internal/integrations/channel/engine/session_test.go@@ -101,10 +101,6 @@ 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@@ -302,26 +298,6 @@ 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/bot_identity.go b/server/internal/integrations/dingtalk/bot_identity.gonew file mode 100644index 0000000000..bfe0fbfa7c--- /dev/null+++ b/server/internal/integrations/dingtalk/bot_identity.go@@ -0,0 +1,242 @@+package dingtalk++import (+ "context"+ "errors"+ "fmt"+ "strings"+ "sync"+ "time"++ "golang.org/x/sync/singleflight"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++const (+ groupBotsPath = "/v1.0/robot/groups/robots/query"+ botNameLookupTimeout = 3 * time.Second+ botNameCacheTTL = time.Hour+ botNameErrorCacheTTL = time.Minute+ // qyapi_chat_manage is granted per DingTalk app, not per group. Cache a+ // denial briefly across every group for the same Bot so the normal missing-+ // permission state cannot trigger one OpenAPI request per inbound message.+ // A 30-second bound keeps grant-and-mention remediation responsive.+ botNamePermissionCacheTTL = 30 * time.Second+ botNameCacheMaxSize = 4096++ dingTalkPermissionDeniedCode = "Forbidden.AccessDenied.AccessTokenPermissionDenied"+ botIdentityIssueMissingChatManage = "missing_qyapi_chat_manage"+)++var errMissingChatManagePermission = errors.New("dingtalk: qyapi_chat_manage permission is required")++type groupBotListResponse struct {+ Bots []groupBotListItem `json:"chatbotInstanceVOList"`+}++type groupBotListItem struct {+ RobotCode string `json:"robotCode"`+ Name string `json:"name"`+}++// botNameInGroup returns the readable DingTalk name for one exact robot code+// in a group. The API returns every bot in the group; callers must never infer+// identity from list position or persist another bot's metadata.+func (c *Client) botNameInGroup(ctx context.Context, appKey, appSecret, robotCode, conversationID string) (string, error) {+ if strings.TrimSpace(robotCode) == "" || strings.TrimSpace(conversationID) == "" {+ return "", errors.New("dingtalk: bot-name lookup requires robot code and conversation id")+ }++ body := map[string]string{"openConversationId": conversationID}+ var out groupBotListResponse+ token, err := c.accessToken(ctx, appKey, appSecret)+ if err != nil {+ return "", err+ }+ err = c.postJSON(ctx, groupBotsPath, token, body, &out)+ if errors.Is(err, errUnauthorized) {+ c.invalidate(appKey)+ if token, err = c.accessToken(ctx, appKey, appSecret); err != nil {+ return "", err+ }+ err = c.postJSON(ctx, groupBotsPath, token, body, &out)+ }+ if err != nil {+ var apiErr *apiRequestError+ if errors.As(err, &apiErr) &&+ apiErr.Code == dingTalkPermissionDeniedCode &&+ strings.Contains(apiErr.Message, "qyapi_chat_manage") {+ return "", fmt.Errorf("%w: %v", errMissingChatManagePermission, err)+ }+ return "", err+ }+ for _, bot := range out.Bots {+ if bot.RobotCode != robotCode {+ continue+ }+ name := strings.TrimSpace(bot.Name)+ if name == "" {+ return "", fmt.Errorf("dingtalk: robot %q has no readable name in group %q", robotCode, conversationID)+ }+ return name, nil+ }+ return "", fmt.Errorf("dingtalk: robot %q is absent from group %q bot list", robotCode, conversationID)+}++type cachedBotName struct {+ name string+ err error+ expiresAt time.Time+}++type botNameFlightResult struct {+ name string+ sourceConversationID string+}++// BotNameResolver resolves the real DingTalk bot identity through one observed+// group. Names and app-scoped permission denials are cached across every group+// for that Bot; only group-specific failures use a group key. Successful names+// refresh hourly so renames converge. Permission denial refreshes after 30+// seconds so grant-and-mention remediation remains responsive.+type BotNameResolver struct {+ client *Client+ decrypt Decrypter+ now func() time.Time+ timeout time.Duration+ maxSize int++ mu sync.Mutex+ cache map[string]cachedBotName+ group singleflight.Group+}++func NewBotNameResolver(client *Client, decrypt Decrypter) *BotNameResolver {+ if client == nil {+ client = NewClient(nil, "")+ }+ return &BotNameResolver{+ client: client,+ decrypt: decrypt,+ now: time.Now,+ timeout: botNameLookupTimeout,+ maxSize: botNameCacheMaxSize,+ cache: make(map[string]cachedBotName),+ }+}++func (r *BotNameResolver) Resolve(ctx context.Context, installation db.ChannelInstallation, conversationID string) (string, error) {+ credentials, err := decodeCredentials(installation.Config, r.decrypt)+ if err != nil {+ return "", err+ }+ identityKey := "identity\x00" + credentials.AppKey + "\x00" + credentials.RobotCode+ if cached, ok := r.cached(identityKey); ok {+ return cached.name, cached.err+ }+ groupKey := "group\x00" + credentials.AppKey + "\x00" + credentials.RobotCode + "\x00" + conversationID+ if cached, ok := r.cached(groupKey); ok {+ return cached.name, cached.err+ }++ resolved, err := r.resolveFlight(ctx, identityKey, identityKey, groupKey, credentials, conversationID)+ if err == nil || errors.Is(err, errMissingChatManagePermission) ||+ resolved.sourceConversationID == "" || resolved.sourceConversationID == conversationID {+ return resolved.name, err+ }++ // Success and qyapi_chat_manage denial are app-scoped, so the identity+ // flight may safely share them across groups. Any other failure can depend+ // on the group used by the flight leader (for example, the Bot is absent+ // there), so retry this caller's own group instead of returning that error.+ resolved, err = r.resolveFlight(ctx, groupKey, identityKey, groupKey, credentials, conversationID)+ return resolved.name, err+}++func (r *BotNameResolver) resolveFlight(+ ctx context.Context,+ flightKey string,+ identityKey string,+ groupKey string,+ credentials credentials,+ conversationID string,+) (botNameFlightResult, error) {+ result := r.group.DoChan(flightKey, func() (any, error) {+ if cached, ok := r.cached(identityKey); ok {+ return botNameFlightResult{name: cached.name}, cached.err+ }+ if cached, ok := r.cached(groupKey); ok {+ return botNameFlightResult{+ name: cached.name,+ sourceConversationID: conversationID,+ }, cached.err+ }+ lookupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), r.timeout)+ defer cancel()+ name, lookupErr := r.client.botNameInGroup(+ lookupCtx,+ credentials.AppKey,+ credentials.AppSecret,+ credentials.RobotCode,+ conversationID,+ )+ ttl := botNameCacheTTL+ if lookupErr != nil {+ if errors.Is(lookupErr, errMissingChatManagePermission) {+ r.store(identityKey, cachedBotName{+ err: lookupErr,+ expiresAt: r.now().Add(botNamePermissionCacheTTL),+ })+ return botNameFlightResult{sourceConversationID: conversationID}, lookupErr+ }+ ttl = botNameErrorCacheTTL+ r.store(groupKey, cachedBotName{name: "", err: lookupErr, expiresAt: r.now().Add(ttl)})+ return botNameFlightResult{sourceConversationID: conversationID}, lookupErr+ }+ r.store(identityKey, cachedBotName{name: name, expiresAt: r.now().Add(ttl)})+ return botNameFlightResult{name: name, sourceConversationID: conversationID}, nil+ })+ select {+ case <-ctx.Done():+ return botNameFlightResult{}, ctx.Err()+ case resolved := <-result:+ return resolved.Val.(botNameFlightResult), resolved.Err+ }+}++func (r *BotNameResolver) cached(key string) (cachedBotName, bool) {+ r.mu.Lock()+ defer r.mu.Unlock()+ value, ok := r.cache[key]+ if !ok || !value.expiresAt.After(r.now()) {+ return cachedBotName{}, false+ }+ return value, true+}++func (r *BotNameResolver) store(key string, value cachedBotName) {+ r.mu.Lock()+ defer r.mu.Unlock()+ if _, exists := r.cache[key]; exists {+ r.cache[key] = value+ return+ }+ now := r.now()+ for cachedKey, cached := range r.cache {+ if !cached.expiresAt.After(now) {+ delete(r.cache, cachedKey)+ }+ }+ if r.maxSize > 0 && len(r.cache) >= r.maxSize {+ var oldestKey string+ var oldestExpiry time.Time+ for cachedKey, cached := range r.cache {+ if oldestKey == "" || cached.expiresAt.Before(oldestExpiry) {+ oldestKey, oldestExpiry = cachedKey, cached.expiresAt+ }+ }+ delete(r.cache, oldestKey)+ }+ r.cache[key] = value+}diff --git a/server/internal/integrations/dingtalk/bot_identity_test.go b/server/internal/integrations/dingtalk/bot_identity_test.gonew file mode 100644index 0000000000..f33a6f0783--- /dev/null+++ b/server/internal/integrations/dingtalk/bot_identity_test.go@@ -0,0 +1,474 @@+package dingtalk++import (+ "context"+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type observedDoneContext struct {+ context.Context+ once sync.Once+ observed chan struct{}+}++func (c *observedDoneContext) Done() <-chan struct{} {+ c.once.Do(func() { close(c.observed) })+ return nil+}++func botIdentityInstallation(t *testing.T, appKey, robotCode string) db.ChannelInstallation {+ t.Helper()+ config, err := json.Marshal(installConfig{+ AppID: appKey,+ RobotCode: robotCode,+ AppSecretEncrypted: base64.StdEncoding.EncodeToString([]byte("app-secret")),+ })+ if err != nil {+ t.Fatalf("marshal installation config: %v", err)+ }+ return db.ChannelInstallation{Config: config}+}++func TestNewBotNameResolverDefaultsClient(t *testing.T) {+ resolver := NewBotNameResolver(nil, nil)+ if resolver.client == nil || resolver.client.apiBase != defaultAPIBase {+ t.Fatalf("default client = %#v, want DingTalk API client", resolver.client)+ }+}++func TestBotNameInGroupSelectsExactRobotIdentityAndRefreshes401(t *testing.T) {+ mints := 0+ groupCalls := 0+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch r.URL.Path {+ case accessTokenPath:+ mints+++ _, _ = fmt.Fprintf(w, `{"accessToken":"tok-%d","expireIn":7200}`, mints)+ case groupBotsPath:+ groupCalls+++ if groupCalls == 1 {+ w.WriteHeader(http.StatusUnauthorized)+ return+ }+ if got := r.Header.Get("x-acs-dingtalk-access-token"); got != "tok-2" {+ t.Errorf("refreshed token = %q, want tok-2", got)+ }+ var body map[string]string+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Fatalf("decode group bot request: %v", err)+ }+ if body["openConversationId"] != "cid-platform" {+ t.Errorf("request body = %v", body)+ }+ _, _ = w.Write([]byte(`{"chatbotInstanceVOList":[{"robotCode":"robot-support","name":"Support Bot"},{"robotCode":"robot-release","name":" Release Bot "}]}`))+ default:+ w.WriteHeader(http.StatusNotFound)+ }+ }))+ defer srv.Close()++ name, err := NewClient(nil, srv.URL).botNameInGroup(+ context.Background(), "app-key", "app-secret", "robot-release", "cid-platform",+ )+ if err != nil || name != "Release Bot" {+ t.Fatalf("botNameInGroup = %q, %v", name, err)+ }+ if mints != 2 || groupCalls != 2 {+ t.Fatalf("token/group calls = %d/%d, want 2/2", mints, groupCalls)+ }+}++func TestBotNameInGroupRejectsInvalidAndMissingIdentities(t *testing.T) {+ client := NewClient(nil, "")+ if _, err := client.botNameInGroup(context.Background(), "app", "secret", "", "cid"); err == nil {+ t.Fatal("empty robot code must fail before a request")+ }+ if _, err := client.botNameInGroup(context.Background(), "app", "secret", "robot", ""); err == nil {+ t.Fatal("empty conversation id must fail before a request")+ }++ tests := []struct {+ name string+ body string+ }{+ {name: "robot absent", body: `{"chatbotInstanceVOList":[{"robotCode":"other","name":"Other"}]}`},+ {name: "blank name", body: `{"chatbotInstanceVOList":[{"robotCode":"robot","name":" "}]}`},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if r.URL.Path == accessTokenPath {+ _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))+ return+ }+ _, _ = w.Write([]byte(tt.body))+ }))+ defer srv.Close()+ if _, err := NewClient(nil, srv.URL).botNameInGroup(+ context.Background(), "app", "secret", "robot", "cid",+ ); err == nil {+ t.Fatal("expected identity lookup to fail")+ }+ })+ }+}++func TestBotNameInGroupClassifiesOnlyChatManagePermission(t *testing.T) {+ for _, tt := range []struct {+ name string+ message string+ classified bool+ }{+ {name: "chat manage", message: "missing qyapi_chat_manage", classified: true},+ {name: "other permission", message: "missing another_permission", classified: false},+ } {+ t.Run(tt.name, func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if r.URL.Path == accessTokenPath {+ _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))+ return+ }+ w.WriteHeader(http.StatusForbidden)+ _, _ = fmt.Fprintf(w, `{"code":%q,"message":%q}`, dingTalkPermissionDeniedCode, tt.message)+ }))+ defer srv.Close()+ _, err := NewClient(nil, srv.URL).botNameInGroup(+ context.Background(), "app", "secret", "robot", "cid",+ )+ if errors.Is(err, errMissingChatManagePermission) != tt.classified {+ t.Fatalf("error = %v, classified=%t", err, tt.classified)+ }+ })+ }+}++func TestBotNameResolverCachesSuccessfulIdentityAcrossGroups(t *testing.T) {+ var calls atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if r.URL.Path == accessTokenPath {+ _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))+ return+ }+ calls.Add(1)+ _, _ = w.Write([]byte(`{"chatbotInstanceVOList":[{"robotCode":"release","name":"Release"},{"robotCode":"support","name":"Support"}]}`))+ }))+ defer srv.Close()++ resolver := NewBotNameResolver(NewClient(nil, srv.URL), nil)+ for range 2 {+ if name, err := resolver.Resolve(context.Background(), botIdentityInstallation(t, "app", "release"), "group-a"); err != nil || name != "Release" {+ t.Fatalf("cached release = %q, %v", name, err)+ }+ }+ if _, err := resolver.Resolve(context.Background(), botIdentityInstallation(t, "app", "support"), "group-a"); err != nil {+ t.Fatal(err)+ }+ if _, err := resolver.Resolve(context.Background(), botIdentityInstallation(t, "app", "release"), "group-b"); err != nil {+ t.Fatal(err)+ }+ if got := calls.Load(); got != 2 {+ t.Fatalf("API calls = %d, want one per Bot", got)+ }+}++func TestBotNameResolverCachesTransientAndBrieflyCachesPermissionFailure(t *testing.T) {+ groupCalls := 0+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if r.URL.Path == accessTokenPath {+ _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))+ return+ }+ groupCalls+++ switch groupCalls {+ case 1:+ w.WriteHeader(http.StatusServiceUnavailable)+ _, _ = w.Write([]byte(`{"code":"unavailable","message":"retry"}`))+ case 2:+ w.WriteHeader(http.StatusForbidden)+ _, _ = w.Write([]byte(`{"code":"Forbidden.AccessDenied.AccessTokenPermissionDenied","message":"missing qyapi_chat_manage"}`))+ default:+ _, _ = w.Write([]byte(`{"chatbotInstanceVOList":[{"robotCode":"release","name":"Release"}]}`))+ }+ }))+ defer srv.Close()++ resolver := NewBotNameResolver(NewClient(nil, srv.URL), nil)+ now := time.Date(2026, time.August, 19, 0, 0, 0, 0, time.UTC)+ resolver.now = func() time.Time { return now }+ installation := botIdentityInstallation(t, "app", "release")+ for range 2 {+ if _, err := resolver.Resolve(context.Background(), installation, "group"); err == nil {+ t.Fatal("transient failure expected")+ }+ }+ if groupCalls != 1 {+ t.Fatalf("transient API calls = %d, want cached failure", groupCalls)+ }+ now = now.Add(botNameErrorCacheTTL + time.Second)+ if _, err := resolver.Resolve(context.Background(), installation, "group"); !errors.Is(err, errMissingChatManagePermission) {+ t.Fatalf("permission error = %v", err)+ }+ if _, err := resolver.Resolve(context.Background(), installation, "another-group"); !errors.Is(err, errMissingChatManagePermission) {+ t.Fatalf("cached cross-group permission error = %v", err)+ }+ if groupCalls != 2 {+ t.Fatalf("permission denial API calls = %d, want one app-scoped lookup", groupCalls)+ }+ now = now.Add(botNamePermissionCacheTTL + time.Second)+ name, err := resolver.Resolve(context.Background(), installation, "group")+ if err != nil || name != "Release" || groupCalls != 3 {+ t.Fatalf("permission retry after TTL = %q, %v (calls %d)", name, err, groupCalls)+ }+}++func TestBotNameResolverRefreshesSuccessfulNameAfterTTL(t *testing.T) {+ groupCalls := 0+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if r.URL.Path == accessTokenPath {+ _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))+ return+ }+ groupCalls+++ name := "Release Bot"+ if groupCalls > 1 {+ name = "Release Bot Renamed"+ }+ _, _ = fmt.Fprintf(w, `{"chatbotInstanceVOList":[{"robotCode":"release","name":%q}]}`, name)+ }))+ defer srv.Close()++ resolver := NewBotNameResolver(NewClient(nil, srv.URL), nil)+ now := time.Date(2026, time.August, 19, 0, 0, 0, 0, time.UTC)+ resolver.now = func() time.Time { return now }+ installation := botIdentityInstallation(t, "app", "release")+ name, err := resolver.Resolve(context.Background(), installation, "group")+ if err != nil || name != "Release Bot" {+ t.Fatalf("initial Resolve = %q, %v", name, err)+ }+ now = now.Add(botNameCacheTTL - time.Second)+ name, err = resolver.Resolve(context.Background(), installation, "group")+ if err != nil || name != "Release Bot" || groupCalls != 1 {+ t.Fatalf("Resolve before TTL = %q, %v (calls %d)", name, err, groupCalls)+ }+ now = now.Add(2 * time.Second)+ name, err = resolver.Resolve(context.Background(), installation, "group")+ if err != nil || name != "Release Bot Renamed" || groupCalls != 2 {+ t.Fatalf("Resolve after TTL = %q, %v (calls %d)", name, err, groupCalls)+ }+}++func TestBotNameResolverTimesOutDetachedLookup(t *testing.T) {+ groupStarted := make(chan struct{})+ httpClient := &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {+ if r.URL.Path == accessTokenPath {+ return &http.Response{+ StatusCode: http.StatusOK,+ Header: http.Header{"Content-Type": []string{"application/json"}},+ Body: io.NopCloser(strings.NewReader(`{"accessToken":"tok","expireIn":7200}`)),+ }, nil+ }+ close(groupStarted)+ <-r.Context().Done()+ return nil, r.Context().Err()+ })}+ resolver := NewBotNameResolver(NewClient(httpClient, "https://api.example.test"), nil)+ resolver.timeout = 10 * time.Millisecond+ _, err := resolver.Resolve(+ context.Background(),+ botIdentityInstallation(t, "app", "release"),+ "group",+ )+ <-groupStarted+ if !errors.Is(err, context.DeadlineExceeded) {+ t.Fatalf("timed-out Resolve error = %v, want context deadline exceeded", err)+ }+}++func TestBotNameResolverCallerCancellationDoesNotCancelSharedLookup(t *testing.T) {+ started := make(chan struct{})+ release := make(chan struct{})+ finished := make(chan struct{})+ httpClient := &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {+ switch r.URL.Path {+ case accessTokenPath:+ close(started)+ <-release+ return &http.Response{+ StatusCode: http.StatusOK,+ Header: http.Header{"Content-Type": []string{"application/json"}},+ Body: io.NopCloser(strings.NewReader(`{"accessToken":"tok","expireIn":7200}`)),+ }, nil+ case groupBotsPath:+ close(finished)+ return &http.Response{+ StatusCode: http.StatusOK,+ Header: http.Header{"Content-Type": []string{"application/json"}},+ Body: io.NopCloser(strings.NewReader(`{"chatbotInstanceVOList":[{"robotCode":"release","name":"Release Bot"}]}`)),+ }, nil+ default:+ return &http.Response{StatusCode: http.StatusNotFound, Body: http.NoBody}, nil+ }+ })}+ resolver := NewBotNameResolver(NewClient(httpClient, "https://api.example.test"), nil)+ installation := botIdentityInstallation(t, "app", "release")+ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan error, 1)+ go func() {+ _, err := resolver.Resolve(ctx, installation, "group")+ done <- err+ }()+ <-started+ cancel()+ if err := <-done; !errors.Is(err, context.Canceled) {+ t.Fatalf("caller cancellation error = %v, want context.Canceled", err)+ }+ close(release)+ select {+ case <-finished:+ case <-time.After(time.Second):+ t.Fatal("detached shared lookup did not finish after caller cancellation")+ }+}++func TestBotNameResolverCollapsesLookupsAndBoundsCache(t *testing.T) {+ var groupCalls atomic.Int32+ started := make(chan struct{})+ release := make(chan struct{})+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if r.URL.Path == accessTokenPath {+ _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))+ return+ }+ if groupCalls.Add(1) == 1 {+ close(started)+ }+ if r.Header.Get("x-test-block") == "" && r.URL.Path == groupBotsPath && groupCalls.Load() == 1 {+ <-release+ }+ _, _ = w.Write([]byte(`{"chatbotInstanceVOList":[{"robotCode":"release","name":"Release"}]}`))+ }))+ defer srv.Close()++ resolver := NewBotNameResolver(NewClient(nil, srv.URL), nil)+ resolver.maxSize = 2+ installation := botIdentityInstallation(t, "app", "release")+ results := make(chan error, 2)+ for _, groupID := range []string{"group-a", "group-b"} {+ go func() {+ _, err := resolver.Resolve(context.Background(), installation, groupID)+ results <- err+ }()+ }+ <-started+ close(release)+ for range 2 {+ if err := <-results; err != nil {+ t.Fatal(err)+ }+ }+ if got := groupCalls.Load(); got != 1 {+ t.Fatalf("concurrent cross-group calls = %d, want 1 per Bot", got)+ }+ resolver.mu.Lock()+ resolver.cache["expired"] = cachedBotName{expiresAt: time.Now().Add(-time.Second)}+ resolver.mu.Unlock()+ for _, appKey := range []string{"app-b", "app-c"} {+ if _, err := resolver.Resolve(+ context.Background(),+ botIdentityInstallation(t, appKey, "release"),+ "group-a",+ ); err != nil {+ t.Fatal(err)+ }+ }+ resolver.mu.Lock()+ cacheSize := len(resolver.cache)+ _, keptExpired := resolver.cache["expired"]+ resolver.mu.Unlock()+ if cacheSize != 2 || keptExpired {+ t.Fatalf("cache size/expired entry = %d/%t, want 2/false", cacheSize, keptExpired)+ }+}++func TestBotNameResolverRetriesGroupSpecificFailureForAnotherGroup(t *testing.T) {+ groupAStarted := make(chan struct{})+ releaseGroupA := make(chan struct{})+ var groupCalls atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if r.URL.Path == accessTokenPath {+ _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))+ return+ }+ groupCalls.Add(1)+ var body map[string]string+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Fatalf("decode group bot request: %v", err)+ }+ switch body["openConversationId"] {+ case "group-a":+ close(groupAStarted)+ <-releaseGroupA+ _, _ = w.Write([]byte(`{"chatbotInstanceVOList":[{"robotCode":"other","name":"Other"}]}`))+ case "group-b":+ _, _ = w.Write([]byte(`{"chatbotInstanceVOList":[{"robotCode":"release","name":"Release"}]}`))+ default:+ t.Errorf("unexpected conversation id %q", body["openConversationId"])+ w.WriteHeader(http.StatusBadRequest)+ }+ }))+ defer srv.Close()++ resolver := NewBotNameResolver(NewClient(nil, srv.URL), nil)+ installation := botIdentityInstallation(t, "app", "release")+ type outcome struct {+ name string+ err error+ }+ groupAResult := make(chan outcome, 1)+ go func() {+ name, err := resolver.Resolve(context.Background(), installation, "group-a")+ groupAResult <- outcome{name: name, err: err}+ }()+ <-groupAStarted++ waiting := make(chan struct{})+ groupBContext := &observedDoneContext{Context: context.Background(), observed: waiting}+ groupBResult := make(chan outcome, 1)+ go func() {+ name, err := resolver.Resolve(groupBContext, installation, "group-b")+ groupBResult <- outcome{name: name, err: err}+ }()+ <-waiting+ close(releaseGroupA)++ if got := <-groupAResult; got.err == nil || !strings.Contains(got.err.Error(), "absent from group") {+ t.Fatalf("group A result = %q, %v; want group-specific absence", got.name, got.err)+ }+ if got := <-groupBResult; got.err != nil || got.name != "Release" {+ t.Fatalf("group B result = %q, %v; want its own successful lookup", got.name, got.err)+ }+ if got := groupCalls.Load(); got != 2 {+ t.Fatalf("group API calls = %d, want one failed group and one successful group", got)+ }+}diff --git a/server/internal/integrations/dingtalk/byo_install.go b/server/internal/integrations/dingtalk/byo_install.goindex 06ac2998fd..266cb0a40a 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-// default agent. The user creates their own DingTalk Stream-mode robot and pastes its+// 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,9 +86,7 @@ func (s *InstallService) RegisterBYO(ctx context.Context, p RegisterBYOParams) (return db.ChannelInstallation{}, fmt.Errorf("encode dingtalk installation config: %w", err)}- // Persist one installation per default agent (the row is keyed by workspace- // + agent). Group routes can target other agents without another Stream- // connection. The+ // Persist one bot per agent (the row is keyed by workspace + agent). 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/byo_install_test.go b/server/internal/integrations/dingtalk/byo_install_test.goindex d27d647072..63782dc3e4 100644--- a/server/internal/integrations/dingtalk/byo_install_test.go+++ b/server/internal/integrations/dingtalk/byo_install_test.go@@ -279,6 +279,7 @@ func TestRegisterBYO_SameAgentReconnect_UpdatesRowInPlace(t *testing.T) {ID: mustUUID(t, "44444444-4444-4444-4444-444444444444"),WorkspaceID: mustUUID(t, "11111111-1111-1111-1111-111111111111"),AgentID: mustUUID(t, "22222222-2222-2222-2222-222222222222"),+ Config: []byte(`{"group_titles":{"cid-platform":"Platform"},"group_bot_names":{"cid-platform":"Release Bot"}}`),}q := &fakeInstallQueries{existing: existing, existingAppID: "ding-app-key-xyz"}svc := newTestInstallService(t, q)@@ -297,6 +298,15 @@ func TestRegisterBYO_SameAgentReconnect_UpdatesRowInPlace(t *testing.T) {if q.replaceCalled {t.Fatal("same-AppKey reconnect retired the installation identity")}+ var reconnectConfig map[string]json.RawMessage+ if err := json.Unmarshal(q.upsertParams.Config, &reconnectConfig); err != nil {+ t.Fatal(err)+ }+ for _, key := range []string{"group_titles", "group_bot_names"} {+ if _, ok := reconnectConfig[key]; ok {+ t.Fatalf("credential config retained presence key %q: %s", key, q.upsertParams.Config)+ }+ }}// Replacing an agent's robot with a DIFFERENT AppKey must establish a freshdiff --git a/server/internal/integrations/dingtalk/client.go b/server/internal/integrations/dingtalk/client.goindex 1eab4ff516..3bd0bb5a45 100644--- a/server/internal/integrations/dingtalk/client.go+++ b/server/internal/integrations/dingtalk/client.go@@ -43,6 +43,22 @@ type apiError struct {Message string `json:"message"`}+// apiRequestError preserves DingTalk's machine-readable error code so callers+// can distinguish an actionable permission problem from a transient failure.+type apiRequestError struct {+ Path string+ StatusCode int+ Code string+ Message string+}++func (e *apiRequestError) Error() string {+ if e.Message != "" {+ return fmt.Sprintf("dingtalk: %s: code=%q message=%q", e.Path, e.Code, e.Message)+ }+ return fmt.Sprintf("dingtalk: %s: http %d", e.Path, e.StatusCode)+}+// messageFilesDownloadPath resolves a robot message downloadCode to a// short-lived download URL. Both the code and the returned URL are temporary// (DingTalk documents no exact TTL) — resolve and fetch immediately, and neverdiff --git a/server/internal/integrations/dingtalk/config.go b/server/internal/integrations/dingtalk/config.goindex 5124610059..757de9b8bf 100644--- a/server/internal/integrations/dingtalk/config.go+++ b/server/internal/integrations/dingtalk/config.go@@ -1,10 +1,11 @@// Package dingtalk is the DingTalk integration for the channel-agnostic engine.-// It uses the bring-your-own-app (BYO) model: a workspace admin creates their-// own DingTalk Stream-mode robot and pastes its AppKey (client id) and AppSecret-// (client secret) into Multica. Each channel_installation carries its OWN-// AppSecret and gets its OWN Stream-mode connection, supervised per-installation-// by the engine like Feishu and Slack (dingtalk_channel.go) — so several agents-// can each have a distinct bot identity in one DingTalk organization.+// It uses the bring-your-own-app (BYO) model: an agent owner or workspace admin+// creates a DingTalk Stream-mode robot and pastes its AppKey (client id) and+// AppSecret (client secret) into Multica. Each channel_installation carries its+// OWN AppSecret and gets its OWN Stream-mode connection, supervised+// per-installation by the engine like Feishu and Slack (dingtalk_channel.go) —+// so several agents can each have a distinct bot identity in one DingTalk+// organization.//// Each installation's Stream connection only ever delivers events for its own// robot, so the per-installation connection stamps its AppKey into the inbounddiff --git a/server/internal/integrations/dingtalk/group_presence_db_test.go b/server/internal/integrations/dingtalk/group_presence_db_test.gonew file mode 100644index 0000000000..381c6ac983--- /dev/null+++ b/server/internal/integrations/dingtalk/group_presence_db_test.go@@ -0,0 +1,290 @@+package dingtalk++import (+ "context"+ "errors"+ "fmt"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestDingTalkGroupPresencePreservesMetadataAndAggregatesBotsDB(t *testing.T) {+ pool := dingtalkInstallTestDB(t)+ ctx := context.Background()+ const (+ workspaceID = "d1471000-0000-4000-8000-000000000001"+ agentOneID = "d1471000-0000-4000-8000-000000000002"+ agentTwoID = "d1471000-0000-4000-8000-000000000003"+ installerID = "d1471000-0000-4000-8000-000000000004"+ installOne = "d1471000-0000-4000-8000-000000000011"+ installTwo = "d1471000-0000-4000-8000-000000000012"+ sessionOne = "d1471000-0000-4000-8000-000000000021"+ sessionTwo = "d1471000-0000-4000-8000-000000000022"+ )+ clean := func() {+ _, _ = pool.Exec(context.Background(), `DELETE FROM dingtalk_group_presence WHERE installation_id = ANY($1::uuid[])`, []string{installOne, installTwo})+ _, _ = pool.Exec(context.Background(), `DELETE FROM dingtalk_bot_identity WHERE installation_id = ANY($1::uuid[])`, []string{installOne, installTwo})+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE installation_id = ANY($1::uuid[])`, []string{installOne, installTwo})+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_installation WHERE workspace_id = $1 AND channel_type = 'dingtalk'`, workspaceID)+ }+ clean()+ t.Cleanup(clean)+ for _, installation := range []struct {+ id string+ agentID string+ appID string+ }{+ {id: installOne, agentID: agentOneID, appID: "group-presence-one"},+ {id: installTwo, agentID: agentTwoID, appID: "group-presence-two"},+ } {+ if _, err := pool.Exec(ctx, `+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.id, workspaceID, installation.agentID, installation.appID, installerID); err != nil {+ t.Fatalf("seed installation %s: %v", installation.id, err)+ }+ }++ queries := db.New(pool)+ record := func(installationID, conversationID, title, name, issue string) {+ t.Helper()+ if _, err := queries.UpsertDingTalkBotIdentity(ctx, db.UpsertDingTalkBotIdentityParams{+ BotName: name, BotIdentityIssue: issue,+ InstallationID: util.MustParseUUID(installationID),+ WorkspaceID: util.MustParseUUID(workspaceID),+ }); err != nil {+ t.Fatalf("record bot identity: %v", err)+ }+ if _, err := queries.RecordDingTalkGroupPresence(ctx, db.RecordDingTalkGroupPresenceParams{+ ConversationID: conversationID, ConversationTitle: title,+ InstallationID: util.MustParseUUID(installationID),+ WorkspaceID: util.MustParseUUID(workspaceID),+ }); err != nil {+ t.Fatalf("record group presence: %v", err)+ }+ }+ recordActivity := func(installationID, conversationID string) {+ t.Helper()+ if _, err := queries.RecordDingTalkGroupActivity(ctx, db.RecordDingTalkGroupActivityParams{+ InstallationID: util.MustParseUUID(installationID),+ ConversationID: conversationID,+ }); err != nil {+ t.Fatalf("record group activity: %v", err)+ }+ }+ record(installOne, "cid-shared", "Platform", "Release Bot", "")+ record(installTwo, "cid-shared", "Platform", "", botIdentityIssueMissingChatManage)+ // A transient lookup in another group must not erase the application-level+ // permission problem observed on this installation.+ record(installTwo, "cid-repair", "Repair", "", "")+ for _, binding := range []struct {+ sessionID string+ installationID string+ }{+ {sessionID: sessionOne, installationID: installOne},+ {sessionID: sessionTwo, installationID: installTwo},+ } {+ if _, err := pool.Exec(ctx, `+INSERT INTO channel_chat_session_binding (+ chat_session_id, installation_id, channel_type, channel_chat_id, chat_type+) VALUES ($1, $2, 'dingtalk', 'cid-shared', 'group')+`, binding.sessionID, binding.installationID); err != nil {+ t.Fatalf("seed group binding: %v", err)+ }+ }+ recordActivity(installTwo, "cid-repair")+ recordActivity(installOne, "cid-shared")+ recordActivity(installOne, "cid-shared")+ recordActivity(installTwo, "cid-shared")+ listParams := db.ListDingTalkGroupPresencesByWorkspaceParams{+ WorkspaceID: util.MustParseUUID(workspaceID),+ ActiveSince: pgtype.Timestamptz{Time: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true},+ }+ rows, err := queries.ListDingTalkGroupPresencesByWorkspace(ctx, listParams)+ if err != nil {+ t.Fatal(err)+ }+ if len(rows) != 3 {+ t.Fatalf("presence rows = %d, want 3: %+v", len(rows), rows)+ }+ for _, row := range rows {+ wantIssue := ""+ if row.InstallationID == util.MustParseUUID(installTwo) {+ wantIssue = botIdentityIssueMissingChatManage+ }+ if row.BotIdentityIssue != wantIssue {+ t.Fatalf("transient lookup changed permission state: %+v", rows)+ }+ }++ // Empty refresh values preserve known metadata. A successful lookup in any+ // group proves the app permission is repaired and clears every stale issue.+ record(installOne, "cid-shared", "", "", "")+ record(installTwo, "cid-repair", "", "Support Bot", "")++ // A repeated observation must not make the installation look reconfigured.+ // Use a sentinel timestamp so the assertion does not depend on clock timing.+ sentinelUpdatedAt := time.Date(2025, time.January, 2, 3, 4, 5, 0, time.UTC)+ if _, err := pool.Exec(ctx, `UPDATE channel_installation SET updated_at = $1 WHERE id = $2`, sentinelUpdatedAt, installOne); err != nil {+ t.Fatal(err)+ }+ if _, err := pool.Exec(ctx, `UPDATE dingtalk_bot_identity SET updated_at = $1 WHERE installation_id = $2`, sentinelUpdatedAt, installOne); err != nil {+ t.Fatal(err)+ }+ record(installOne, "cid-shared", "Platform", "Release Bot", "")+ var updatedAt, identityUpdatedAt time.Time+ if err := pool.QueryRow(ctx, `SELECT updated_at FROM channel_installation WHERE id = $1`, installOne).Scan(&updatedAt); err != nil {+ t.Fatal(err)+ }+ if err := pool.QueryRow(ctx, `SELECT updated_at FROM dingtalk_bot_identity WHERE installation_id = $1`, installOne).Scan(&identityUpdatedAt); err != nil {+ t.Fatal(err)+ }+ if !updatedAt.Equal(sentinelUpdatedAt) || !identityUpdatedAt.Equal(sentinelUpdatedAt) {+ t.Fatalf("no-op observation updated timestamps to installation %s identity %s, want %s", updatedAt, identityUpdatedAt, sentinelUpdatedAt)+ }++ rows, err = queries.ListDingTalkGroupPresencesByWorkspace(ctx, listParams)+ if err != nil {+ t.Fatal(err)+ }+ if len(rows) != 3 {+ t.Fatalf("group presence rows = %d, want two bots in one group plus repair group: %+v", len(rows), rows)+ }+ byKey := make(map[string]db.ListDingTalkGroupPresencesByWorkspaceRow, len(rows))+ for _, row := range rows {+ byKey[util.UUIDToString(row.InstallationID)+"/"+row.ConversationID] = row+ }+ first := byKey[installOne+"/cid-shared"]+ if first.ConversationTitle != "Platform" || first.BotName != "Release Bot" ||+ first.BotIdentityIssue != "" || first.MentionCount != 2 || !first.LastActiveAt.Valid {+ t.Fatalf("first bot presence = %+v", first)+ }+ second := byKey[installTwo+"/cid-shared"]+ if second.ConversationTitle != "Platform" || second.BotName != "Support Bot" ||+ second.BotIdentityIssue != "" || second.MentionCount != 1 || !second.LastActiveAt.Valid {+ t.Fatalf("second bot presence = %+v", second)+ }+ repaired := byKey[installTwo+"/cid-repair"]+ if repaired.ConversationTitle != "Repair" || repaired.BotName != "Support Bot" ||+ repaired.BotIdentityIssue != "" || repaired.MentionCount != 1 {+ t.Fatalf("repaired bot presence = %+v", repaired)+ }+ filteredRows, err := queries.ListDingTalkGroupPresencesByWorkspace(ctx, db.ListDingTalkGroupPresencesByWorkspaceParams{+ WorkspaceID: util.MustParseUUID(workspaceID),+ FilterByAgent: true,+ AgentID: util.MustParseUUID(agentTwoID),+ ActiveSince: listParams.ActiveSince,+ })+ if err != nil || len(filteredRows) != 2 {+ t.Fatalf("Agent-filtered rows = %+v err %v", filteredRows, err)+ }+ for _, row := range filteredRows {+ if row.AgentID != util.MustParseUUID(agentTwoID) {+ t.Fatalf("Agent filter leaked row %+v", row)+ }+ }+ if _, err := queries.RecordDingTalkGroupActivity(ctx, db.RecordDingTalkGroupActivityParams{+ InstallationID: util.MustParseUUID(installOne),+ ConversationID: "cid-unknown",+ }); !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("unknown group activity error = %v, want no rows", err)+ }++ if _, err := pool.Exec(ctx, `UPDATE channel_installation SET status = 'revoked' WHERE id = $1`, installTwo); err != nil {+ t.Fatal(err)+ }+ if _, err := queries.RecordDingTalkGroupPresence(ctx, db.RecordDingTalkGroupPresenceParams{+ ConversationID: "cid-new", ConversationTitle: "Must not land",+ InstallationID: util.MustParseUUID(installTwo),+ WorkspaceID: util.MustParseUUID(workspaceID),+ }); !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("revoked observation error = %v, want no rows", err)+ }+ rows, err = queries.ListDingTalkGroupPresencesByWorkspace(ctx, listParams)+ if err != nil || len(rows) != 1 || rows[0].InstallationID != util.MustParseUUID(installOne) {+ t.Fatalf("revoked bot filtering = rows %+v err %v", rows, err)+ }+}++func TestDingTalkGroupPresenceConcurrentGroupsDoNotLoseUpdatesDB(t *testing.T) {+ pool := dingtalkInstallTestDB(t)+ ctx := context.Background()+ const (+ workspaceID = "d1472000-0000-4000-8000-000000000001"+ agentID = "d1472000-0000-4000-8000-000000000002"+ installerID = "d1472000-0000-4000-8000-000000000003"+ installationID = "d1472000-0000-4000-8000-000000000004"+ )+ _, _ = pool.Exec(ctx, `DELETE FROM dingtalk_group_presence WHERE installation_id = $1`, installationID)+ _, _ = pool.Exec(ctx, `DELETE FROM dingtalk_bot_identity WHERE installation_id = $1`, installationID)+ _, _ = pool.Exec(ctx, `DELETE FROM channel_installation WHERE id = $1`, installationID)+ t.Cleanup(func() {+ _, _ = pool.Exec(context.Background(), `DELETE FROM dingtalk_group_presence WHERE installation_id = $1`, installationID)+ _, _ = pool.Exec(context.Background(), `DELETE FROM dingtalk_bot_identity WHERE installation_id = $1`, installationID)+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)+ })+ if _, err := pool.Exec(ctx, `+INSERT INTO channel_installation (id, workspace_id, agent_id, channel_type, config, installer_user_id)+VALUES ($1, $2, $3, 'dingtalk', '{"app_id":"group-presence-concurrent"}', $4)+`, installationID, workspaceID, agentID, installerID); err != nil {+ t.Fatal(err)+ }++ queries := db.New(pool)+ const groupCount = 8+ start := make(chan struct{})+ errs := make(chan error, groupCount)+ var ready sync.WaitGroup+ ready.Add(groupCount)+ for i := range groupCount {+ go func() {+ ready.Done()+ <-start+ conversationID := fmt.Sprintf("cid-%d", i)+ _, err := queries.UpsertDingTalkBotIdentity(ctx, db.UpsertDingTalkBotIdentityParams{+ BotName: "Concurrent Bot",+ InstallationID: util.MustParseUUID(installationID),+ WorkspaceID: util.MustParseUUID(workspaceID),+ })+ if err == nil {+ _, err = queries.RecordDingTalkGroupPresence(ctx, db.RecordDingTalkGroupPresenceParams{+ ConversationID: conversationID,+ ConversationTitle: fmt.Sprintf("Group %d", i),+ InstallationID: util.MustParseUUID(installationID),+ WorkspaceID: util.MustParseUUID(workspaceID),+ })+ }+ if err == nil {+ _, err = queries.RecordDingTalkGroupActivity(ctx, db.RecordDingTalkGroupActivityParams{+ InstallationID: util.MustParseUUID(installationID),+ ConversationID: conversationID,+ })+ }+ errs <- err+ }()+ }+ ready.Wait()+ close(start)+ for range groupCount {+ if err := <-errs; err != nil {+ t.Fatalf("concurrent record: %v", err)+ }+ }+ rows, err := queries.ListDingTalkGroupPresencesByWorkspace(ctx, db.ListDingTalkGroupPresencesByWorkspaceParams{+ WorkspaceID: util.MustParseUUID(workspaceID),+ ActiveSince: pgtype.Timestamptz{Time: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true},+ })+ if err != nil {+ t.Fatal(err)+ }+ if len(rows) != groupCount {+ t.Fatalf("concurrent group rows = %d, want %d: %+v", len(rows), groupCount, rows)+ }+}diff --git a/server/internal/integrations/dingtalk/group_route_cleanup_db_test.go b/server/internal/integrations/dingtalk/group_route_cleanup_db_test.godeleted file mode 100644index 6b54246b13..0000000000--- a/server/internal/integrations/dingtalk/group_route_cleanup_db_test.go+++ /dev/null@@ -1,238 +0,0 @@-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.godeleted file mode 100644index 3cfe1ac22a..0000000000--- a/server/internal/integrations/dingtalk/group_route_db_test.go+++ /dev/null@@ -1,553 +0,0 @@-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.godeleted file mode 100644index ad1ff0f417..0000000000--- a/server/internal/integrations/dingtalk/group_route_pipeline_db_test.go+++ /dev/null@@ -1,108 +0,0 @@-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.goindex ec8db6fd81..aec58b9d55 100644--- a/server/internal/integrations/dingtalk/inbound.go+++ b/server/internal/integrations/dingtalk/inbound.go@@ -116,7 +116,10 @@ func inboundFromCallback(data *botCallbackData, appID string) (channel.InboundMe}chatType := dingtalkChatType(data.ConversationType)- rawEvent := dingtalkRawEvent{AppID: appID, ConversationTitle: strings.TrimSpace(data.ConversationTitle)}+ 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.goindex 88d74d7947..d92a10a452 100644--- a/server/internal/integrations/dingtalk/inbound_test.go+++ b/server/internal/integrations/dingtalk/inbound_test.go@@ -39,11 +39,11 @@ func TestInboundFromCallback_P2PAddressedAndTrimmed(t *testing.T) {func TestInboundFromCallback_GroupAddressing(t *testing.T) {callback := textCallback(convTypeGroup, true)- callback.ConversationTitle = "Platform team"+ 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)+ t.Fatalf("group title metadata = %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.goindex 4619b3260d..c025886557 100644--- a/server/internal/integrations/dingtalk/install.go+++ b/server/internal/integrations/dingtalk/install.go@@ -18,9 +18,9 @@ import ()// This file is the DingTalk install backend. DingTalk uses the-// bring-your-own-app (BYO) model: the workspace admin creates their own DingTalk-// Stream-mode robot, and pastes its AppKey (client id) + AppSecret (client-// secret) into Multica (the paste path lives in byo_install.go). The+// bring-your-own-app (BYO) model: an agent owner or workspace admin creates a+// DingTalk Stream-mode robot, then pastes its AppKey (client id) + AppSecret+// (client secret) into Multica (the paste path lives in byo_install.go). The// InstallService owns the at-rest encryption of the AppSecret — so no caller can// write a channel_installation with a plaintext secret — plus the shared// persistInstall transaction and the list / get / revoke management surface.@@ -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 installation/default agent;- // group-specific routes may target other agents inside that workspace.+ // robot is one bot identity and maps to one agent; reusing it here requires+ // disconnecting it in the other workspace first.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 installation/default agent per bot.+// is keyed by (workspace, agent) — one bot per agent.type installPersist struct {wsID pgtype.UUIDagentID pgtype.UUID@@ -139,8 +139,7 @@ type installPersist struct {// pgUniqueViolation is the Postgres SQLSTATE for a unique-constraint violation.const pgUniqueViolation = "23505"-// persistInstall stores one DingTalk installation per (workspace, default-// agent). Reconnecting+// persistInstall stores one DingTalk bot per (workspace, 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 userdiff --git a/server/internal/integrations/dingtalk/install_test.go b/server/internal/integrations/dingtalk/install_test.goindex 68df5c5390..52e5569d0a 100644--- a/server/internal/integrations/dingtalk/install_test.go+++ b/server/internal/integrations/dingtalk/install_test.go@@ -78,7 +78,9 @@ func (f *fakeInstallQueries) GetDingTalkInstallationOwnerForUpdate(_ context.Conif f.existing == nil {return db.GetDingTalkInstallationOwnerForUpdateRow{}, pgx.ErrNoRows}- return db.GetDingTalkInstallationOwnerForUpdateRow{ID: f.existing.ID, AppID: f.existingAppID}, nil+ return db.GetDingTalkInstallationOwnerForUpdateRow{+ ID: f.existing.ID, AppID: f.existingAppID,+ }, nil}func (f *fakeInstallQueries) DeleteDingTalkInstallationForReplacement(_ context.Context, arg db.DeleteDingTalkInstallationForReplacementParams) (pgtype.UUID, error) {diff --git a/server/internal/integrations/dingtalk/replier.go b/server/internal/integrations/dingtalk/replier.goindex fafbcfd83d..3af655f809 100644--- a/server/internal/integrations/dingtalk/replier.go+++ b/server/internal/integrations/dingtalk/replier.go@@ -40,7 +40,7 @@ const (// pre-engine IssueCommandProcessor: without them the user's command// vanishes with no signal that it will never be handled.issueNotMemberText = "You're not a member of this Multica workspace, so I can't file an issue for you. Ask a workspace admin to invite you, then send the command again."- issueDisabledText = "This DingTalk robot isn't connected to Multica (or was disconnected). Ask a workspace admin to reconnect it."+ issueDisabledText = "This DingTalk robot isn't connected to Multica (or was disconnected). Ask the agent owner or a workspace owner/admin to reconnect it.")// bindingMinter is the binding-token surface the replier needs.diff --git a/server/internal/integrations/dingtalk/resolvers.go b/server/internal/integrations/dingtalk/resolvers.goindex 46c97727ae..2bee130169 100644--- a/server/internal/integrations/dingtalk/resolvers.go+++ b/server/internal/integrations/dingtalk/resolvers.go@@ -5,13 +5,13 @@ import ("encoding/json""errors""fmt"+ "log/slog""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/integrations/channel""github.com/multica-ai/multica/server/internal/integrations/channel/engine"- "github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/dbid")@@ -33,21 +33,21 @@ const originDingTalkChat = "dingtalk_chat"// per-message reaction, so the ack notifier stands in for a typing indicator (a// "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+func NewDingTalkResolverSet(q *db.Queries, tx engine.TxStarter, replier engine.OutboundReplier, ack *ackNotifier, media engine.MediaResolver, botNames *BotNameResolver) engine.ResolverSet {+ groupPresence := &groupPresenceObserver{+ q: q,+ botNames: botNames,+ logger: slog.Default(),}set := engine.ResolverSet{Installation: &installationResolver{q: q},Identity: &identityResolver{q: q},- Validated: &validatedInboundResolver{q: q},Dedup: &deduper{q: q},- Session: &sessionBinder{q: q, lockRouteForAppend: lockRouteForAppend, session: engine.NewChatSession(q, tx, TypeDingTalk, engine.SessionTitles{+ Session: &sessionBinder{session: engine.NewChatSession(q, tx, TypeDingTalk, engine.SessionTitles{Group: "DingTalk group",Direct: "DingTalk direct message",Fallback: "DingTalk chat",- })},+ }), groupPresence: groupPresence},Audit: &auditor{q: q},Replier: replier,OriginType: originDingTalkChat,@@ -64,12 +64,11 @@ func NewDingTalkResolverSet(q *db.Queries, tx engine.TxStarter, replier engine.O}var (- _ engine.InstallationResolver = (*installationResolver)(nil)- _ engine.IdentityResolver = (*identityResolver)(nil)- _ engine.ValidatedInboundResolver = (*validatedInboundResolver)(nil)- _ engine.Deduper = (*deduper)(nil)- _ engine.SessionBinder = (*sessionBinder)(nil)- _ engine.Auditor = (*auditor)(nil)+ _ engine.InstallationResolver = (*installationResolver)(nil)+ _ engine.IdentityResolver = (*identityResolver)(nil)+ _ engine.Deduper = (*deduper)(nil)+ _ engine.SessionBinder = (*sessionBinder)(nil)+ _ engine.Auditor = (*auditor)(nil))// dingtalkBindingConfig is the opaque outbound routing persisted on the chat@@ -80,7 +79,6 @@ 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@@ -88,12 +86,11 @@ 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, agentID pgtype.UUID) (bindingKey string, config []byte) {+func dingtalkSessionRouting(msg channel.InboundMessage) (bindingKey string, config []byte) {chatID := msg.Source.ChatIDcfg := dingtalkBindingConfig{ConversationType: convTypeGroup,ConversationID: chatID,- AgentID: util.UUIDToString(agentID),}if msg.Source.ChatType == channel.ChatTypeP2P {cfg.ConversationType = convTypeP2P@@ -142,11 +139,7 @@ func nullText(s string) pgtype.Text {// ---- installation routing -----type installationQueries interface {- GetChannelInstallationByAppID(ctx context.Context, arg db.GetChannelInstallationByAppIDParams) (db.ChannelInstallation, error)-}--type installationResolver struct{ q installationQueries }+type installationResolver struct{ q *db.Queries }func (r *installationResolver) ResolveInstallation(ctx context.Context, msg channel.InboundMessage) (engine.ResolvedInstallation, error) {raw, err := decodeDingTalkRaw(msg)@@ -167,51 +160,14 @@ 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: agentID,+ AgentID: inst.AgentID,InstallerUserID: inst.InstallerUserID,Active: inst.Status == "active",Platform: inst,- }+ }, nil}// ---- identity ----@@ -287,20 +243,90 @@ type chatSession interface {BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error}-type sessionQueries interface {- DingTalkGroupRouteMatchesAgent(ctx context.Context, arg db.DingTalkGroupRouteMatchesAgentParams) (bool, error)- DeleteDingTalkStaleGroupChatBinding(ctx context.Context, arg db.DeleteDingTalkStaleGroupChatBindingParams) (int64, error)+type groupPresenceQueries interface {+ UpsertDingTalkBotIdentity(ctx context.Context, arg db.UpsertDingTalkBotIdentityParams) (pgtype.UUID, error)+ RecordDingTalkGroupPresence(ctx context.Context, arg db.RecordDingTalkGroupPresenceParams) (pgtype.UUID, error)+ RecordDingTalkGroupActivity(ctx context.Context, arg db.RecordDingTalkGroupActivityParams) (pgtype.UUID, error)+}++// groupPresenceObserver records product metadata after group-addressing and+// sender-membership checks have accepted the message.+type groupPresenceObserver struct {+ q groupPresenceQueries+ botNames *BotNameResolver+ logger *slog.Logger+}++func (o *groupPresenceObserver) Observe(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage) error {+ if o == nil || o.q == nil || msg.Source.ChatType != channel.ChatTypeGroup {+ return nil+ }+ raw, err := decodeDingTalkRaw(msg)+ if err != nil {+ return err+ }+ botName := ""+ botIdentityIssue := ""+ if o.botNames != nil {+ if installation, ok := inst.Platform.(db.ChannelInstallation); ok {+ botName, err = o.botNames.Resolve(ctx, installation, msg.Source.ChatID)+ if err != nil {+ if errors.Is(err, errMissingChatManagePermission) {+ botIdentityIssue = botIdentityIssueMissingChatManage+ }+ logger := o.logger+ if logger == nil {+ logger = slog.Default()+ }+ logger.WarnContext(ctx, "dingtalk: could not resolve readable bot identity",+ "installation_id", inst.ID,+ "conversation_id", msg.Source.ChatID,+ "error", err,+ )+ botName = ""+ }+ }+ }+ _, err = o.q.UpsertDingTalkBotIdentity(ctx, db.UpsertDingTalkBotIdentityParams{+ BotName: botName,+ BotIdentityIssue: botIdentityIssue,+ InstallationID: inst.ID,+ WorkspaceID: inst.WorkspaceID,+ })+ if err != nil {+ return err+ }+ _, err = o.q.RecordDingTalkGroupPresence(ctx, db.RecordDingTalkGroupPresenceParams{+ ConversationID: msg.Source.ChatID,+ ConversationTitle: raw.ConversationTitle,+ InstallationID: inst.ID,+ WorkspaceID: inst.WorkspaceID,+ })+ return err+}++// RecordActivity advances the counters only after AppendUserMessage commits.+// Presence discovery runs earlier, after addressing and membership checks, but+// counting there would include messages whose durable append later fails.+func (o *groupPresenceObserver) RecordActivity(ctx context.Context, installationID pgtype.UUID, msg channel.InboundMessage) error {+ if o == nil || o.q == nil || msg.Source.ChatType != channel.ChatTypeGroup {+ return nil+ }+ _, err := o.q.RecordDingTalkGroupActivity(ctx, db.RecordDingTalkGroupActivityParams{+ InstallationID: installationID,+ ConversationID: msg.Source.ChatID,+ })+ return err}type sessionBinder struct {- q sessionQueries- lockRouteForAppend func(context.Context, pgx.Tx, db.LockDingTalkGroupRouteForAppendParams) error- session chatSession+ session chatSession+ groupPresence *groupPresenceObserver}func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessionParams) (pgtype.UUID, error) {- bindingKey, config := dingtalkSessionRouting(p.Message, p.Installation.AgentID)- input := engine.EnsureSessionInput{+ bindingKey, config := dingtalkSessionRouting(p.Message)+ sessionID, err := r.session.EnsureSession(ctx, engine.EnsureSessionInput{WorkspaceID: p.Installation.WorkspaceID,AgentID: p.Installation.AgentID,InstallationID: p.Installation.ID,@@ -308,54 +334,24 @@ func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessioBindingKey: bindingKey,BindingConfig: config,ChatType: p.Message.Source.ChatType,+ })+ if err != nil {+ return pgtype.UUID{}, err}- 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+ // Group inventory is best-effort metadata. A lookup or write failure must+ // not turn a valid group mention into a failed chat message.+ if err := r.groupPresence.Observe(ctx, p.Installation, p.Message); err != nil {+ logger := slog.Default()+ if r.groupPresence != nil && r.groupPresence.logger != nil {+ logger = r.groupPresence.logger}+ logger.WarnContext(ctx, "dingtalk: could not record group presence",+ "installation_id", p.Installation.ID,+ "conversation_id", p.Message.Source.ChatID,+ "error", err,+ )}- return pgtype.UUID{}, engine.ErrRouteChanged+ return sessionID, nil}func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {@@ -367,7 +363,7 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParamsif commandText == "" {commandText = p.Message.Text}- input := engine.AppendInput{+ result, err := r.session.AppendUserMessage(ctx, engine.AppendInput{SessionID: p.SessionID,Sender: p.Sender,InstallationID: p.InstallationID,@@ -378,25 +374,25 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParamsClaimToken: p.ClaimToken,MediaPendingSeconds: p.MediaPendingSeconds,ForceFresh: p.Message.ForceFresh,+ })+ if err != nil {+ return engine.AppendResult{}, err}- 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+ // Group inventory is best-effort product metadata. The message and dedup+ // mark are already durable, so a counter write failure must not release the+ // claim or make DingTalk retry and risk a duplicate user-visible turn.+ if err := r.groupPresence.RecordActivity(ctx, p.InstallationID, p.Message); err != nil {+ logger := slog.Default()+ if r.groupPresence != nil && r.groupPresence.logger != nil {+ logger = r.groupPresence.logger}+ logger.WarnContext(ctx, "dingtalk: could not record group activity",+ "installation_id", p.InstallationID,+ "conversation_id", p.Message.Source.ChatID,+ "error", err,+ )}- return r.session.AppendUserMessage(ctx, input)+ return result, nil}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.goindex 7824cd4479..ccc55dd955 100644--- a/server/internal/integrations/dingtalk/resolvers_test.go+++ b/server/internal/integrations/dingtalk/resolvers_test.go@@ -4,10 +4,10 @@ import ("context""encoding/json""errors"- "strings"+ "net/http"+ "net/http/httptest""testing"- "github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/integrations/channel"@@ -15,69 +15,34 @@ 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 fakeGroupPresenceQueries struct {+ identityCalls int+ identityParams db.UpsertDingTalkBotIdentityParams+ identityErr error+ calls int+ params db.RecordDingTalkGroupPresenceParams+ err error+ activityCalls int+ activityParams db.RecordDingTalkGroupActivityParams+ activityErr error}-type fakeValidatedInboundQueries struct {- params db.DiscoverDingTalkGroupRouteParams- row db.DiscoverDingTalkGroupRouteRow- err error- calls int+func (f *fakeGroupPresenceQueries) UpsertDingTalkBotIdentity(_ context.Context, params db.UpsertDingTalkBotIdentityParams) (pgtype.UUID, error) {+ f.identityCalls+++ f.identityParams = params+ return params.InstallationID, f.identityErr}-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+func (f *fakeGroupPresenceQueries) RecordDingTalkGroupPresence(_ context.Context, params db.RecordDingTalkGroupPresenceParams) (pgtype.UUID, error) {f.calls++- return f.row, f.err+ f.params = params+ return params.InstallationID, f.err}-func (f *fakeValidatedInboundQueries) DiscoverDingTalkGroupRoute(_ context.Context, params db.DiscoverDingTalkGroupRouteParams) (db.DiscoverDingTalkGroupRouteRow, error) {- f.params = params- f.calls++- return f.row, f.err+func (f *fakeGroupPresenceQueries) RecordDingTalkGroupActivity(_ context.Context, params db.RecordDingTalkGroupActivityParams) (pgtype.UUID, error) {+ f.activityCalls+++ f.activityParams = params+ return params.InstallationID, f.activityErr}type captureChatSession struct {@@ -85,9 +50,7 @@ type captureChatSession struct {ensureCalls intensureErr errorappend engine.AppendInput- appendCalls int- appended int- runGuard bool+ appendErr errormedia engine.BindMediaInput}@@ -97,16 +60,48 @@ func (c *captureChatSession) EnsureSession(_ context.Context, in engine.EnsureSereturn pgtype.UUID{}, c.ensureErr}func (c *captureChatSession) MarkPendingFresh(context.Context, pgtype.UUID) error { return nil }-func (c *captureChatSession) AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error) {+func (c *captureChatSession) AppendUserMessage(_ 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- }+ return engine.AppendResult{}, c.appendErr+}++func TestSessionBinder_RecordsActivityOnlyAfterSuccessfulGroupAppend(t *testing.T) {+ installationID := pgtype.UUID{Bytes: [16]byte{4}, Valid: true}+ queries := &fakeGroupPresenceQueries{activityErr: errors.New("activity unavailable")}+ capture := &captureChatSession{}+ binder := &sessionBinder{+ session: capture,+ groupPresence: &groupPresenceObserver{q: queries},+ }+ message := channel.InboundMessage{Source: channel.Source{+ ChatID: "cid-platform",+ ChatType: channel.ChatTypeGroup,+ }}+ // Activity metadata is best effort after the durable append, so its own+ // failure does not turn the accepted message into an error.+ if _, err := binder.AppendMessage(context.Background(), engine.AppendParams{+ InstallationID: installationID,+ Message: message,+ }); err != nil {+ t.Fatalf("activity failure blocked append: %v", err)+ }+ if queries.activityCalls != 1 || queries.activityParams.InstallationID != installationID ||+ queries.activityParams.ConversationID != "cid-platform" {+ t.Fatalf("activity call = %d params %+v", queries.activityCalls, queries.activityParams)+ }++ appendErr := errors.New("append unavailable")+ queries.activityCalls = 0+ capture.appendErr = appendErr+ if _, err := binder.AppendMessage(context.Background(), engine.AppendParams{+ InstallationID: installationID,+ Message: message,+ }); !errors.Is(err, appendErr) {+ t.Fatalf("append error = %v, want %v", err, appendErr)+ }+ if queries.activityCalls != 0 {+ t.Fatalf("failed append recorded activity %d times", queries.activityCalls)}- c.appended++- return engine.AppendResult{}, nil}func (c *captureChatSession) BindMediaRefs(_ context.Context, in engine.BindMediaInput) error {c.media = in@@ -114,200 +109,205 @@ func (c *captureChatSession) BindMediaRefs(_ context.Context, in engine.BindMedi}func TestNewDingTalkResolverSetUsesDatabaseBackedIssueOrigin(t *testing.T) {- set := NewDingTalkResolverSet(nil, nil, nil, nil, nil)+ set := NewDingTalkResolverSet(nil, nil, nil, nil, nil, nil)if set.OriginType != originDingTalkChat {t.Fatalf("OriginType = %q, want %q", set.OriginType, originDingTalkChat)}}-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,+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+ session.Valid, sender.Valid, inst.Valid, claim.Valid = true, true, true, true+ capture := &captureChatSession{}+ binder := &sessionBinder{session: capture}+ _, err := binder.AppendMessage(context.Background(), engine.AppendParams{+ SessionID: session, Sender: sender, InstallationID: inst, ClaimToken: claim,+ MediaPendingSeconds: 45,+ Message: channel.InboundMessage{+ MessageID: "m1", Text: "[Image]\n/issue fix login", CommandText: "/issue fix login", ForceFresh: true,+ },})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)+ in := capture.append+ if in.Body != "[Image]\n/issue fix login" || in.CommandText != "/issue fix login" {+ t.Fatalf("body/command = %q/%q", in.Body, in.CommandText)+ }+ if in.MediaPendingSeconds != 45 || !in.ForceFresh || in.SessionID != session || in.Sender != sender || in.InstallationID != inst || in.ClaimToken != claim {+ t.Fatalf("mapped append input = %+v", in)+ }+}++func TestSessionBinder_GroupUsesInstallationDefaultAgent(t *testing.T) {+ installationID := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}+ workspaceID := pgtype.UUID{Bytes: [16]byte{2}, Valid: true}+ defaultAgentID := pgtype.UUID{Bytes: [16]byte{3}, Valid: true}+ installerID := pgtype.UUID{Bytes: [16]byte{4}, Valid: true}+ capture := &captureChatSession{}+ binder := &sessionBinder{session: capture}++ if _, err := binder.EnsureSession(context.Background(), engine.EnsureSessionParams{+ Installation: engine.ResolvedInstallation{+ ID: installationID,+ WorkspaceID: workspaceID,+ AgentID: defaultAgentID,+ InstallerUserID: installerID,+ },+ Sender: installerID,+ Message: channel.InboundMessage{Source: channel.Source{+ ChatID: "group-1",+ ChatType: channel.ChatTypeGroup,+ }},+ }); err != nil {+ t.Fatalf("ensure DingTalk group session: %v", err)}- if fake.params.ChannelType != string(TypeDingTalk) || fake.params.AppID != "app-key" {- t.Fatalf("installation lookup params = %+v", fake.params)++ if capture.ensure.AgentID != defaultAgentID {+ t.Fatalf("group session agent = %v, want installation default %v", capture.ensure.AgentID, defaultAgentID)}- platform, ok := resolved.Platform.(db.ChannelInstallation)- if !ok || platform.AgentID != defaultAgentID {- t.Fatalf("platform installation must retain default agent: %#v", resolved.Platform)+ if capture.ensure.InstallationID != installationID || capture.ensure.WorkspaceID != workspaceID {+ t.Fatalf("group session scope = %+v", capture.ensure)}}-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)- }- })+func TestGroupPresenceObserverRecordsExactBotWithoutChangingRouting(t *testing.T) {+ installationID := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}+ workspaceID := pgtype.UUID{Bytes: [16]byte{2}, Valid: true}+ agentID := pgtype.UUID{Bytes: [16]byte{3}, Valid: true}+ platform := botIdentityInstallation(t, "app-key", "robot-release")+ platform.ID = installationID- 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)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if r.URL.Path == accessTokenPath {+ _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))+ return}- })-}+ _, _ = w.Write([]byte(`{"chatbotInstanceVOList":[{"robotCode":"robot-other","name":"Other Bot"},{"robotCode":"robot-release","name":"Release Bot"}]}`))+ }))+ defer srv.Close()-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}+ queries := &fakeGroupPresenceQueries{}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)+ err := (&groupPresenceObserver{+ q: queries,+ botNames: NewBotNameResolver(NewClient(nil, srv.URL), nil),+ }).Observe(context.Background(), engine.ResolvedInstallation{+ ID: installationID, WorkspaceID: workspaceID, AgentID: agentID, Platform: platform,+ }, channel.InboundMessage{+ Source: channel.Source{ChatID: "cid-platform", ChatType: channel.ChatTypeGroup},+ Raw: raw,+ })+ if err != nil {+ t.Fatal(err)}- 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)+ if queries.calls != 1 || queries.params.InstallationID != installationID ||+ queries.params.WorkspaceID != workspaceID || queries.params.ConversationID != "cid-platform" ||+ queries.params.ConversationTitle != "Platform team" || queries.identityCalls != 1 ||+ queries.identityParams.BotName != "Release Bot" || queries.identityParams.BotIdentityIssue != "" {+ t.Fatalf("recorded identity/group presence = identity calls %d params %+v, group calls %d params %+v",+ queries.identityCalls, queries.identityParams, queries.calls, queries.params)}}-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")}+func TestGroupPresenceObserverSkipsDirectMessagesAndRejectsMalformedGroupRaw(t *testing.T) {+ queries := &fakeGroupPresenceQueries{}+ observer := &groupPresenceObserver{q: queries}+ if err := observer.Observe(context.Background(), engine.ResolvedInstallation{}, channel.InboundMessage{+ Source: channel.Source{ChatType: channel.ChatTypeP2P}, Raw: []byte("{"),+ }); err != nil || queries.calls != 0 {+ t.Fatalf("direct observation = error %v calls %d, want no-op", err, queries.calls)+ }+ if err := observer.Observe(context.Background(), engine.ResolvedInstallation{}, channel.InboundMessage{+ Source: channel.Source{ChatType: channel.ChatTypeGroup}, Raw: []byte("{"),+ }); err == nil || queries.calls != 0 {+ t.Fatalf("malformed group observation = error %v calls %d", err, queries.calls)+ }+}- 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)+func TestGroupPresenceObserverPersistsPermissionIssueAndPropagatesDatabaseError(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if r.URL.Path == accessTokenPath {+ _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))+ return+ }+ w.WriteHeader(http.StatusForbidden)+ _, _ = w.Write([]byte(`{"code":"Forbidden.AccessDenied.AccessTokenPermissionDenied","message":"missing qyapi_chat_manage"}`))+ }))+ defer srv.Close()++ databaseErr := errors.New("database unavailable")+ queries := &fakeGroupPresenceQueries{err: databaseErr}+ platform := botIdentityInstallation(t, "app-key", "robot-release")+ raw, _ := json.Marshal(dingtalkRawEvent{ConversationTitle: "Platform"})+ err := (&groupPresenceObserver{+ q: queries,+ botNames: NewBotNameResolver(NewClient(nil, srv.URL), nil),+ }).Observe(context.Background(), engine.ResolvedInstallation{+ Platform: platform,+ }, channel.InboundMessage{+ Source: channel.Source{ChatID: "cid-platform", ChatType: channel.ChatTypeGroup},+ Raw: raw,+ })+ if !errors.Is(err, databaseErr) {+ t.Fatalf("observer error = %v, want database error", err)+ }+ if queries.identityParams.BotName != "" || queries.identityParams.BotIdentityIssue != botIdentityIssueMissingChatManage {+ t.Fatalf("permission fallback params = %+v", queries.identityParams)}+}- queries := &fakeSessionQueries{matchErrs: []error{errors.New("must not query group route session fence for p2p")}}+func TestSessionBinder_GroupPresenceFailureDoesNotBlockMessages(t *testing.T) {+ databaseErr := errors.New("database unavailable")+ queries := &fakeGroupPresenceQueries{err: databaseErr}capture := &captureChatSession{}- appendFenceCalls := 0+ raw, _ := json.Marshal(dingtalkRawEvent{ConversationTitle: "Platform"})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")+ session: capture,+ groupPresence: &groupPresenceObserver{+ q: queries,},}- 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{+ if _, err := binder.EnsureSession(context.Background(), engine.EnsureSessionParams{+ Installation: engine.ResolvedInstallation{+ ID: pgtype.UUID{Bytes: [16]byte{1}, Valid: true},+ WorkspaceID: pgtype.UUID{Bytes: [16]byte{2}, Valid: true},+ AgentID: pgtype.UUID{Bytes: [16]byte{3}, Valid: true},+ },+ Message: 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)+ }); err != nil {+ t.Fatalf("group metadata failure blocked session: %v", err)}- 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)+ if capture.ensureCalls != 1 || queries.calls != 1 {+ t.Fatalf("session/group calls = %d/%d, want 1/1", capture.ensureCalls, queries.calls)}}-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_SessionFailureDoesNotWriteGroupPresence(t *testing.T) {+ sessionErr := errors.New("session unavailable")+ queries := &fakeGroupPresenceQueries{}+ capture := &captureChatSession{ensureErr: sessionErr}+ raw, _ := json.Marshal(dingtalkRawEvent{ConversationTitle: "Platform"})+ binder := &sessionBinder{+ session: capture,+ groupPresence: &groupPresenceObserver{q: queries},}-}-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- session.Valid, sender.Valid, inst.Valid, claim.Valid = true, true, true, true- capture := &captureChatSession{}- binder := &sessionBinder{session: capture}- _, err := binder.AppendMessage(context.Background(), engine.AppendParams{- SessionID: session, Sender: sender, InstallationID: inst, ClaimToken: claim,- MediaPendingSeconds: 45,+ _, err := binder.EnsureSession(context.Background(), engine.EnsureSessionParams{Message: channel.InboundMessage{- MessageID: "m1", Text: "[Image]\n/issue fix login", CommandText: "/issue fix login", ForceFresh: true,+ Source: channel.Source{ChatID: "cid-platform", ChatType: channel.ChatTypeGroup},+ Raw: raw,},})- if err != nil {- t.Fatal(err)- }- in := capture.append- if in.Body != "[Image]\n/issue fix login" || in.CommandText != "/issue fix login" {- t.Fatalf("body/command = %q/%q", in.Body, in.CommandText)- }- if in.MediaPendingSeconds != 45 || !in.ForceFresh || in.SessionID != session || in.Sender != sender || in.InstallationID != inst || in.ClaimToken != claim {- t.Fatalf("mapped append input = %+v", in)+ if !errors.Is(err, sessionErr) || queries.calls != 0 {+ t.Fatalf("session error/group calls = %v/%d, want original error and no metadata write", err, queries.calls)}}@@ -337,7 +337,7 @@ func TestDingTalkSessionRouting_P2PCarriesStaffID(t *testing.T) {ChatType: channel.ChatTypeP2P,SenderID: "staff-7",}}- key, cfg := dingtalkSessionRouting(msg, pgtype.UUID{})+ key, cfg := dingtalkSessionRouting(msg)if key != "cid-1" {t.Errorf("binding key = %q, want conversation id", key)}@@ -356,7 +356,7 @@ func TestDingTalkSessionRouting_GroupOmitsStaffID(t *testing.T) {ChatType: channel.ChatTypeGroup,SenderID: "staff-7",}}- _, cfg := dingtalkSessionRouting(msg, pgtype.UUID{})+ _, cfg := dingtalkSessionRouting(msg)var dc dingtalkBindingConfig_ = json.Unmarshal(cfg, &dc)if dc.ConversationType != convTypeGroup || dc.StaffID != "" {@@ -369,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)@@ -382,182 +382,3 @@ 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/integrations/dingtalk/token.go b/server/internal/integrations/dingtalk/token.goindex fdb009d599..f47cb40ebb 100644--- a/server/internal/integrations/dingtalk/token.go+++ b/server/internal/integrations/dingtalk/token.go@@ -184,10 +184,12 @@ func (c *Client) postJSON(ctx context.Context, path, accessToken string, body, oif resp.StatusCode < 200 || resp.StatusCode >= 300 {var apiErr apiError_ = json.Unmarshal(respBody, &apiErr)- if apiErr.Message != "" {- return fmt.Errorf("dingtalk: %s: code=%q message=%q", path, apiErr.Code, apiErr.Message)+ return &apiRequestError{+ Path: path,+ StatusCode: resp.StatusCode,+ Code: apiErr.Code,+ Message: apiErr.Message,}- return fmt.Errorf("dingtalk: %s: http %d", path, resp.StatusCode)}if out != nil && len(respBody) > 0 {if err := json.Unmarshal(respBody, out); err != nil {diff --git a/server/internal/migrations/dingtalk_group_routing_removal_migration_test.go b/server/internal/migrations/dingtalk_group_routing_removal_migration_test.gonew file mode 100644index 0000000000..1e9a5083ca--- /dev/null+++ b/server/internal/migrations/dingtalk_group_routing_removal_migration_test.go@@ -0,0 +1,327 @@+package migrations++import (+ "context"+ "os"+ "testing"++ "github.com/jackc/pgx/v5/pgxpool"+)++const dingtalkRoutingRemovalTestSchema = "dingtalk_routing_removal_test"++func TestDingTalkGroupRoutingRemovalMigrations(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 "+dingtalkRoutingRemovalTestSchema+" CASCADE")+ }+ cleanup()+ t.Cleanup(cleanup)+ if _, err := conn.Exec(ctx, "CREATE SCHEMA "+dingtalkRoutingRemovalTestSchema); err != nil {+ t.Fatalf("create isolated migration schema: %v", err)+ }+ if _, err := conn.Exec(ctx, `SELECT set_config('search_path', $1, false)`, dingtalkRoutingRemovalTestSchema); err != nil {+ t.Fatalf("set isolated migration search path: %v", err)+ }++ if _, err := conn.Exec(ctx, `+ CREATE TABLE channel_installation (+ id UUID PRIMARY KEY,+ workspace_id UUID NOT NULL,+ channel_type TEXT NOT NULL,+ agent_id UUID NOT NULL,+ config JSONB NOT NULL DEFAULT '{}'::jsonb,+ status TEXT NOT NULL DEFAULT 'active',+ installed_at TIMESTAMPTZ NOT NULL DEFAULT now()+ );+ CREATE TABLE chat_session (+ id UUID PRIMARY KEY,+ agent_id UUID+ );+ CREATE TABLE channel_chat_session_binding (+ id UUID PRIMARY KEY,+ chat_session_id UUID NOT NULL,+ installation_id UUID NOT NULL,+ channel_type TEXT NOT NULL,+ channel_chat_id TEXT NOT NULL,+ chat_type TEXT NOT NULL+ );+ CREATE TABLE channel_outbound_card_message (+ id UUID PRIMARY KEY,+ chat_session_id UUID NOT NULL+ );+ `); err != nil {+ t.Fatalf("create removal fixtures: %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)+ }++ const (+ workspaceID = "d3480000-0000-4000-8000-000000000000"+ defaultAgent = "d3480000-0000-4000-8000-000000000001"+ otherAgent = "d3480000-0000-4000-8000-000000000002"+ dingtalkInst = "d3480000-0000-4000-8000-000000000003"+ slackInst = "d3480000-0000-4000-8000-000000000004"+ defaultGroup = "d3480000-0000-4000-8000-000000000005"+ staleGroup = "d3480000-0000-4000-8000-000000000006"+ staleP2P = "d3480000-0000-4000-8000-000000000007"+ otherChannel = "d3480000-0000-4000-8000-000000000008"+ )+ if _, err := conn.Exec(ctx, `+ INSERT INTO channel_installation (id, workspace_id, channel_type, agent_id, config) VALUES+ ($1, $4, 'dingtalk', $3, '{"group_bot_names":{"stale-group":"Migration Bot"}}'),+ ($2, $4, 'slack', $3, '{}')+ `, dingtalkInst, slackInst, defaultAgent, workspaceID); err != nil {+ t.Fatalf("seed installations: %v", err)+ }+ if _, err := conn.Exec(ctx, `+ INSERT INTO chat_session (id, agent_id) VALUES+ ($1, $2),+ ($3, $4),+ ($5, $4),+ ($6, $4)+ `, defaultGroup, defaultAgent, staleGroup, otherAgent, staleP2P, otherChannel); err != nil {+ t.Fatalf("seed chat sessions: %v", err)+ }+ if _, err := conn.Exec(ctx, `+ INSERT INTO dingtalk_group_route (+ workspace_id, installation_id, conversation_id, conversation_title, agent_id, discovered_at+ ) VALUES+ ($1, $2, 'default-group', 'Default group', $3, '2026-01-01T00:00:00Z'),+ ($1, $2, 'stale-group', 'Stale group', $4, '2026-02-01T00:00:00Z')+ `, workspaceID, dingtalkInst, defaultAgent, otherAgent); err != nil {+ t.Fatalf("seed legacy routes: %v", err)+ }+ if _, err := conn.Exec(ctx, `+ INSERT INTO channel_chat_session_binding (+ id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type+ ) VALUES+ (gen_random_uuid(), $3, $1, 'dingtalk', 'default-group', 'group'),+ (gen_random_uuid(), $4, $1, 'dingtalk', 'stale-group', 'group'),+ (gen_random_uuid(), $5, $1, 'dingtalk', 'stale-p2p', 'p2p'),+ (gen_random_uuid(), $6, $2, 'slack', 'other-group', 'group')+ `, dingtalkInst, slackInst, defaultGroup, staleGroup, staleP2P, otherChannel); err != nil {+ t.Fatalf("seed chat bindings: %v", err)+ }+ if _, err := conn.Exec(ctx, `+ INSERT INTO channel_outbound_card_message (id, chat_session_id) VALUES+ (gen_random_uuid(), $1),+ (gen_random_uuid(), $2),+ (gen_random_uuid(), $3),+ (gen_random_uuid(), $4)+ `, defaultGroup, staleGroup, staleP2P, otherChannel); err != nil {+ t.Fatalf("seed outbound cards: %v", err)+ }++ applyMigrationFile(t, ctx, conn.Conn(), "382_remove_dingtalk_group_routing_bindings.up.sql")++ assertMigrationRowCount(t, ctx, conn, "channel_chat_session_binding", 3)+ assertMigrationRowCount(t, ctx, conn, "channel_outbound_card_message", 3)+ var staleBindingExists, staleCardExists bool+ if err := conn.QueryRow(ctx, `SELECT EXISTS (+ SELECT 1 FROM channel_chat_session_binding WHERE chat_session_id = $1+ )`, staleGroup).Scan(&staleBindingExists); err != nil {+ t.Fatalf("inspect stale group binding: %v", err)+ }+ if err := conn.QueryRow(ctx, `SELECT EXISTS (+ SELECT 1 FROM channel_outbound_card_message WHERE chat_session_id = $1+ )`, staleGroup).Scan(&staleCardExists); err != nil {+ t.Fatalf("inspect stale group card: %v", err)+ }+ if staleBindingExists || staleCardExists {+ t.Fatalf("stale group state remains: binding=%t card=%t", staleBindingExists, staleCardExists)+ }++ for _, name := range []string{+ "383_create_dingtalk_group_presence.up.sql",+ "384_create_dingtalk_group_presence_identity_index.up.sql",+ "385_create_dingtalk_group_presence_activity_index.up.sql",+ "386_backfill_dingtalk_group_presence.up.sql",+ "387_create_dingtalk_bot_identity.up.sql",+ "388_create_dingtalk_bot_identity_installation_index.up.sql",+ "389_backfill_dingtalk_bot_identity.up.sql",+ } {+ applyMigrationFile(t, ctx, conn.Conn(), name)+ }+ var routeTableExists, presenceTableExists bool+ if err := conn.QueryRow(ctx, `SELECT to_regclass($1) IS NOT NULL`, dingtalkRoutingRemovalTestSchema+".dingtalk_group_route").Scan(&routeTableExists); err != nil {+ t.Fatalf("inspect retained route table: %v", err)+ }+ if !routeTableExists {+ t.Fatal("legacy route table was removed during the compatibility window")+ }+ if err := conn.QueryRow(ctx, `SELECT to_regclass($1) IS NOT NULL`, dingtalkRoutingRemovalTestSchema+".dingtalk_group_presence").Scan(&presenceTableExists); err != nil {+ t.Fatalf("inspect presence table: %v", err)+ }+ if !presenceTableExists {+ t.Fatal("dingtalk_group_presence was not created")+ }+ var identityTableExists bool+ if err := conn.QueryRow(ctx, `SELECT to_regclass($1) IS NOT NULL`, dingtalkRoutingRemovalTestSchema+".dingtalk_bot_identity").Scan(&identityTableExists); err != nil {+ t.Fatalf("inspect Bot identity table: %v", err)+ }+ if !identityTableExists {+ t.Fatal("dingtalk_bot_identity was not created")+ }+ assertMigrationRowCount(t, ctx, conn, "dingtalk_group_presence", 2)+ assertMigrationRowCount(t, ctx, conn, "dingtalk_bot_identity", 1)+ var title string+ var lastActiveAt *string+ var mentionCount int64+ if err := conn.QueryRow(ctx, `+ SELECT conversation_title, last_active_at::text, mention_count+ FROM dingtalk_group_presence+ WHERE installation_id = $1 AND conversation_id = 'stale-group'+ `, dingtalkInst).Scan(&title, &lastActiveAt, &mentionCount); err != nil {+ t.Fatalf("inspect backfilled presence: %v", err)+ }+ if title != "Stale group" || lastActiveAt != nil || mentionCount != 0 {+ t.Fatalf("backfill = title %q, active %v, mentions %d", title, lastActiveAt, mentionCount)+ }+ var botName string+ if err := conn.QueryRow(ctx, `+ SELECT bot_name FROM dingtalk_bot_identity WHERE installation_id = $1+ `, dingtalkInst).Scan(&botName); err != nil {+ t.Fatalf("inspect backfilled Bot identity: %v", err)+ }+ if botName != "Migration Bot" {+ t.Fatalf("backfilled Bot name = %q, want Migration Bot", botName)+ }++ // An older process keeps writing the route table after the backfill. The+ // compatibility trigger must mirror discoveries without interpreting an+ // admin route revision as message activity.+ if _, err := conn.Exec(ctx, `+ INSERT INTO dingtalk_group_route (+ workspace_id, installation_id, conversation_id, conversation_title, agent_id+ ) VALUES ($1, $2, 'mixed-rollout', 'Mixed rollout', $3)+ `, workspaceID, dingtalkInst, defaultAgent); err != nil {+ t.Fatalf("simulate old-process discovery: %v", err)+ }+ if err := conn.QueryRow(ctx, `+ SELECT last_active_at IS NOT NULL, mention_count+ FROM dingtalk_group_presence+ WHERE installation_id = $1 AND conversation_id = 'mixed-rollout'+ `, dingtalkInst).Scan(&presenceTableExists, &mentionCount); err != nil {+ t.Fatalf("inspect mirrored discovery: %v", err)+ }+ if !presenceTableExists || mentionCount != 1 {+ t.Fatalf("mirrored discovery activity = %t/%d, want true/1", presenceTableExists, mentionCount)+ }+ if _, err := conn.Exec(ctx, `+ UPDATE dingtalk_group_route+ SET agent_id = $2, revision = revision + 1+ WHERE installation_id = $1 AND conversation_id = 'mixed-rollout'+ `, dingtalkInst, otherAgent); err != nil {+ t.Fatalf("simulate legacy route reassignment: %v", err)+ }+ if err := conn.QueryRow(ctx, `+ SELECT mention_count FROM dingtalk_group_presence+ WHERE installation_id = $1 AND conversation_id = 'mixed-rollout'+ `, dingtalkInst).Scan(&mentionCount); err != nil {+ t.Fatalf("inspect route-only update: %v", err)+ }+ if mentionCount != 1 {+ t.Fatalf("route reassignment incremented activity to %d", mentionCount)+ }++ // A process from the previous group-backed draft may still update identity+ // on a presence row during rollout. The compatibility trigger must preserve+ // that installation-level update.+ if _, err := conn.Exec(ctx, `+ UPDATE dingtalk_group_presence+ SET bot_name = 'Old Draft Bot'+ WHERE installation_id = $1 AND conversation_id = 'mixed-rollout'+ `, dingtalkInst); err != nil {+ t.Fatalf("simulate old-draft identity update: %v", err)+ }+ if err := conn.QueryRow(ctx, `+ SELECT bot_name FROM dingtalk_bot_identity WHERE installation_id = $1+ `, dingtalkInst).Scan(&botName); err != nil {+ t.Fatalf("inspect mirrored Bot identity: %v", err)+ }+ if botName != "Old Draft Bot" {+ t.Fatalf("mirrored Bot name = %q, want Old Draft Bot", botName)+ }++ for _, name := range []string{+ "389_backfill_dingtalk_bot_identity.down.sql",+ "388_create_dingtalk_bot_identity_installation_index.down.sql",+ "387_create_dingtalk_bot_identity.down.sql",+ "386_backfill_dingtalk_group_presence.down.sql",+ "385_create_dingtalk_group_presence_activity_index.down.sql",+ "384_create_dingtalk_group_presence_identity_index.down.sql",+ "383_create_dingtalk_group_presence.down.sql",+ "382_remove_dingtalk_group_routing_bindings.down.sql",+ } {+ applyMigrationFile(t, ctx, conn.Conn(), name)+ }+ assertDingTalkRoutingRemovalIndex(t, ctx, conn, "idx_dingtalk_group_route_installation_conversation", true)+ assertDingTalkRoutingRemovalIndex(t, ctx, conn, "idx_dingtalk_group_route_workspace", false)+ assertDingTalkRoutingRemovalIndex(t, ctx, conn, "idx_dingtalk_group_route_id_unique", true)+ if err := conn.QueryRow(ctx, `SELECT to_regclass($1) IS NOT NULL`, dingtalkRoutingRemovalTestSchema+".dingtalk_group_presence").Scan(&presenceTableExists); err != nil {+ t.Fatalf("inspect rolled-back presence table: %v", err)+ }+ if presenceTableExists {+ t.Fatal("presence table remains after rollback")+ }+ if err := conn.QueryRow(ctx, `SELECT to_regclass($1) IS NOT NULL`, dingtalkRoutingRemovalTestSchema+".dingtalk_bot_identity").Scan(&identityTableExists); err != nil {+ t.Fatalf("inspect rolled-back Bot identity table: %v", err)+ }+ if identityTableExists {+ t.Fatal("Bot identity table remains after rollback")+ }+}++func assertMigrationRowCount(t *testing.T, ctx context.Context, conn *pgxpool.Conn, table string, want int) {+ t.Helper()+ var got int+ if err := conn.QueryRow(ctx, "SELECT count(*) FROM "+table).Scan(&got); err != nil {+ t.Fatalf("count %s: %v", table, err)+ }+ if got != want {+ t.Fatalf("%s row count = %d, want %d", table, got, want)+ }+}++func assertDingTalkRoutingRemovalIndex(t *testing.T, ctx context.Context, conn *pgxpool.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+ `, dingtalkRoutingRemovalTestSchema, 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)+ }+}diff --git a/server/migrations/382_remove_dingtalk_group_routing_bindings.down.sql b/server/migrations/382_remove_dingtalk_group_routing_bindings.down.sqlnew file mode 100644index 0000000000..f343220291--- /dev/null+++ b/server/migrations/382_remove_dingtalk_group_routing_bindings.down.sql@@ -0,0 +1,2 @@+-- The removed bindings represented stale cross-agent routing and must not be restored.+SELECT 1;diff --git a/server/migrations/382_remove_dingtalk_group_routing_bindings.up.sql b/server/migrations/382_remove_dingtalk_group_routing_bindings.up.sqlnew file mode 100644index 0000000000..efcb1b8f30--- /dev/null+++ b/server/migrations/382_remove_dingtalk_group_routing_bindings.up.sql@@ -0,0 +1,19 @@+-- A channel chat session is permanently owned by the agent recorded on its+-- chat_session row. Remove only DingTalk group bindings that still point at an+-- agent other than the installation's default so the next @bot message creates+-- a new session for that default agent. Direct messages, other channels, and+-- groups already owned by the default agent keep their existing context.+WITH removed_bindings AS (+ DELETE FROM channel_chat_session_binding binding+ USING channel_installation installation, chat_session session+ WHERE binding.installation_id = installation.id+ AND binding.chat_session_id = session.id+ AND binding.channel_type = 'dingtalk'+ AND binding.chat_type = 'group'+ AND installation.channel_type = 'dingtalk'+ AND session.agent_id IS DISTINCT FROM installation.agent_id+ RETURNING binding.chat_session_id+)+DELETE FROM channel_outbound_card_message outbound+USING removed_bindings removed+WHERE outbound.chat_session_id = removed.chat_session_id;diff --git a/server/migrations/383_create_dingtalk_group_presence.down.sql b/server/migrations/383_create_dingtalk_group_presence.down.sqlnew file mode 100644index 0000000000..db3b494501--- /dev/null+++ b/server/migrations/383_create_dingtalk_group_presence.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS dingtalk_group_presence;diff --git a/server/migrations/383_create_dingtalk_group_presence.up.sql b/server/migrations/383_create_dingtalk_group_presence.up.sqlnew file mode 100644index 0000000000..af8dc09d87--- /dev/null+++ b/server/migrations/383_create_dingtalk_group_presence.up.sql@@ -0,0 +1,16 @@+-- Product-facing DingTalk group inventory. This table records observations and+-- activity only: it deliberately has no agent routing columns or foreign keys.+-- Relationships are enforced and cleaned up by application transactions.+CREATE TABLE dingtalk_group_presence (+ workspace_id UUID NOT NULL,+ installation_id UUID NOT NULL,+ conversation_id TEXT NOT NULL,+ conversation_title TEXT NOT NULL DEFAULT '',+ bot_name TEXT NOT NULL DEFAULT '',+ bot_identity_issue TEXT NOT NULL DEFAULT '',+ first_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ last_active_at TIMESTAMPTZ,+ mention_count BIGINT NOT NULL DEFAULT 0 CHECK (mention_count >= 0),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);diff --git a/server/migrations/384_create_dingtalk_group_presence_identity_index.down.sql b/server/migrations/384_create_dingtalk_group_presence_identity_index.down.sqlnew file mode 100644index 0000000000..494172eccc--- /dev/null+++ b/server/migrations/384_create_dingtalk_group_presence_identity_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_dingtalk_group_presence_installation_conversation;diff --git a/server/migrations/384_create_dingtalk_group_presence_identity_index.up.sql b/server/migrations/384_create_dingtalk_group_presence_identity_index.up.sqlnew file mode 100644index 0000000000..7e2af0fa91--- /dev/null+++ b/server/migrations/384_create_dingtalk_group_presence_identity_index.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_dingtalk_group_presence_installation_conversation ON dingtalk_group_presence(installation_id, conversation_id);diff --git a/server/migrations/385_create_dingtalk_group_presence_activity_index.down.sql b/server/migrations/385_create_dingtalk_group_presence_activity_index.down.sqlnew file mode 100644index 0000000000..342ebaf842--- /dev/null+++ b/server/migrations/385_create_dingtalk_group_presence_activity_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_dingtalk_group_presence_workspace_activity;diff --git a/server/migrations/385_create_dingtalk_group_presence_activity_index.up.sql b/server/migrations/385_create_dingtalk_group_presence_activity_index.up.sqlnew file mode 100644index 0000000000..5d0bb3b7ce--- /dev/null+++ b/server/migrations/385_create_dingtalk_group_presence_activity_index.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_dingtalk_group_presence_workspace_activity ON dingtalk_group_presence(workspace_id, last_active_at DESC NULLS LAST, installation_id, conversation_id);diff --git a/server/migrations/386_backfill_dingtalk_group_presence.down.sql b/server/migrations/386_backfill_dingtalk_group_presence.down.sqlnew file mode 100644index 0000000000..d07cb2af3e--- /dev/null+++ b/server/migrations/386_backfill_dingtalk_group_presence.down.sql@@ -0,0 +1,8 @@+DO $$+BEGIN+ IF to_regclass('dingtalk_group_route') IS NOT NULL THEN+ EXECUTE 'DROP TRIGGER IF EXISTS mirror_legacy_dingtalk_group_route_presence ON dingtalk_group_route';+ END IF;+END;+$$;+DROP FUNCTION IF EXISTS mirror_legacy_dingtalk_group_route_presence();diff --git a/server/migrations/386_backfill_dingtalk_group_presence.up.sql b/server/migrations/386_backfill_dingtalk_group_presence.up.sqlnew file mode 100644index 0000000000..bc76bcfad5--- /dev/null+++ b/server/migrations/386_backfill_dingtalk_group_presence.up.sql@@ -0,0 +1,132 @@+-- Keep accepting writes from an older server process during a mixed-version+-- rollout. Old discovery writes do not expose bot identity, but they must not+-- disappear after the one-time backfill. A route revision change is an admin+-- routing edit, not observed message activity, so it only refreshes the title.+CREATE OR REPLACE FUNCTION mirror_legacy_dingtalk_group_route_presence()+RETURNS trigger+LANGUAGE plpgsql+AS $$+DECLARE+ is_activity BOOLEAN;+BEGIN+ is_activity := TG_OP = 'INSERT';+ IF TG_OP = 'UPDATE' THEN+ is_activity := NEW.revision = OLD.revision;+ END IF;++ INSERT INTO dingtalk_group_presence (+ workspace_id,+ installation_id,+ conversation_id,+ conversation_title,+ first_seen_at,+ last_active_at,+ mention_count+ ) VALUES (+ NEW.workspace_id,+ NEW.installation_id,+ NEW.conversation_id,+ NEW.conversation_title,+ NEW.discovered_at,+ CASE WHEN is_activity THEN now() ELSE NULL END,+ CASE WHEN is_activity THEN 1 ELSE 0 END+ )+ ON CONFLICT (installation_id, conversation_id) DO UPDATE SET+ workspace_id = EXCLUDED.workspace_id,+ conversation_title = CASE+ WHEN EXCLUDED.conversation_title <> '' THEN EXCLUDED.conversation_title+ ELSE dingtalk_group_presence.conversation_title+ END,+ first_seen_at = LEAST(dingtalk_group_presence.first_seen_at, EXCLUDED.first_seen_at),+ last_active_at = CASE+ WHEN is_activity THEN now()+ ELSE dingtalk_group_presence.last_active_at+ END,+ mention_count = dingtalk_group_presence.mention_count + CASE WHEN is_activity THEN 1 ELSE 0 END,+ updated_at = now();++ RETURN NEW;+END;+$$;++DO $$+BEGIN+ IF to_regclass('dingtalk_group_route') IS NOT NULL THEN+ EXECUTE 'CREATE TRIGGER mirror_legacy_dingtalk_group_route_presence+ AFTER INSERT OR UPDATE ON dingtalk_group_route+ FOR EACH ROW+ EXECUTE FUNCTION mirror_legacy_dingtalk_group_route_presence()';+ END IF;+END;+$$;++-- Historical route rows prove that a bot was discovered in a group and retain+-- its title. They do not prove when a message was last processed, so activity+-- remains unknown until a new addressed message succeeds.+-- A draft build briefly persisted observed titles in installation config. This+-- source also makes upgrades from that build recoverable if it already dropped+-- the legacy route table.+INSERT INTO dingtalk_group_presence (+ workspace_id, installation_id, conversation_id, conversation_title,+ bot_name, bot_identity_issue+)+SELECT+ installation.workspace_id,+ installation.id,+ groups.conversation_id,+ groups.conversation_title,+ COALESCE(installation.config -> 'group_bot_names' ->> groups.conversation_id, ''),+ COALESCE(installation.config -> 'group_bot_identity_issues' ->> groups.conversation_id, '')+FROM channel_installation installation+CROSS JOIN LATERAL jsonb_each_text(+ CASE+ WHEN jsonb_typeof(installation.config -> 'group_titles') = 'object'+ THEN installation.config -> 'group_titles'+ ELSE '{}'::jsonb+ END+) AS groups(conversation_id, conversation_title)+WHERE installation.channel_type = 'dingtalk'+ON CONFLICT (installation_id, conversation_id) DO UPDATE SET+ conversation_title = CASE+ WHEN dingtalk_group_presence.conversation_title = '' AND EXCLUDED.conversation_title <> ''+ THEN EXCLUDED.conversation_title+ ELSE dingtalk_group_presence.conversation_title+ END,+ bot_name = CASE+ WHEN EXCLUDED.bot_name <> '' THEN EXCLUDED.bot_name+ ELSE dingtalk_group_presence.bot_name+ END,+ bot_identity_issue = CASE+ WHEN EXCLUDED.bot_identity_issue <> '' THEN EXCLUDED.bot_identity_issue+ ELSE dingtalk_group_presence.bot_identity_issue+ END,+ updated_at = now();++DO $$+BEGIN+ IF to_regclass('dingtalk_group_route') IS NOT NULL THEN+ EXECUTE $backfill$+ INSERT INTO dingtalk_group_presence (+ workspace_id, installation_id, conversation_id,+ conversation_title, first_seen_at+ )+ SELECT+ workspace_id, installation_id, conversation_id,+ conversation_title, discovered_at+ FROM dingtalk_group_route+ ON CONFLICT (installation_id, conversation_id) DO UPDATE SET+ conversation_title = CASE+ WHEN dingtalk_group_presence.conversation_title = ''+ AND EXCLUDED.conversation_title <> ''+ THEN EXCLUDED.conversation_title+ ELSE dingtalk_group_presence.conversation_title+ END,+ first_seen_at = LEAST(+ dingtalk_group_presence.first_seen_at,+ EXCLUDED.first_seen_at+ ),+ updated_at = now()+ $backfill$;+ END IF;+END;+$$;diff --git a/server/migrations/387_create_dingtalk_bot_identity.down.sql b/server/migrations/387_create_dingtalk_bot_identity.down.sqlnew file mode 100644index 0000000000..db92c97686--- /dev/null+++ b/server/migrations/387_create_dingtalk_bot_identity.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS dingtalk_bot_identity;diff --git a/server/migrations/387_create_dingtalk_bot_identity.up.sql b/server/migrations/387_create_dingtalk_bot_identity.up.sqlnew file mode 100644index 0000000000..610c777777--- /dev/null+++ b/server/migrations/387_create_dingtalk_bot_identity.up.sql@@ -0,0 +1,11 @@+-- Bot identity belongs to one DingTalk installation, independently of how many+-- groups have been observed or forgotten. Relationships are enforced and+-- cleaned up by application transactions; no foreign keys are added.+CREATE TABLE dingtalk_bot_identity (+ workspace_id UUID NOT NULL,+ installation_id UUID NOT NULL,+ bot_name TEXT NOT NULL DEFAULT '',+ bot_identity_issue TEXT NOT NULL DEFAULT '',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);diff --git a/server/migrations/388_create_dingtalk_bot_identity_installation_index.down.sql b/server/migrations/388_create_dingtalk_bot_identity_installation_index.down.sqlnew file mode 100644index 0000000000..1fa918ea33--- /dev/null+++ b/server/migrations/388_create_dingtalk_bot_identity_installation_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_dingtalk_bot_identity_installation;diff --git a/server/migrations/388_create_dingtalk_bot_identity_installation_index.up.sql b/server/migrations/388_create_dingtalk_bot_identity_installation_index.up.sqlnew file mode 100644index 0000000000..e6e829dc1d--- /dev/null+++ b/server/migrations/388_create_dingtalk_bot_identity_installation_index.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_dingtalk_bot_identity_installation ON dingtalk_bot_identity(installation_id);diff --git a/server/migrations/389_backfill_dingtalk_bot_identity.down.sql b/server/migrations/389_backfill_dingtalk_bot_identity.down.sqlnew file mode 100644index 0000000000..54b44fa1e0--- /dev/null+++ b/server/migrations/389_backfill_dingtalk_bot_identity.down.sql@@ -0,0 +1,2 @@+DROP TRIGGER IF EXISTS mirror_dingtalk_group_presence_bot_identity ON dingtalk_group_presence;+DROP FUNCTION IF EXISTS mirror_dingtalk_group_presence_bot_identity();diff --git a/server/migrations/389_backfill_dingtalk_bot_identity.up.sql b/server/migrations/389_backfill_dingtalk_bot_identity.up.sqlnew file mode 100644index 0000000000..8c6a98b428--- /dev/null+++ b/server/migrations/389_backfill_dingtalk_bot_identity.up.sql@@ -0,0 +1,102 @@+-- During a mixed-version rollout, a process from the previous draft may still+-- write identity values to group-presence rows. Mirror those writes into the+-- installation-level identity without treating empty transient lookups as new+-- information.+CREATE OR REPLACE FUNCTION mirror_dingtalk_group_presence_bot_identity()+RETURNS trigger+LANGUAGE plpgsql+AS $$+BEGIN+ IF NEW.bot_name = '' AND NEW.bot_identity_issue = '' THEN+ RETURN NEW;+ END IF;++ IF EXISTS (+ SELECT 1+ FROM dingtalk_bot_identity identity+ WHERE identity.installation_id = NEW.installation_id+ AND identity.workspace_id = NEW.workspace_id+ AND identity.bot_name = NEW.bot_name+ AND identity.bot_identity_issue = NEW.bot_identity_issue+ ) THEN+ RETURN NEW;+ END IF;++ INSERT INTO dingtalk_bot_identity (+ workspace_id, installation_id, bot_name, bot_identity_issue+ ) VALUES (+ NEW.workspace_id, NEW.installation_id, NEW.bot_name, NEW.bot_identity_issue+ )+ ON CONFLICT (installation_id) DO UPDATE SET+ workspace_id = EXCLUDED.workspace_id,+ bot_name = CASE+ WHEN EXCLUDED.bot_name <> '' THEN EXCLUDED.bot_name+ ELSE dingtalk_bot_identity.bot_name+ END,+ bot_identity_issue = CASE+ WHEN EXCLUDED.bot_identity_issue <> '' THEN EXCLUDED.bot_identity_issue+ WHEN EXCLUDED.bot_name <> '' THEN ''+ ELSE dingtalk_bot_identity.bot_identity_issue+ END,+ updated_at = now();++ RETURN NEW;+END;+$$;++CREATE TRIGGER mirror_dingtalk_group_presence_bot_identity+AFTER INSERT OR UPDATE OF bot_name, bot_identity_issue ON dingtalk_group_presence+FOR EACH ROW+EXECUTE FUNCTION mirror_dingtalk_group_presence_bot_identity();++-- Prefer normalized observations, then recover identity written by the brief+-- config-backed draft. Empty rows are still useful: they preserve the fact that+-- an installation has been observed without inventing a readable Bot name.+INSERT INTO dingtalk_bot_identity (+ workspace_id, installation_id, bot_name, bot_identity_issue+)+SELECT+ installation.workspace_id,+ installation.id,+ COALESCE(presence.bot_name, config_name.bot_name, ''),+ COALESCE(presence.bot_identity_issue, config_issue.bot_identity_issue, '')+FROM channel_installation installation+LEFT JOIN LATERAL (+ SELECT+ max(NULLIF(bot_name, ''))::text AS bot_name,+ max(NULLIF(bot_identity_issue, ''))::text AS bot_identity_issue+ FROM dingtalk_group_presence+ WHERE installation_id = installation.id+) presence ON true+LEFT JOIN LATERAL (+ SELECT max(NULLIF(value, ''))::text AS bot_name+ FROM jsonb_each_text(+ CASE+ WHEN jsonb_typeof(installation.config -> 'group_bot_names') = 'object'+ THEN installation.config -> 'group_bot_names'+ ELSE '{}'::jsonb+ END+ )+) config_name ON true+LEFT JOIN LATERAL (+ SELECT max(NULLIF(value, ''))::text AS bot_identity_issue+ FROM jsonb_each_text(+ CASE+ WHEN jsonb_typeof(installation.config -> 'group_bot_identity_issues') = 'object'+ THEN installation.config -> 'group_bot_identity_issues'+ ELSE '{}'::jsonb+ END+ )+) config_issue ON true+WHERE installation.channel_type = 'dingtalk'+ON CONFLICT (installation_id) DO UPDATE SET+ workspace_id = EXCLUDED.workspace_id,+ bot_name = CASE+ WHEN EXCLUDED.bot_name <> '' THEN EXCLUDED.bot_name+ ELSE dingtalk_bot_identity.bot_name+ END,+ bot_identity_issue = CASE+ WHEN EXCLUDED.bot_identity_issue <> '' THEN EXCLUDED.bot_identity_issue+ ELSE dingtalk_bot_identity.bot_identity_issue+ END,+ updated_at = now();diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.goindex 7f9a4b145f..f142116188 100644--- a/server/pkg/db/generated/channel.sql.go+++ b/server/pkg/db/generated/channel.sql.go@@ -575,13 +575,19 @@ WITH doomed AS (SELECT id FROM agent WHERE runtime_id = $1 AND kind = 'system')),-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_presence AS (+ DELETE FROM dingtalk_group_presence WHERE installation_id IN (SELECT id FROM doomed)+),+cleared_dingtalk_bot_identity AS (+ DELETE FROM dingtalk_bot_identity WHERE installation_id IN (SELECT id FROM doomed)),cleared_dingtalk_group_routes AS (DELETE FROM dingtalk_group_route WHERE installation_id IN (SELECT id FROM doomed)),+cleared_chat_sessions AS (+ DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM doomed)+ RETURNING chat_session_id+),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.@@ -1539,15 +1545,20 @@ WITH dead AS ()RETURNING ci.id),+cleared_dingtalk_group_presence AS (+ DELETE FROM dingtalk_group_presence WHERE installation_id IN (SELECT id FROM dead)+),+cleared_dingtalk_bot_identity AS (+ DELETE FROM dingtalk_bot_identity WHERE installation_id IN (SELECT id FROM dead)+),+cleared_dingtalk_group_routes AS (+ DELETE FROM dingtalk_group_route WHERE installation_id IN (SELECT id FROM dead)+),cleared_chat_sessions AS (DELETE FROM channel_chat_session_bindingWHERE 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 andiff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex 7d6a57a079..34cab339cc 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -2090,24 +2090,6 @@ func (q *Queries) ListPendingChatTasksForSession(ctx context.Context, chatSessioreturn 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 :oneSELECT id FROM chat_sessionWHERE id = $1diff --git a/server/pkg/db/generated/dingtalk.sql.go b/server/pkg/db/generated/dingtalk.sql.goindex 082a34a742..c4bf342945 100644--- a/server/pkg/db/generated/dingtalk.sql.go+++ b/server/pkg/db/generated/dingtalk.sql.go@@ -11,6 +11,56 @@ import ("github.com/jackc/pgx/v5/pgtype")+const countInactiveDingTalkGroupPresencesByWorkspace = `-- name: CountInactiveDingTalkGroupPresencesByWorkspace :many+SELECT presence.installation_id, installation.agent_id, count(*)::bigint AS group_count+FROM dingtalk_group_presence presence+JOIN channel_installation installation ON installation.id = presence.installation_id+WHERE installation.workspace_id = $1+ AND installation.channel_type = 'dingtalk'+ AND installation.status = 'active'+ AND (presence.last_active_at < $2 OR presence.last_active_at IS NULL)+ AND (NOT $3::boolean OR installation.agent_id = $4)+GROUP BY presence.installation_id, installation.agent_id+`++type CountInactiveDingTalkGroupPresencesByWorkspaceParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ActiveSince pgtype.Timestamptz `json:"active_since"`+ FilterByAgent bool `json:"filter_by_agent"`+ AgentID pgtype.UUID `json:"agent_id"`+}++type CountInactiveDingTalkGroupPresencesByWorkspaceRow struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ GroupCount int64 `json:"group_count"`+}++func (q *Queries) CountInactiveDingTalkGroupPresencesByWorkspace(ctx context.Context, arg CountInactiveDingTalkGroupPresencesByWorkspaceParams) ([]CountInactiveDingTalkGroupPresencesByWorkspaceRow, error) {+ rows, err := q.db.Query(ctx, countInactiveDingTalkGroupPresencesByWorkspace,+ arg.WorkspaceID,+ arg.ActiveSince,+ arg.FilterByAgent,+ arg.AgentID,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []CountInactiveDingTalkGroupPresencesByWorkspaceRow{}+ for rows.Next() {+ var i CountInactiveDingTalkGroupPresencesByWorkspaceRow+ if err := rows.Scan(&i.InstallationID, &i.AgentID, &i.GroupCount); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const deleteDingTalkInstallationForReplacement = `-- name: DeleteDingTalkInstallationForReplacement :oneWITH retired AS (DELETE FROM channel_installation ci@@ -20,15 +70,23 @@ WITH retired AS (AND ci.channel_type = 'dingtalk'RETURNING ci.id),-cleared_chat_sessions AS (- DELETE FROM channel_chat_session_binding+cleared_group_presence AS (+ DELETE FROM dingtalk_group_presence+ WHERE installation_id IN (SELECT id FROM retired)+),+cleared_bot_identity AS (+ DELETE FROM dingtalk_bot_identityWHERE installation_id IN (SELECT id FROM retired)- RETURNING chat_session_id),cleared_group_routes AS (DELETE FROM dingtalk_group_routeWHERE installation_id IN (SELECT id FROM retired)),+cleared_chat_sessions AS (+ DELETE FROM channel_chat_session_binding+ WHERE installation_id IN (SELECT id FROM retired)+ RETURNING chat_session_id+),cleared_outbound_cards AS (DELETE FROM channel_outbound_card_messageWHERE chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)@@ -79,201 +137,29 @@ 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+const forgetDingTalkGroupPresence = `-- name: ForgetDingTalkGroupPresence :one+DELETE FROM dingtalk_group_presence presence+USING channel_installation installation+WHERE presence.installation_id = installation.id+ AND presence.workspace_id = $1+ AND presence.installation_id = $2+ AND presence.conversation_id = $3+ AND installation.workspace_id = $1+ AND installation.channel_type = 'dingtalk'+RETURNING presence.installation_id`-type DingTalkGroupRouteMatchesAgentParams struct {+type ForgetDingTalkGroupPresenceParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`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"`-}--// 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"`}-// 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.-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+func (q *Queries) ForgetDingTalkGroupPresence(ctx context.Context, arg ForgetDingTalkGroupPresenceParams) (pgtype.UUID, error) {+ row := q.db.QueryRow(ctx, forgetDingTalkGroupPresence, arg.WorkspaceID, arg.InstallationID, arg.ConversationID)+ var installation_id pgtype.UUID+ err := row.Scan(&installation_id)+ return installation_id, err}const getDingTalkInstallationOwnerForUpdate = `-- name: GetDingTalkInstallationOwnerForUpdate :one@@ -306,36 +192,141 @@ func (q *Queries) GetDingTalkInstallationOwnerForUpdate(ctx context.Context, argreturn i, err}-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+const listDingTalkBotIdentitiesByWorkspace = `-- name: ListDingTalkBotIdentitiesByWorkspace :many+SELECT+ installation.id AS installation_id,+ installation.agent_id,+ identity.bot_name,+ identity.bot_identity_issue+FROM channel_installation installation+JOIN dingtalk_bot_identity identity ON identity.installation_id = installation.id+WHERE installation.workspace_id = $1+ AND installation.channel_type = 'dingtalk'+ AND installation.status = 'active'+ AND (NOT $2::boolean OR installation.agent_id = $3)`-func (q *Queries) ListDingTalkGroupRoutesByWorkspace(ctx context.Context, workspaceID pgtype.UUID) ([]DingtalkGroupRoute, error) {- rows, err := q.db.Query(ctx, listDingTalkGroupRoutesByWorkspace, workspaceID)+type ListDingTalkBotIdentitiesByWorkspaceParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ FilterByAgent bool `json:"filter_by_agent"`+ AgentID pgtype.UUID `json:"agent_id"`+}++type ListDingTalkBotIdentitiesByWorkspaceRow struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ BotName string `json:"bot_name"`+ BotIdentityIssue string `json:"bot_identity_issue"`+}++// Identity is installation-owned, so forgetting or collapsing groups cannot+// change the connection label.+func (q *Queries) ListDingTalkBotIdentitiesByWorkspace(ctx context.Context, arg ListDingTalkBotIdentitiesByWorkspaceParams) ([]ListDingTalkBotIdentitiesByWorkspaceRow, error) {+ rows, err := q.db.Query(ctx, listDingTalkBotIdentitiesByWorkspace, arg.WorkspaceID, arg.FilterByAgent, arg.AgentID)if err != nil {return nil, err}defer rows.Close()- items := []DingtalkGroupRoute{}+ items := []ListDingTalkBotIdentitiesByWorkspaceRow{}for rows.Next() {- var i DingtalkGroupRoute+ var i ListDingTalkBotIdentitiesByWorkspaceRowif err := rows.Scan(- &i.ID,- &i.WorkspaceID,&i.InstallationID,+ &i.AgentID,+ &i.BotName,+ &i.BotIdentityIssue,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listDingTalkGroupPresencesByWorkspace = `-- name: ListDingTalkGroupPresencesByWorkspace :many+SELECT+ presence.conversation_id,+ presence.conversation_title,+ presence.installation_id,+ installation.agent_id,+ COALESCE(identity.bot_name, presence.bot_name)::text AS bot_name,+ COALESCE(identity.bot_identity_issue, presence.bot_identity_issue)::text AS bot_identity_issue,+ presence.last_active_at,+ presence.mention_count+FROM dingtalk_group_presence presence+JOIN channel_installation installation ON installation.id = presence.installation_id+LEFT JOIN dingtalk_bot_identity identity ON identity.installation_id = presence.installation_id+WHERE installation.workspace_id = $1+ AND installation.channel_type = 'dingtalk'+ AND installation.status = 'active'+ AND (NOT $2::boolean OR installation.agent_id = $3)+ AND (NOT $4::boolean OR installation.id = $5)+ AND (+ (NOT $6::boolean AND presence.last_active_at >= $7)+ OR ($6::boolean AND (presence.last_active_at < $7 OR presence.last_active_at IS NULL))+ )+ORDER BY presence.last_active_at DESC NULLS LAST, presence.conversation_title ASC,+ presence.conversation_id ASC, installation.installed_at ASC, installation.id ASC+LIMIT NULLIF($9::integer, 0)+OFFSET $8::integer+`++type ListDingTalkGroupPresencesByWorkspaceParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ FilterByAgent bool `json:"filter_by_agent"`+ AgentID pgtype.UUID `json:"agent_id"`+ FilterByInstallation bool `json:"filter_by_installation"`+ FilterInstallationID pgtype.UUID `json:"filter_installation_id"`+ IncludeInactive bool `json:"include_inactive"`+ ActiveSince pgtype.Timestamptz `json:"active_since"`+ PageOffset int32 `json:"page_offset"`+ PageLimit int32 `json:"page_limit"`+}++type ListDingTalkGroupPresencesByWorkspaceRow struct {+ ConversationID string `json:"conversation_id"`+ ConversationTitle string `json:"conversation_title"`+ InstallationID pgtype.UUID `json:"installation_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ BotName string `json:"bot_name"`+ BotIdentityIssue string `json:"bot_identity_issue"`+ LastActiveAt pgtype.Timestamptz `json:"last_active_at"`+ MentionCount int64 `json:"mention_count"`+}++// Active rows are the default inventory. Inactive rows are loaded only when a+// client expands one installation's historical section.+func (q *Queries) ListDingTalkGroupPresencesByWorkspace(ctx context.Context, arg ListDingTalkGroupPresencesByWorkspaceParams) ([]ListDingTalkGroupPresencesByWorkspaceRow, error) {+ rows, err := q.db.Query(ctx, listDingTalkGroupPresencesByWorkspace,+ arg.WorkspaceID,+ arg.FilterByAgent,+ arg.AgentID,+ arg.FilterByInstallation,+ arg.FilterInstallationID,+ arg.IncludeInactive,+ arg.ActiveSince,+ arg.PageOffset,+ arg.PageLimit,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListDingTalkGroupPresencesByWorkspaceRow{}+ for rows.Next() {+ var i ListDingTalkGroupPresencesByWorkspaceRow+ if err := rows.Scan(&i.ConversationID,&i.ConversationTitle,+ &i.InstallationID,&i.AgentID,- &i.Revision,- &i.DiscoveredAt,- &i.UpdatedAt,+ &i.BotName,+ &i.BotIdentityIssue,+ &i.LastActiveAt,+ &i.MentionCount,); err != nil {return nil, err}@@ -393,49 +384,6 @@ func (q *Queries) ListDingTalkUserBindingsForMember(ctx context.Context, arg Lisreturn 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 :execSELECT pg_advisory_xact_lock(hashtextextended(@@ -461,105 +409,171 @@ func (q *Queries) LockDingTalkInstallationOwner(ctx context.Context, arg LockDinreturn err}-const reassignDingTalkGroupRoute = `-- name: ReassignDingTalkGroupRoute :one-WITH workspace_guard AS MATERIALIZED (- SELECT w.id- FROM workspace w- WHERE w.id = $1+const recordDingTalkGroupActivity = `-- name: RecordDingTalkGroupActivity :one+UPDATE dingtalk_group_presence+SET last_active_at = now(), mention_count = mention_count + 1, updated_at = now()+WHERE installation_id = $1+ AND conversation_id = $2+RETURNING installation_id+`++type RecordDingTalkGroupActivityParams struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ ConversationID string `json:"conversation_id"`+}++// Advances activity only after the deduplicated inbound message is durable.+// Presence observation runs first, so a forgotten group is recreated before+// this update executes.+func (q *Queries) RecordDingTalkGroupActivity(ctx context.Context, arg RecordDingTalkGroupActivityParams) (pgtype.UUID, error) {+ row := q.db.QueryRow(ctx, recordDingTalkGroupActivity, arg.InstallationID, arg.ConversationID)+ var installation_id pgtype.UUID+ err := row.Scan(&installation_id)+ return installation_id, err+}++const recordDingTalkGroupPresence = `-- name: RecordDingTalkGroupPresence :one+WITH target AS MATERIALIZED (+ SELECT channel_installation.id, channel_installation.workspace_id+ FROM channel_installation+ WHERE channel_installation.id = $1+ AND channel_installation.workspace_id = $2+ AND channel_installation.channel_type = 'dingtalk'+ AND channel_installation.status = 'active'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 = $2- AND a.workspace_id = $1- 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 = $1- AND i.workspace_id = $1- 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 = $1- FOR UPDATE OF r-), updated AS (- UPDATE dingtalk_group_route r- SET agent_id = $2,- revision = r.revision + 1,+), current_identity AS (+ SELECT identity.installation_id, identity.bot_name, identity.bot_identity_issue+ FROM target+ JOIN dingtalk_bot_identity identity ON identity.installation_id = target.id+), observed AS (+ INSERT INTO dingtalk_group_presence (+ workspace_id, installation_id, conversation_id, conversation_title,+ bot_name, bot_identity_issue+ )+ SELECT+ target.workspace_id,+ target.id,+ $3::text,+ $4::text,+ current_identity.bot_name,+ current_identity.bot_identity_issue+ FROM target+ JOIN current_identity ON current_identity.installation_id = target.id+ ON CONFLICT (installation_id, conversation_id) DO UPDATE SET+ conversation_title = CASE+ WHEN EXCLUDED.conversation_title <> '' THEN EXCLUDED.conversation_title+ ELSE dingtalk_group_presence.conversation_title+ END,+ bot_name = EXCLUDED.bot_name,+ bot_identity_issue = EXCLUDED.bot_identity_issue,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)+ WHERE (+ dingtalk_group_presence.conversation_title IS DISTINCT FROM EXCLUDED.conversation_title+ AND EXCLUDED.conversation_title <> ''+ )+ OR dingtalk_group_presence.bot_name IS DISTINCT FROM EXCLUDED.bot_name+ OR dingtalk_group_presence.bot_identity_issue IS DISTINCT FROM EXCLUDED.bot_identity_issue+ RETURNING installation_id+), synced_identity AS (+ UPDATE dingtalk_group_presence presence+ SET+ bot_name = current_identity.bot_name,+ bot_identity_issue = current_identity.bot_identity_issue,+ updated_at = now()+ FROM current_identity+ WHERE presence.installation_id = current_identity.installation_id+ AND presence.conversation_id <> $3::text+ AND (+ presence.bot_name IS DISTINCT FROM current_identity.bot_name+ OR presence.bot_identity_issue IS DISTINCT FROM current_identity.bot_identity_issue+ ))-SELECT id, workspace_id, installation_id, conversation_id,- conversation_title, agent_id, revision, discovered_at, updated_at-FROM updated+SELECT target.id FROM target`-type ReassignDingTalkGroupRouteParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- AgentID pgtype.UUID `json:"agent_id"`- ID pgtype.UUID `json:"id"`+type RecordDingTalkGroupPresenceParams struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ConversationID string `json:"conversation_id"`+ ConversationTitle string `json:"conversation_title"`}-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"`+// Records an observed bot/group pair without carrying routing state. The+// installation identity is copied only for compatibility with the preceding+// draft; readers use dingtalk_bot_identity as the authority.+func (q *Queries) RecordDingTalkGroupPresence(ctx context.Context, arg RecordDingTalkGroupPresenceParams) (pgtype.UUID, error) {+ row := q.db.QueryRow(ctx, recordDingTalkGroupPresence,+ arg.InstallationID,+ arg.WorkspaceID,+ arg.ConversationID,+ arg.ConversationTitle,+ )+ var id pgtype.UUID+ err := row.Scan(&id)+ return id, err}-// 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.WorkspaceID, arg.AgentID, 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,+const upsertDingTalkBotIdentity = `-- name: UpsertDingTalkBotIdentity :one+WITH target AS MATERIALIZED (+ SELECT channel_installation.id, channel_installation.workspace_id+ FROM channel_installation+ WHERE channel_installation.id = $1+ AND channel_installation.workspace_id = $2+ AND channel_installation.channel_type = 'dingtalk'+ AND channel_installation.status = 'active'+ FOR UPDATE+), prior_identity AS (+ SELECT+ COALESCE(identity.bot_name, '')::text AS bot_name,+ COALESCE(identity.bot_identity_issue, '')::text AS bot_identity_issue+ FROM target+ LEFT JOIN dingtalk_bot_identity identity ON identity.installation_id = target.id+), upserted_identity AS (+ INSERT INTO dingtalk_bot_identity (+ workspace_id, installation_id, bot_name, bot_identity_issue+ )+ SELECT+ target.workspace_id,+ target.id,+ COALESCE(NULLIF($3::text, ''), prior_identity.bot_name),+ CASE+ WHEN $4::text <> '' THEN $4::text+ WHEN $3::text <> '' THEN ''+ ELSE prior_identity.bot_identity_issue+ END+ FROM target, prior_identity+ ON CONFLICT (installation_id) DO UPDATE SET+ workspace_id = EXCLUDED.workspace_id,+ bot_name = EXCLUDED.bot_name,+ bot_identity_issue = EXCLUDED.bot_identity_issue,+ updated_at = now()+ WHERE dingtalk_bot_identity.workspace_id IS DISTINCT FROM EXCLUDED.workspace_id+ OR dingtalk_bot_identity.bot_name IS DISTINCT FROM EXCLUDED.bot_name+ OR dingtalk_bot_identity.bot_identity_issue IS DISTINCT FROM EXCLUDED.bot_identity_issue+ RETURNING installation_id+)+SELECT target.id FROM target+`++type UpsertDingTalkBotIdentityParams struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ BotName string `json:"bot_name"`+ BotIdentityIssue string `json:"bot_identity_issue"`+}++// Bot identity and the optional permission issue belong to the installation,+// not to any one group. Keep this as a separate command so the mixed-version+// compatibility trigger can observe the completed command state when the+// group-presence command runs next.+func (q *Queries) UpsertDingTalkBotIdentity(ctx context.Context, arg UpsertDingTalkBotIdentityParams) (pgtype.UUID, error) {+ row := q.db.QueryRow(ctx, upsertDingTalkBotIdentity,+ arg.InstallationID,+ arg.WorkspaceID,+ arg.BotName,+ arg.BotIdentityIssue,)- return i, err+ var id pgtype.UUID+ err := row.Scan(&id)+ return id, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 61f6e8ffb7..dd5c700622 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -546,6 +546,29 @@ type DaemonToken struct {CreatedAt pgtype.Timestamptz `json:"created_at"`}+type DingtalkBotIdentity struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ BotName string `json:"bot_name"`+ BotIdentityIssue string `json:"bot_identity_issue"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}++type DingtalkGroupPresence struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ ConversationID string `json:"conversation_id"`+ ConversationTitle string `json:"conversation_title"`+ BotName string `json:"bot_name"`+ BotIdentityIssue string `json:"bot_identity_issue"`+ FirstSeenAt pgtype.Timestamptz `json:"first_seen_at"`+ LastActiveAt pgtype.Timestamptz `json:"last_active_at"`+ MentionCount int64 `json:"mention_count"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type DingtalkGroupRoute struct {ID pgtype.UUID `json:"id"`WorkspaceID pgtype.UUID `json:"workspace_id"`diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.goindex 324f50cf47..ecdb8474e3 100644--- a/server/pkg/db/generated/workspace.sql.go+++ b/server/pkg/db/generated/workspace.sql.go@@ -72,9 +72,6 @@ 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@@ -98,6 +95,15 @@ cleared_draft_restores AS (cleared_inbound_dedup AS (DELETE FROM channel_inbound_message_dedup WHERE installation_id IN (SELECT id FROM ws_installations)),+cleared_dingtalk_group_presence AS (+ DELETE FROM dingtalk_group_presence WHERE installation_id IN (SELECT id FROM ws_installations)+),+cleared_dingtalk_bot_identity AS (+ DELETE FROM dingtalk_bot_identity WHERE installation_id IN (SELECT id FROM ws_installations)+),+cleared_dingtalk_group_routes AS (+ DELETE FROM dingtalk_group_route WHERE workspace_id = $1+),cleared_audit AS (-- Purge, don't detach: the workspace is gone and channel_inbound_audit has no-- workspace_id and no reaper, so a detached (NULL) row would be permanentlydiff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex e7a4da5a04..f7a8fabda9 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -192,6 +192,12 @@ WITHdeleted_sessions AS (DELETE FROM chat_session WHERE chat_session.workspace_id = $1),+deleted_dingtalk_group_presence AS (+ DELETE FROM dingtalk_group_presence WHERE workspace_id = $1+),+deleted_dingtalk_bot_identity AS (+ DELETE FROM dingtalk_bot_identity WHERE workspace_id = $1+),deleted_channel_installations AS (DELETE FROM channel_installationWHERE channel_installation.workspace_id = $1diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sqlindex 3f6c712b76..2e9da7293b 100644--- a/server/pkg/db/queries/channel.sql+++ b/server/pkg/db/queries/channel.sql@@ -204,15 +204,20 @@ WITH dead AS ()RETURNING ci.id),+cleared_dingtalk_group_presence AS (+ DELETE FROM dingtalk_group_presence WHERE installation_id IN (SELECT id FROM dead)+),+cleared_dingtalk_bot_identity AS (+ DELETE FROM dingtalk_bot_identity WHERE installation_id IN (SELECT id FROM dead)+),+cleared_dingtalk_group_routes AS (+ DELETE FROM dingtalk_group_route WHERE installation_id IN (SELECT id FROM dead)+),cleared_chat_sessions AS (DELETE FROM channel_chat_session_bindingWHERE 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,13 +265,19 @@ WITH doomed AS (SELECT id FROM agent WHERE runtime_id = sqlc.arg('runtime_id') AND kind = 'system')),-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_presence AS (+ DELETE FROM dingtalk_group_presence WHERE installation_id IN (SELECT id FROM doomed)+),+cleared_dingtalk_bot_identity AS (+ DELETE FROM dingtalk_bot_identity WHERE installation_id IN (SELECT id FROM doomed)),cleared_dingtalk_group_routes AS (DELETE FROM dingtalk_group_route WHERE installation_id IN (SELECT id FROM doomed)),+cleared_chat_sessions AS (+ DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM doomed)+ RETURNING chat_session_id+),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.sqlindex ebc078aeaa..8870c8c589 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -332,16 +332,6 @@ SELECT id FROM chat_sessionWHERE id = $1FOR 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.sqlindex f95641e545..99fc63c9d9 100644--- a/server/pkg/db/queries/dingtalk.sql+++ b/server/pkg/db/queries/dingtalk.sql@@ -13,220 +13,6 @@ WHERE workspace_id = sqlc.arg(workspace_id)AND channel_type = 'dingtalk'ORDER BY bound_at DESC, id ASC;--- 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@@ -253,6 +39,188 @@ WHERE workspace_id = sqlc.arg(workspace_id)AND channel_type = 'dingtalk'FOR UPDATE;+-- name: UpsertDingTalkBotIdentity :one+-- Bot identity and the optional permission issue belong to the installation,+-- not to any one group. Keep this as a separate command so the mixed-version+-- compatibility trigger can observe the completed command state when the+-- group-presence command runs next.+WITH target AS MATERIALIZED (+ SELECT channel_installation.id, channel_installation.workspace_id+ FROM channel_installation+ WHERE channel_installation.id = sqlc.arg(installation_id)+ AND channel_installation.workspace_id = sqlc.arg(workspace_id)+ AND channel_installation.channel_type = 'dingtalk'+ AND channel_installation.status = 'active'+ FOR UPDATE+), prior_identity AS (+ SELECT+ COALESCE(identity.bot_name, '')::text AS bot_name,+ COALESCE(identity.bot_identity_issue, '')::text AS bot_identity_issue+ FROM target+ LEFT JOIN dingtalk_bot_identity identity ON identity.installation_id = target.id+), upserted_identity AS (+ INSERT INTO dingtalk_bot_identity (+ workspace_id, installation_id, bot_name, bot_identity_issue+ )+ SELECT+ target.workspace_id,+ target.id,+ COALESCE(NULLIF(sqlc.arg(bot_name)::text, ''), prior_identity.bot_name),+ CASE+ WHEN sqlc.arg(bot_identity_issue)::text <> '' THEN sqlc.arg(bot_identity_issue)::text+ WHEN sqlc.arg(bot_name)::text <> '' THEN ''+ ELSE prior_identity.bot_identity_issue+ END+ FROM target, prior_identity+ ON CONFLICT (installation_id) DO UPDATE SET+ workspace_id = EXCLUDED.workspace_id,+ bot_name = EXCLUDED.bot_name,+ bot_identity_issue = EXCLUDED.bot_identity_issue,+ updated_at = now()+ WHERE dingtalk_bot_identity.workspace_id IS DISTINCT FROM EXCLUDED.workspace_id+ OR dingtalk_bot_identity.bot_name IS DISTINCT FROM EXCLUDED.bot_name+ OR dingtalk_bot_identity.bot_identity_issue IS DISTINCT FROM EXCLUDED.bot_identity_issue+ RETURNING installation_id+)+SELECT target.id FROM target;++-- name: RecordDingTalkGroupPresence :one+-- Records an observed bot/group pair without carrying routing state. The+-- installation identity is copied only for compatibility with the preceding+-- draft; readers use dingtalk_bot_identity as the authority.+WITH target AS MATERIALIZED (+ SELECT channel_installation.id, channel_installation.workspace_id+ FROM channel_installation+ WHERE channel_installation.id = sqlc.arg(installation_id)+ AND channel_installation.workspace_id = sqlc.arg(workspace_id)+ AND channel_installation.channel_type = 'dingtalk'+ AND channel_installation.status = 'active'+ FOR KEY SHARE+), current_identity AS (+ SELECT identity.installation_id, identity.bot_name, identity.bot_identity_issue+ FROM target+ JOIN dingtalk_bot_identity identity ON identity.installation_id = target.id+), observed AS (+ INSERT INTO dingtalk_group_presence (+ workspace_id, installation_id, conversation_id, conversation_title,+ bot_name, bot_identity_issue+ )+ SELECT+ target.workspace_id,+ target.id,+ sqlc.arg(conversation_id)::text,+ sqlc.arg(conversation_title)::text,+ current_identity.bot_name,+ current_identity.bot_identity_issue+ FROM target+ JOIN current_identity ON current_identity.installation_id = target.id+ ON CONFLICT (installation_id, conversation_id) DO UPDATE SET+ conversation_title = CASE+ WHEN EXCLUDED.conversation_title <> '' THEN EXCLUDED.conversation_title+ ELSE dingtalk_group_presence.conversation_title+ END,+ bot_name = EXCLUDED.bot_name,+ bot_identity_issue = EXCLUDED.bot_identity_issue,+ updated_at = now()+ WHERE (+ dingtalk_group_presence.conversation_title IS DISTINCT FROM EXCLUDED.conversation_title+ AND EXCLUDED.conversation_title <> ''+ )+ OR dingtalk_group_presence.bot_name IS DISTINCT FROM EXCLUDED.bot_name+ OR dingtalk_group_presence.bot_identity_issue IS DISTINCT FROM EXCLUDED.bot_identity_issue+ RETURNING installation_id+), synced_identity AS (+ UPDATE dingtalk_group_presence presence+ SET+ bot_name = current_identity.bot_name,+ bot_identity_issue = current_identity.bot_identity_issue,+ updated_at = now()+ FROM current_identity+ WHERE presence.installation_id = current_identity.installation_id+ AND presence.conversation_id <> sqlc.arg(conversation_id)::text+ AND (+ presence.bot_name IS DISTINCT FROM current_identity.bot_name+ OR presence.bot_identity_issue IS DISTINCT FROM current_identity.bot_identity_issue+ )+)+SELECT target.id FROM target;++-- name: RecordDingTalkGroupActivity :one+-- Advances activity only after the deduplicated inbound message is durable.+-- Presence observation runs first, so a forgotten group is recreated before+-- this update executes.+UPDATE dingtalk_group_presence+SET last_active_at = now(), mention_count = mention_count + 1, updated_at = now()+WHERE installation_id = sqlc.arg(installation_id)+ AND conversation_id = sqlc.arg(conversation_id)+RETURNING installation_id;++-- name: ListDingTalkGroupPresencesByWorkspace :many+-- Active rows are the default inventory. Inactive rows are loaded only when a+-- client expands one installation's historical section.+SELECT+ presence.conversation_id,+ presence.conversation_title,+ presence.installation_id,+ installation.agent_id,+ COALESCE(identity.bot_name, presence.bot_name)::text AS bot_name,+ COALESCE(identity.bot_identity_issue, presence.bot_identity_issue)::text AS bot_identity_issue,+ presence.last_active_at,+ presence.mention_count+FROM dingtalk_group_presence presence+JOIN channel_installation installation ON installation.id = presence.installation_id+LEFT JOIN dingtalk_bot_identity identity ON identity.installation_id = presence.installation_id+WHERE installation.workspace_id = sqlc.arg(workspace_id)+ AND installation.channel_type = 'dingtalk'+ AND installation.status = 'active'+ AND (NOT sqlc.arg(filter_by_agent)::boolean OR installation.agent_id = sqlc.arg(agent_id))+ AND (NOT sqlc.arg(filter_by_installation)::boolean OR installation.id = sqlc.arg(filter_installation_id))+ AND (+ (NOT sqlc.arg(include_inactive)::boolean AND presence.last_active_at >= sqlc.arg(active_since))+ OR (sqlc.arg(include_inactive)::boolean AND (presence.last_active_at < sqlc.arg(active_since) OR presence.last_active_at IS NULL))+ )+ORDER BY presence.last_active_at DESC NULLS LAST, presence.conversation_title ASC,+ presence.conversation_id ASC, installation.installed_at ASC, installation.id ASC+LIMIT NULLIF(sqlc.arg(page_limit)::integer, 0)+OFFSET sqlc.arg(page_offset)::integer;++-- name: CountInactiveDingTalkGroupPresencesByWorkspace :many+SELECT presence.installation_id, installation.agent_id, count(*)::bigint AS group_count+FROM dingtalk_group_presence presence+JOIN channel_installation installation ON installation.id = presence.installation_id+WHERE installation.workspace_id = sqlc.arg(workspace_id)+ AND installation.channel_type = 'dingtalk'+ AND installation.status = 'active'+ AND (presence.last_active_at < sqlc.arg(active_since) OR presence.last_active_at IS NULL)+ AND (NOT sqlc.arg(filter_by_agent)::boolean OR installation.agent_id = sqlc.arg(agent_id))+GROUP BY presence.installation_id, installation.agent_id;++-- name: ListDingTalkBotIdentitiesByWorkspace :many+-- Identity is installation-owned, so forgetting or collapsing groups cannot+-- change the connection label.+SELECT+ installation.id AS installation_id,+ installation.agent_id,+ identity.bot_name,+ identity.bot_identity_issue+FROM channel_installation installation+JOIN dingtalk_bot_identity identity ON identity.installation_id = installation.id+WHERE installation.workspace_id = sqlc.arg(workspace_id)+ AND installation.channel_type = 'dingtalk'+ AND installation.status = 'active'+ AND (NOT sqlc.arg(filter_by_agent)::boolean OR installation.agent_id = sqlc.arg(agent_id));++-- name: ForgetDingTalkGroupPresence :one+DELETE FROM dingtalk_group_presence presence+USING channel_installation installation+WHERE presence.installation_id = installation.id+ AND presence.workspace_id = sqlc.arg(workspace_id)+ AND presence.installation_id = sqlc.arg(installation_id)+ AND presence.conversation_id = sqlc.arg(conversation_id)+ AND installation.workspace_id = sqlc.arg(workspace_id)+ AND installation.channel_type = 'dingtalk'+RETURNING presence.installation_id;+-- name: DeleteDingTalkInstallationForReplacement :one-- Retires an installation when the same agent is connected with a DIFFERENT-- AppKey. A senderStaffId is scoped to one DingTalk organization, so none of the@@ -272,15 +240,23 @@ WITH retired AS (AND ci.channel_type = 'dingtalk'RETURNING ci.id),-cleared_chat_sessions AS (- DELETE FROM channel_chat_session_binding+cleared_group_presence AS (+ DELETE FROM dingtalk_group_presence+ WHERE installation_id IN (SELECT id FROM retired)+),+cleared_bot_identity AS (+ DELETE FROM dingtalk_bot_identityWHERE installation_id IN (SELECT id FROM retired)- RETURNING chat_session_id),cleared_group_routes AS (DELETE FROM dingtalk_group_routeWHERE installation_id IN (SELECT id FROM retired)),+cleared_chat_sessions AS (+ DELETE FROM channel_chat_session_binding+ WHERE installation_id IN (SELECT id FROM retired)+ RETURNING chat_session_id+),cleared_outbound_cards AS (DELETE FROM channel_outbound_card_messageWHERE 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.sqlindex 75b11e0203..de09ad197b 100644--- a/server/pkg/db/queries/workspace.sql+++ b/server/pkg/db/queries/workspace.sql@@ -115,9 +115,6 @@ 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@@ -141,6 +138,15 @@ cleared_draft_restores AS (cleared_inbound_dedup AS (DELETE FROM channel_inbound_message_dedup WHERE installation_id IN (SELECT id FROM ws_installations)),+cleared_dingtalk_group_presence AS (+ DELETE FROM dingtalk_group_presence WHERE installation_id IN (SELECT id FROM ws_installations)+),+cleared_dingtalk_bot_identity AS (+ DELETE FROM dingtalk_bot_identity WHERE installation_id IN (SELECT id FROM ws_installations)+),+cleared_dingtalk_group_routes AS (+ DELETE FROM dingtalk_group_route WHERE workspace_id = $1+),cleared_audit AS (-- Purge, don't detach: the workspace is gone and channel_inbound_audit has no-- workspace_id and no reaper, so a detached (NULL) row would be permanentlydiff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex 45dad74770..5bf5a592f0 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -498,6 +498,12 @@ WITHdeleted_sessions AS (DELETE FROM chat_session WHERE chat_session.workspace_id = $1),+deleted_dingtalk_group_presence AS (+ DELETE FROM dingtalk_group_presence WHERE workspace_id = $1+),+deleted_dingtalk_bot_identity AS (+ DELETE FROM dingtalk_bot_identity WHERE workspace_id = $1+),deleted_channel_installations AS (DELETE FROM channel_installationWHERE channel_installation.workspace_id = $1diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex 02090c8a1e..74f76c9a81 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -199,7 +199,6 @@ const (EventDingTalkInstallationCreated = "dingtalk_installation:created"EventDingTalkInstallationRevoked = "dingtalk_installation:revoked"EventDingTalkAccountBindingUpdated = "dingtalk_installation:binding_updated"- EventDingTalkGroupRouteUpdated = "dingtalk_group_route:updated"// WeCom smart-bot installation lifecycle. Same semantics as Lark /// Slack: `created` covers both first install and re-install via